Python exception when calculating age - python

I have a python code that ask user input for the date of birth and returns the age of the user. However, I'd like to modify the code so if the user input enter the date with the wrong format a message is shown so the user can try again. I am aware that there is the while loop for this type of tasks, but haven't been able to make it work.
import datetime as date
def calculateAge(birthDate):
today = date.datetime.today()
age = today.year - birthDate.year -((today.month, today.day) < (birthDate.month, birthDate.day))
return age
birthDate = input("Please enter your birthdate on the following format (dd/mm/yyyy)\n>>> ")
birthDate = date.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " + birthDate.strftime("%B, %Y"))
#lets print the age now
print("You are", calculateAge(birthDate), "years old")

birthDate = input("Please enter your birthdate on the following format (dd/mm/yyyy)\n>>> ")
while True:
try:
birthDate = date.datetime.strptime(birthDate, "%d/%m/%Y").date()
break
except(ValueError):
birthDate = input("Please enter your birthdate on the following format (dd/mm/yyyy)\n>>> ")
try attempts to do the function under try, which is to convert into a date. If it is in the correct format, then it will exit the while loop. However, if its in the wrong format, then it will raise a ValueError and thats what except catches and it will ask for the input again. This will continue till it exits the while loop only through keying in something in the proper format.

Related

Python 3 - functions beginners exercise

Python 3, functions.
There is the following exercise:
Write a function that asks the user to enter his birth year, first name and surname. Keep each of these things in a variable. The function will calculate what is the age of the user, the initials of his name and print them.
for example:
John
Doh
1989
Your initials are JD and you are 32.
Age calculation depends on what year you are doing the track,
you should use input, format etc.
the given answer is:
def user_input():
birth_year = int(input("enter your birth year:\n"))
first_name = input ("enter your first name:\n")
surname = input ("enter your surname:\n")
print ("your initials are {1}{2} and you are {0} years old". format(first_name[0], surname[0],2021-birth_year))
when I run this the terminal stays empty,
hope you could help,
thank you in advance!
Make sure to call your function, so that it gets executed:
def user_input():
birth_year = int(input("enter your birth year:\n"))
first_name = input("enter your first name:\n")
surname = input("enter your surname:\n")
print("your initials are {1}{2} and you are {0} years old".format(first_name[0], surname[0], 2021-birth_year))
# Call it here
user_input()
The terminal stays empty is because you did not call the function to execute it.
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("\n\nYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], 2021-birth_year))
# remember to call the function
user_input()
Small change:
You can use the DateTime module to change the year rather than the hardcoded year value.
from datetime import date
def user_input():
birth_year = int(input("Please enter your birth year: "))
surname = input("Please enter your surname: ")
first_name = input("Please enter your first name: ")
print("\n\nYour initials are {1}{0} and you are {2} years old".format(first_name[0], surname[0], date.today().year-birth_year))
# remember to call the function
user_input()

Python input function, printing

I'm trying to make a simple function where python would calculate age depending on your year input. I've tried several ways and I haven't had luck atm.
ps. sorry, I'm a newbie at this.
ame = input(" Enter your name: ")
age = input(" When were you born?: ")
print("Hello " + name + "! You are " + input (2021 - age)
import datetime
# get the year so it works all the time.
year = datetime.datetime.today().year
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
# calclute the age
age = year - int(birth_year)
print("Hello " + name + "! You are ", age)
There are other ways to print which might look more clean:
print(f'Hello {name}! You are {age}')
or
print("Hello {0}! You are {1}".format(name, age))
To make it a function:
import datetime
def age_cal(birth_year):
# get the year so it works all the time.
year = datetime.datetime.today().year
return year - int(birth_year)
if __name__ == "__main__":
name = input(" Enter your name: ")
birth_year = input(" When were you born (year) ?: ")
age = age_cal(birth_year)
print("Hello {0}! You are {1}".format(name, age))
Here is what you can do: convert age to integer, then subtract it from 2021.
ame = input(" Enter your name: ")
age = input(" When were you born (year) ?: ")
print("Hello " + name + "! You are ",2021- int(age))
Let’s go through the code sample you provided line-by-line.
name = input(" Enter your name: ")
This line creates a variable called name and assigns it to the return value of the built-in function input.
age = input(" When were you born? ")
This does the same, but for the variable age. Note that this stores a string (some characters) not an int. You’ll probably want to convert it, like this:
age = int(age)
Next, you’re trying to print:
print("Hello " + name + "! You are " + input (2021 - age)
But to figure out what to print, Python has to evaluate the return of input(2021-age). (Remember in your code that age was a string; you can’t subtract strings and ints).
You’ve got another problem here- you’re prompting and waiting for input again, but you don’t need to. You’ve already stored the user’s input in the age and name variables.
So what you really want to do is:
print("Hello, " + name + "! You are " + 2021 - age )
Now, if you wanted to be a little more concise, you could also do:
print(f"Hello, {name}! You are {2021 - age}")
You can convert input to int and format your print statement, like below.
name = input("Enter your name: ")
age = int(input("When were you born? (year): ")) # convert input to int
print("Hello {}! You are {} years old".format(name, (2021-age))) # format output
You can make a simple function with datatime like this:
from datetime import date
name = input(" Enter your name: ")
year = int(input(" When were you born?: "))
def calculateAge(year):
today = date.today()
age = today.year - year
return age
print("Hello " + name + "! You are " + str(calculateAge(year)))
This isn't a function for that you have to use def anyway this is the code
Code-
from datetime import date
todays_date = date.today()
name = input(" Enter your name: ")
dob = int(input(" When were you born?: "))
print("Hello " + name + "! You are " + todays_date.year - dob)

Python: How do I find age from an inputted date of birth and current date?

I have made a programme where the user it asked to input their date of birth as integers and then I've tried to convert the date of birth to a format to then compare to the current date which is imported. However I'm struggling to identify the different formats of date that can be used in python.
Here is my code:
from datetime import datetime
print("This programme calculates your age from your date of birth")
dd=int(input("What day were you born? "))
mm=int(input("What month were you born, enter the month number:" ))
yyyy=int(input("What year were you born? Enter the full year: "))
today = datetime.today()
b1 = dd,mm,yyyy
newdate1 = datetime.strptime(b1, "%d/%m/%Y")
age = today.year - b1.year - ((today.month, today.day) < (b1.month, b1.day))
print(age)
import datetime
#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " +
birthDate.strftime("%B, %Y"))
currentDate = datetime.datetime.today().date()
#some calculations here
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day
#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)
# some decisions
if monthVeri < 0 :
age = age-1
elif dateVeri < 0 and monthVeri == 0:
age = age-1
#lets print the age now
print("Your age is {0:d}".format(age))

In my code i want to add my password number + strings , for example 1234xyz

here is my code
name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
# do exception handling to make sure age is in integer format
age = int(age)
if age >18:
print("welcome")
#here i want to add my password number + strings
password = input("type your code now")
password = int(password)
if password==1234xyz:
print("okay")
else :
print("wrong")
if age < 18:
print("chole jao")
i want to add passwor liek 12323rtrt
You could do the error handling like follows -
name = input("Enter your name:")
print("Hello, " +name)
age = input("Please enter your age:")
# do exception handling to make sure age is in integer format
if age.isdigit() == True:
age = int(age)
if age >18:
print("welcome")
else :
print('age should be a positive integer')
In the second case, you need to know that you cannot convert a string which as alphabets into an integer. So int(password) won't work if the password has some characters. Also, you don't really need to convert the password to an integer. You can directly check/compare the user-inputted password against correct password as follows -
password = input("type your code now")
if password=='1234xyz': # note '1234xyz' which is string can directly be used and this is correct way
print("okay")
else :
print("wrong")

How to check if the user's input is valid Python

This is my exercise: get the user's first name, last name and birth year. Create initials from the name (first letter) and calculate the age of the user.
I wrote a script:
def age_name():
# var= firstName ,lastName ,year
is_running=True
firstName =input("What is your name?").lower()
while is_running==True:
if firstName.isalpha() and len(firstName)>0:
lastName = input("What is your last name?").lower()
if lastName.isalpha() and len(lastName) > 0:
year = input("What is your birth year?")
if year.isnumeric() or len(year)==4:
year=int(year)
print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year))
#print("Your initials are ",firstName[0],lastName[0],"and your age is ",str(2018-year))
else:
print("invalid year. please type your birth year")
year = input("What is your birth year?")
else:
print("invalid last name. please type your last name")
lastName = input("What is you last name?").lower()
else:
print("invalid name. please type your name")
firstName = input("What is you name?").lower()
age_name()
I've tested the code and this is what I get:
What is your name?p5
invalid name. please type your name
What is you name?peter
What is your last name?p5
invalid last name. please type your last name
What is you last name?pen
What is your last name?pen
What is your birth year?p5
invalid year. please type your birth year
What is your birth year?10
What is your last name?pen
What is your birth year?1800
Your initials are pp and your age is 218.
What is your last name?
First of all, I think my code is a bit repetitive - if someone has ideas to shorten it. Second and biggest problem - I keep getting the last name question. Where is my bug?
I think the best readable while least error prone way would be sth like below. The input lines are programmed only once each and everything is dependent on the state of response_invalid.
def age_name():
response_invalid = True
while response_invalid:
firstName = input("What is your name?").lower()
if firstName.isalpha() and len(firstName)>0:
response_invalid = False
else:
print("invalid name. please type your name")
response_invalid = True
while response_invalid:
lastName = input("What is your last name?").lower()
if lastName.isalpha() and len(lastName) > 0:
response_invalid = False
else:
print("invalid last name. please type your last name")
response_invalid = True
while response_invalid:
year = input("What is your birth year?")
if year.isnumeric() or len(year)==4:
response_invalid = False
else:
print("invalid year. please type your birth year")
year=int(year)
print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year))
However, this is the verbose variant of a very common way to implement this, which is I think the shortest, but a little rude...:
def age_name():
while True:
firstName = input("What is your name?").lower()
if firstName.isalpha() and len(firstName)>0:
break
print("invalid name. please type your name")
while True:
lastName = input("What is your last name?").lower()
if lastName.isalpha() and len(lastName) > 0:
break
print("invalid last name. please type your last name")
while True:
year = input("What is your birth year?")
if year.isnumeric() or len(year)==4:
break
print("invalid year. please type your birth year")
year=int(year)
print("Your initials are {0}{1} and your age is {2}.".format(firstName[0],lastName[0],2018-year))
How does this look?
def age_name():
firstname=input("What is your name?")
while firstname.isalpha()!=True:
print("Invalid name, enter again")
firstname = input("What is your name?")
lastname = input("What is your last name?")
while lastname.isalpha()!=True:
print("Invalid name, enter again")
lastname = input("What is your last name?")
year = input("What is your birth year?")
while len(year) != 4 and year.isdigit():
print("Invalid year, enter again")
year = input("What is your birth year?")
year = int(year)
print("First Name:",firstname,"\nLast Name:",lastname,"\nBirth Year:",year)
age_name()
That looks so much better. Thank you.
but look at the error I get when I type year whis letters:
What is your birth year?g5
ValueError: invalid literal for int() with base 10: 'g5'.
i've changed the last while operator from and to or and it works beautifully.

Categories