I have just started Python and I am attempting a simple exercise. It's to end a program on a user specified input and then finding the oldest age from a set of ages entered. I got the user input but having issues with the oldest age aspect. Where am I going wrong? I think I may not be 100% on the "None" aspect. Here is code below:
largest = None
while True:
name = str(input("What is your name? enter Yvonne to end program."))
if name.strip() != 'Yvonne':
age = int(input("Please enter your age"))
elif name.strip() == 'Yvonne':
if largest is None or largest < age:
largest = age
print("Oldest age is: ", largest)
break
The output I get is the wrong number being selected as the oldest:
You’ve got your test for largest in the wrong place:
largest = None
while True:
name = str(input("What is your name? enter Yvonne to end program."))
if name.strip() != 'Yvonne':
age = int(input("Please enter your age"))
if largest is None or largest < age:
largest = age
else:
print("Oldest age is: ", largest)
break
Related
I don't know what is the error of my code can anyone help me to fix this code.
age = ""
while int(len(age)) == 0:
age = int(input("Enter your age: "))
print("Your age is " + age)
You wanted a string for age but you transformed this age into an integer inside your loop :)
You can write :
age = ""
while age == "":
age = input("Enter your age: ")
print("Your age is " + age)
In Python, "" and 0 (and values like None and empty containers) are considered "falsey". Not necessarily the same thing as False but logically treated like False.
So you can simplify your while loop:
age = ""
while not age:
age = input("Enter your age: ")
print("Your age is " + age)
You cast age to be an int inside of your while loop, while using the len(age) as the comparison.
int does not have a length.
You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.
age = ""
while len(age) == 0:
age = input("Enter your age: ")
print("Your age is " + age)
I have been set a task and it is the following, I was wondering would my code would work?
write a program to ask for a name and an age.
when both values have been entered, check if the person is the right
age to on an 18-30 holiday(they must be over 18 and under 31
name = input("What is your name? ")
age = int(input("How old are you ? "))
if 18 <= age < 31:
print("Hello",name,"welcome to this holiday.".format(name))
else:
print("Sorry",name,"you are not old enough to go on this holiday. ")
well actually it works but you don't need the format part
name = input("What is your name? ")
age = int(input("How old are you ? "))
if age >=18 and age <31:
print("Hello",name,"welcome to this holiday.")
else:
print("Sorry",name,"you are not old enough to go on this holiday. ")
if you want to use format you can do this
print("Hello {name} welcome to this holiday.".format(name=name))
Code works perfect, but you have a useless format
Just use format, not the , part.
name = input("What is your name? ")
age = int(input("How old are you ? "))
if 18 <= age < 31:
print("Hello {name} welcome to this holiday.".format(name))
else:
print("Sorry {name} you are not old enough to go on this holiday.".format(name))
Or if you don't like to do format
name = input("What is your name? ")
age = int(input("How old are you ? "))
if age >=18 and age <31:
print("Hello",name,"welcome to this holiday.")
else:
print("Sorry",name,"you are not old enough to go on this holiday. ")
I am trying to check user inputs to ensure that:
1) It is a floating number
2) Floating number is not negative
I am trying to put above 2 checks into a function and call it after user has input into a variable.
However, I cant seem to put 'ValueError' & 'continue' in a function that I can call. Is this possible?
I have tried below code, but it repeats from the top when I key in 't' for salCredit, or any of the next few variables. The code will work if I were to repeat 'ValueError' & 'continue' for every variable. I'm just wondering if there is a shorter way of doing do?
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
#checkInputError(accBal)
salCredit = float(input("Enter your Salary: "))
#checkInputError(salCredit)
creditCard = float(input("Credit Card Spend (S$): "))
#checkInputError(creditCard)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
interestCalculator()
Expected results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Salary: 500
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a valid number.
Enter your Salary: 500
Current results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Account Balance:
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a positive number.
Credit Card Spend (S$):
You could create a function that continues prompting for input until a valid float is input
def get_float_input(prompt):
while True:
try:
user_input = float(input(prompt))
if user_input < 0:
print("Please enter a positive number.")
continue # start the while loop again
return user_input # return will break out of the while loop
except ValueError:
print("Please enter a valid number.")
mul_AccBal = get_float_input("Enter your Account Balance: ")
salCredit = get_float_input("Enter your Salary: ")
creditCard = get_float_input("Credit Card Spend (S$): ")
Try this:
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
invalid = True
while invalid:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
salCredit = float(input("Enter your Salary: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
creditCard = float(input("Credit Card Spend (S$): "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
return True
return False
interestCalculator()
you need to break you while loop if all the input is successful (also note that the continue at the end of the while loop is unnecessary). and if you want to have a validation for every number separately, you could do something like this:
def get_float(message, retry_message="Please enter a valid number."):
while True:
try:
ret = float(input(message))
if ret >= 0:
return ret
else:
print(retry_message)
except ValueError:
print(retry_message)
def interestCalculator():
mul_AccBal = get_float("Enter your Account Balance: ")
salCredit = get_float("Enter your Salary: ")
creditCard = get_float("Credit Card Spend (S$): ")
Ok so i need to ensure that a phone number length is correct. I came up with this but get a syntax error.
phone = int(input("Please enter the customer's Phone Number."))
if len(str(phone)) == 11:
else: phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
You can't have
if:
else:
Because the else, being inside the first if block, doesn't have a corresponding if.
It should be:
if:
this
else:
that
You may try this to be asking for the phone number until it is correct:
phone = ""
while len(str(phone)) != 11:
phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
If you want to check also that the input is a number and not text, you should also trap the exception raised by int in that case, for example:
phone = ""
while len(str(phone)) != 11:
try:
phone = int(input("Please enter the customer's Phone Number."))
except ValueError:
phone = ""
phonumber.append(phone)
I need this to ask for an age, but if the age is under 11 or over 100 to reject it and to also reject anything but integers. If a number put in is out of the given range or isn't an integer I need it to loop back and ask again
def PlayerAgeFunction():
VALID = True
while VALID == True:
PlayerAge = int(raw_input('ENTER YOUR AGE: '))
if PlayerAge == type(int):
VALID = False
elif PlayerAge != type(int):
print 'THAT IS NOT A NUMBER.'
return PlayerAge
I looked on here for an answer before but what I found didn't help.
please can someone help, thank you.
def prompt_age(min=11, max=100):
while True:
try:
age = int(raw_input('ENTER YOUR AGE: '))
except ValueError:
print 'Please enter a valid number'
continue
if not min <= age <= max:
print 'You are too young/old'
continue
return age