Python 3 - functions beginners exercise - python

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

Related

Check for correct user input without exiting loop

I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks
You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.

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)

My python code is not executing a function (program) I coded

I created a program that asks a bunch of input questions and prints out the following line, for example, Marc Gibbons is a 103 year old male. He was born in Ottawa and his SIN # is 1234567890.
But when I keep getting an error.
from datetime import datetime
def main():
name = input('Please enter your name:')
sex = input('Please enter your sex, Male (M) or Female (F) or Non-Binanry(N):')
birthday = input ('Enter your date of birth in YYYY-mm-dd format:')
birthday1 = datetime.strptime(birthday, '%Y-%m-%d')
age = ((datetime.today() - birthday1).days/365)
place = input('What City were you born in:')
try:
sin = int(input('What is your sin number:'))
except ValueError:
print('Error:Please enter a number')
print(f'{name} is a {age} years old {sex}. He was born in {place} and her SIN # is {sin}')
# Do not edit below
if __name__ == '__main__': main()
just make sure that print(f'{name} is a {age} years old {sex}. He was born in {place} and her SIN # is {sin}') indented right inside the function
move the print state into the function. The current indentation means main() (containing your name var) is not in the same scope as the print function:
from datetime import datetime
def main():
name = input('Please enter your name:')
sex = input('Please enter your sex, Male (M) or Female (F) or Non-Binanry(N):')
birthday = input ('Enter your date of birth in YYYY-mm-dd format:')
birthday1 = datetime.strptime(birthday, '%Y-%m-%d')
age = ((datetime.today() - birthday1).days/365)
place = input('What City were you born in:')
try:
sin = int(input('What is your sin number:'))
except ValueError:
print('Error:Please enter a number')
# Indent here to inside the function
print(f'{name} is a {age} years old {sex}. He was born in {place} and her SIN # is {sin}')
Hope it helps

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.

How to create a dictionary that I can access throughout the program?

I'm creating a address book program, and need to have a dictionary that I can add too, edit, and delete, as well as pickle. What would be the best way to create it so it is accessible by all the functions? I currently have the dictionary in the addon function but wouldn't it reset if I were to call the dictionary to another function?
My code so far (not including the menuModule)
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def appendDictionary():
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
listX = [personFirstName, personEmail, personStreetAddress, personCityState, personPhone]
addressBook = {personLastName: listX}
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
Try using lists. One list for each of the variables because if you try to store them as a tuple and then add them into a master list you will not be able to or it will be hard to charge them and edit them. Here is an example of storing the data:
nameList.extend(john)
emailList.extend(john#gmail.com.uk)
john_index = len(nameList)
Give each person an index to help you file their information so if our list looked like [jane#live.com, sam#wenston.com, john#gmail.com.uk] johns data is going to be the last in the list because we just entered it in position 3 on the list and the length function returns 3 so you know where johns data is stored and if you were to add more data it would stack up accourdingly.
here is an example of getting it back out of the list and editing it:
print nameList[john_index]
print emailList[john_index]
emailList[john_index] = new_value
I hope you understand :)

Categories