Contributors: Chris Chen, Evan Han
This program uses the year of birth inputted by the user to calculate the age of the user.
Sample Inputs and Output:
Explanation of Code
Line 6: Import the datetime built-in Python module to get the current date.
Line 9: Using the "today" variable store the value that is returned from the "today()" method in "datetime.date".
Line 12: Set the variable "today_year" the year stored in the "today" variable from line 9 accessed from "today.year".
Line 15: A "while" loop is used to continuously iterate until a valid year input is provided. "while True:" indicates that the loop will run indefinitely until a "break" statement is encountered within the program, terminating the loop.
Line 17: Prompt the user to enter their name using the "input()" function. Then store the inputted value in the variable "name".
Line 19: Prompt the user to enter their year of birth using the "input()" function. It is then converted from a "string" datatype to an "integer" using the "int()" function. Then store the inputted value in the variable "yearOfBirth".
Line 22: Employing an "if statement", verify if the user inputted a positive value. This condition is assessed using the comparison statement: "yearOfBirth > 0". If true, proceed to execute the code within the "if block".
Line 24: Define the variable "age," which will store the resulting age. "today_year - yearOfBirth" calculates the age of the user using today's year.
Line 27: Employing a nested "if statement", verify if the user inputted a year of birth smaller than or equal to today's year. This condition is assessed using the comparison statement: "age >= 0". If true, proceed to execute the code within the "if block".
Line 29: Utilizing the "print()" function, the variable "name", and "age" output a message concatenated with the calculated age of the user.
Line 32: The "break" statement is used to exit the while loop defined in Line 15.
Line 33: An "else" statement accompanies the "if statement" from Line 27 to handle tasks if the condition evaluates to false.
Line 35: Output an error message using the "print()" function and variable "today_year" (to show the user today's year), prompting the user to input a valid parameter for the variable "yearOfBirth". Since there is no "break" statement here, the code will return to Line 17 to prompt for input again.
Line 36: An "else" statement accompanies the "if statement" from Line 22 to handle tasks if the condition evaluates to false.
Line 38: Output an error message using the "print()" function, prompting the user to input a valid parameter for the variable "yearOfBirth". Since there is no "break" statement here, the code will return to Line 17 to prompt for input again.
Give the program a try here: https://replit.com/@ChrisChen42/Age-Calculator?v=1