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.
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()
Im trying to print the email of the student, in the while loop at the bottom im also trying to input the students email but I cannot figure how to do it correctly.
Code:
array1 = []
numstudents = int(input("How many students are in the class?: "))
for i in range (numstudents):
studentname,studentemail,dayofbrith,monthofbrith,yearofbrith = input("Enter the student name, the
student's email and the date of birth in the form 'name, email, day of birth, month of birth, year
of birth' : ").split("")
array1.append(studentname+studentemail+dayofbrith+monthofbrith+yearofbrith)
if studentname == "stop":
print("")
break
else:
print("")
print(array1)
while True:
email = input("From which student's email you want: ")
if email any in array1[0]:
print("")
print(array1[1])
students = []
numstudents = int(input('How many students are in the class?: '))
for _ in range(numstudents):
print("Please enter the following: ")
print("The student's name, The student's email, day of birth, month of birth, year of birth")
students.append(input().split())
target = input("Which studen't email you want: ")
for i in students:
if i[0] == target:
print(f"The student's email is {i[1]}")
Try if this is what you want
Ah, definitely a problem for a dictionary.
dict1= {}
numstudents = int(input("How many students are in the class?: "))
for _ in range (numstudents): #As nk03 correctly points out - we don't need to carry the iterator, so can use an _ instead
studentname,studentemail,dayofbirth,monthofbirth,yearofbirth = input("Enter the student name, the student's email and the date of birth in the form 'name,email,day of birth,month of birth,year of birth' : ").split(",")
if studentname == "stop":
break
else:
dict1[studentname] = {'email':studentemail, 'dOB':dayofbirth, 'mOB':monthofbirth, 'yOB':yearofbirth}
while True:
name = input("From which student's email you want: ")
if name in dict1:
print(dict1[name]['email'])
else:
print(name + " not found in dict")
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")
x = 2
while x>1:
from random import randint
import time
fn = input("Hello, what is your first name?")
while any (ltr.isdigit() for ltr in fn):
fn = input("Sorry an integer was entered, please try again")
firstname = (fn[0].upper())
ln = input("Hello, what is your last name?")
while any (ltr.isdigit() for ltr in ln):
ln = input("Sorry an integer was entered, please try again")
lastname = (ln.lower())
def main():
dob = input("Please enter the year you were born")
if dob > ("2005"):
main()
elif dob < ("2004"):
main()
else:
def mob():
if dob == ("2005"):
age = 11
elif dob == ("2004"):
month = input("Please enter the first three letters of the month you were born")
while month not in ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul","Aug","AUG","aug","Sep","SEP","sep","Oct","OCT","oct","Nov","NOV","nov","Dec","DEC","dec"):
month = input("Sorry that was incorrect, please enter the first three letters of the month you were born")
if month in ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
age = 12
elif month in ("Aug","AUG","aug"):
day = input("Please input the day you were born")
while day not in("31","30","29","28","27","26","25","24","23","22","21","20","19","18","17","16","15","14","13","12","11","10","9","8","7","6","5","4","3","2","1"):
day = input("Please input the day you were born")
if day == ("28","27","26","25","24","23","22","21","20","19","18","17","16","15","14","13","12","11","10","9","8","7","6","5","4","3","2","1"):
age = 12
elif day in ("29","30","31"):
age = 11
else:
age = 12
else:
age = 11
else:
age = 11
usernames = []
age = int(age)
age2 = age + randint(1,9)
age2 = str(age2)
print("Thank you for taking the time to enter your details, your username is now being generated")
time.sleep(1)
print("Generating...")
time.sleep(2)
username = (dob[2]+''+dob[3]+''+firstname+''+lastname+''+age2)
print("This is your username:" +''+username)
usernames.append(username)
age = str(age)
with open("Import Usernames.txt", "w") as text_file:
print("The usernames are: {}".format(usernames), file=text_file)
mob()
main()
An error only appears when I enter a year higher than 2005 or lower than 2004 but I don't know why, my question is, what have I done wrong?
This is the error that pops up:
UnboundLocalError: local variable 'mob' referenced before assignment
This whole programs is structured wrong...
Anyway, mob is declared only inside the else scope and is called right after the if-elif-else statements.
You should declare it in each these scopes, or right before them.
Beside that, I really suggest you read about Python identation.