How to check if the user's input is valid Python - 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.

Related

Python exception when calculating age

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 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()

How can I print a word from an array?

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")

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")

An error appears saying a function was referenced before it was assigned but only when I enter the year above 2005 or 2004

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.

Categories