Python 3.3.3 Code Help. Calories remaining - python

print("Are you male or female?")
gender = input()
print("How old are you?")
age = input() ``
print("How many calories have you eaten today?")
calories = input()
if age in range(10-15) and gender == (Male):
print(2230 - calories)
This is the beginning of a code I have been trying to write where someone enters their gender, age and calories that they have eaten. I have been given data by my teacher that shows the amount of calories that each age group and gender should be eating. You then minus the calories they have eaten with the value they should be eating depending on their age and gender. It is very simple so the only age groups included are 11-14 and 15-18. The questions all run fine, but I can't get the main part of the code to run. It is on Python 3.3.3

You need to make following changes to your code.
print("Are you male or female?")
gender = input().lower()
print("How old are you?")
age = int( input() )
#convert input to int
print("How many calories have you eaten today?")
calories = int( input() )
#convert input to int
if age in [ x for x in range(10,15) ] and gender == "male":
print(2230 - calories)

You've got quite a few issues in your code. One, when you try to compare the value you get as age/calories, you're not converting them to ints first, and you can't compare an int and a string. Also, gender == (Male) compares the variable gender to the variable Male.
Here's a cleaned up version:
print("Are you male or female?")
gender = input()
while True:
try:
age = int(input("How old are you?"))
except ValueError:
print('Please enter a number for your age')
continue
else:
break
while True:
try:
calories = int(input("How many calories have you eaten today?"))
except ValueError:
print('Please enter a number for your calories eaten today')
continue
else:
break
if (10 < age < 15) and gender == 'male':
print(2230 - calories)

Related

Python: how to code a "response" based on user input when given multiple options?

I am new to Python and writing a simple program that is basically just an interactive conversation. I am asking the following question:
What is your name?
What is your gender?
What is your favorite color?
What is your birth year?
Do you have any pets?
etc.
The idea is to create as many response variables for each question as I can. For example: for "what is your gender?" if the user enters male, I want the response to be "Nice to meet you dude!", and if the user enters female I want the response to be "Nice to meet you miss!"
I would also like for the question "What is your birth year" to be met with a response that says You're "age"? You are so old!" (or something similar).
Below is what I have so far:
name = input('What is your name? ')
print('Hi ' + name + '!')
gender = input('What is your gender? ')
is_male = True
if is_male:
print('Nice to meet you, dude!')
else:
print('Nice to meet you, miss!')
favorite_color = input('What is your favorite color? ')
print(favorite_color + '? I love ' + favorite_color)
birth_year = input('What is your birth year? ')
age = 2021 - int(birth_year)
print(age + '? You are so old! ')
pets = input('Do you have any pets? ')
Any thoughts?
Thanks in advance!
I've found two bugs. Here, is_male is always True, so you'll always get the "dude" statement. And in case of age, age is int, so you can't concatenate int and str. Instead you can use fstring. Your corrected code:
name = input('What is your name? ')
print('Hi ' + name + '!')
gender = input('What is your gender? ')
if gender.lower()=="male" or gender.lower()=="m":
print('Nice to meet you, dude!')
else:
print('Nice to meet you, miss!')
favorite_color = input('What is your favorite color? ')
print(favorite_color + '? I love ' + favorite_color)
birth_year = input('What is your birth year? ')
age = 2021 - int(birth_year)
print(f'{age}? You are so old! ')
pets = input('Do you have any pets? ')
You have to convert an integer to string using str() when you concatenate a string with an integer.
age = 2021 - int(birth_year)
print('Your ' +str(age) + '? You are so old! ')
So you did most of it but you took an input
gender
but you did not use it
here:
is_male = True
if is_male:
this is_male is always true, you should read the input there instead of hardcoding it and give the user choices here like [M/F]
then you can continue like this
if gender == "M":
You might be looking for the elif statement like the following:
is_male = False
is_female = False
birth_year = input('What is your birth year? ')
age = 2021 - int(birth_year)
if age < 16:
print("Hello youngster.")
elif 16 <= age < 30:
print(r"Don't trust anyone over 30!")
elif 30 <= age < 50:
print("Metallica rules!")
else:
print("Take a nap. You deserve it.")
male_list = ["Bob", "Don","Joshua", "Cary", "Sachith" ]
female_list = ["Linda", "Tina","Janice", "Grace", "Stevie Nicks" ]
name = input('What is your name? ')
if name in male_list:
is_male = True
elif name in female_list:
is_female = True
if is_male:
print(f"Dude! Good to see you again {name}.")
elif is_female:
print(f"Good to see you again {name} my lady.")
else:
print(f'Nice to meet you {name}, we have not met.')
favorite_color = input('What is your favorite color? ')
print(f"{favorite_color} ? I love {favorite_color}")

Code is giving an "Output is too large" when printing

here is the code=
def main():
print("Enter your age: ")
age= float(input())
while age >= 0:
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
and here is the problem I am trying to solve:
Create a program that begins by reading the ages of all of the guests in a group from the user, with one age entered on each line. The user will enter -1 to indicate that there are no more guests in the group. Then your program should display the admission cost for the group with an appropriate message. The cost should be displayed using two decimal places. Use the following sample run for input and output messages.
You need to move the prompt for input into the loop, otherwise age never changes within the while, creating an infinite loop.
def main():
age = 1
while age >= 0:
print("Enter your age: ")
age = float(input())
if (age<= 2.00) :
print("The guest whose age is",age,"is admitted without charge.")
elif ((age>= 3.00) and (age<= 12.00)):
print("A(n)",age," year old will cost $14.00 dollars for admission.")
elif (age>=65.00) :
print("A(n)",age,"year old will cost $18.00 dollars for admission.")
else :
print("A(n)",age,"year old will cost $23.00 dollars for admission.")
print("End of guest list")
main()
You never update age after its initial value and so the while loop continues forever, printing a line for each iteration.
You need to put a
age = float(input())
as the last line of the while loop.

Having user input take string and int? (Python)

prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active:
age = input(prompt)
age = int(age)
if age == 'quit':
active = False
elif age < 3:
print("Your ticket is $5")
elif age >= 3 and age < 12:
print("Your ticket is $10")
elif age >= 12:
print("Your ticket is $15")
This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?
I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is $5")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.
If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.
prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)
while True:
if user_input == 'quit':
break
age = int(user_input)
if age < 3:
price += 5
elif age < 12:
price += 10
else:
price += 15
print(f"Your ticket is ${price}")
user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")

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.

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