Function which asks for age - python

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

Related

Trying to control the user's input to strictly a positive number only

I am trying to control the user's input using exception handling. I need them to only input a positive number, and then I have to return and print out that number.
I have to send a message if the user puts in non-number and I have to send a message if the user puts in a number less than 1. Here is what I have:
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
boolChoice = False
except ValueError:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
elif l < 0:
print("Your number is not positive")
print("Try again")
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
My program works fine until a negative integer gets inputted. It doesn't print the message and then goes through the loop again, it just returns and prints back the negative number, which I don't want. How can I fix this? Thank you.
You can use try...except to check if its an integer or letters
def input_validation(prompt):
while True:
try:
l = int(input(prompt))
if l<0: #=== If value of l is < 0 like -1,-2
print("Not a positive number.")
else:
break
except ValueError:
print("Your input is invalid.")
print("Try again")
return l
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()
try
def input_validation(prompt):
boolChoice = True
while boolChoice == True:
try:
l = input(prompt)
x = int(l)
if x < 0:
print ("Your input is a negative number\n Please enter a postive number")
elif x == 0:
print("Your input is zero\n Please enter a postive number ")
else:
boolChoice = False
except Exception as e:
print("Not a valid input")
if l.isalpha() == True:
print("Your input is not a number")
elif l.isalnum() == True:
print ("Your input is not completely a positive number")
else:
print(f"Failed to accept input due to {e}")
print("Try again")
continue
return x
def main():
x = input_validation("Enter a positive number: ")
print (x)
main()

Passing 'ValueError' & 'continue' in a function and call it

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

How can I create a 'while'-exception loop?

I am working on a small coding challenge which takes user input. This input should be checked to be a digit. I created a "try: ... except ValueError: ..." block which checks once whether the input is a digit but not multiple times. I would like it to basically checking it continuously.
Can one create a while-exception loop?
My code is the following:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than
one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
uinput = int(input("You entered not a digit. Please try again: "))
flag = True
while flag:
try:
uinput = int(input("Please enter a number: "))
while uinput <= 0:
uinput = int(input("Number is negative. Please try again: "))
else:
flag=False
for i in range(2, uinput):
if (uinput % i == 0):
print("Your number is a composite number with more than one divisors other than itself and one.")
break
else:
print(uinput, "is a prime number!")
break
except ValueError:
print('Wrong input')
Output :
(python37) C:\Users\Documents>py test.py
Please enter a number: qwqe
Wrong input
Please enter a number: -123
Number is negative. Please try again: 123
123 is a prime number!
I add flag boolean to not make it repeat even when the input is correct and deleted input in except because it would ask 2 times.
If you press Enter only, the loop terminated:
while True:
uinput = input("Please enter a number: ")
if uinput.strip()=="":
break
try:
uinput=int(uinput)
except:
print("You entered not a digit. Please try again")
continue
if uinput<=0:
print("Not a positive number. Please try again")
continue
for i in range(2, uinput):
pass; # put your code here

Python Nested Loop Enter Value and Confirm Answer

I'm trying to write a simple block of code that has a user enter an interest rate. The number must be 0 or greater, any other value will be rejected, the user must be polled until a valid number is input. If the number is greater than 10%, the user must be asked if he/she really expects an interest rate that high, if the user replies in the affirmative, the number is to be used, otherwise the user will be asked to input the value again and the above checks will be made. I'm having trouble understanding the nested loop aspect of this. Any help is greatly appreciated!
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
except ValueErrror:
print("Entered value is not a number! ")
except KeyboardInterrupt:
print("Command Error!")
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
main()
do it all in the try, if inp > 10, ask if the user is happy and break if they are, elif user input is within threshold just break the loop:
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
if interest_rate > 10:
confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
if confirm =="y":
break
elif 0 <= interest_rate < 10:
break
except ValueError:
print("Entered value is not a number! ")
return interest_rate
main()
Three things jump out:
1) ValueErrror should be ValueError
2) You don't handle the user input on the final test
3) You probably want to change the < 10 to be <= 10
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
can be:
if 0 <= interest_rate <= 10:
break
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
except the last line must take the response and process it.
Your else was not related to an if
Your elif was unnecessary after break
Make the print("Entered interest rate is greater than 10%. Are you sure? (y/n): ") an input
answer = int(input("Are you sure?"))
if answer == "y":
break
I usually prefer to break down the solution and validation into different modules. Please check the below code to see how I break them down. So it is easy when it comes to debugging and testing.
def validating_user_input(num):
"""
"""
return num > 0
def getting_user_input():
"""
"""
user_input = int(raw_input("Enter the number that is greater than 0: "))
return user_input
def confirming_choose():
"""
"""
try:
user_choose = int(raw_input("Can you confirm your input? [0|1]? "))
except ValueError:
return False
return user_choose == 1
def main():
"""
"""
initial_cond = True
while initial_cond:
user_input = getting_user_input()
if validating_user_input(user_input):
if user_input > 10:
confirmation = confirming_choose()
while not confirmation:
getting_user_input()
#do you operating here
initial_cond = False
else:
print "It is not valid input."
if __name__ == "__main__":
main()

Python: Trying to validate input such as a phone number to ensure it is 10 numerical characters and prompt and error if not

I want the program to remove ()'s and -'s which could possibly be entered when some one enters their phone #. I also want to make sure that is is 10 numerical characters long if not produce a loop.
p = raw_input("Please enter your 10 digit Phone Number")
def only_numerics(p):
seq_type= type(p)
return seq_type().join(filter(seq_type.isdigit, p))
p = only_numerics(p)
valid_phone = False
while not valid_phone:
if p > "0000000000" and p < "9999999999" and len(p) == 10 :
print "You have entered " + p
valid_phone=True
else:
print "You have entered an invalid choice"
If I type in less than 10 numbers I get repeating of the else print command. I would like it to go back to raw input ("please enter your 10 digit Phone Number"). Is there any way to do this?
Apart from setting the "raw_input" inside the loop as James pointed out, you might be interested in using regular expressions and make your code more beautiful:
import re
phone_re = re.compile(r'\d{10}$')
def only_numerics(p):
seq_type= type(p)
return seq_type().join(filter(seq_type.isdigit, p))
valid_phone = False
while not valid_phone:
p = raw_input("Please enter your 10 digit Phone Number: ")
p = only_numerics(p)
if phone_re.match(p):
print "You have entered " + p
valid_phone=True
else:
print "You have entered an invalid choice"
It loops back to the print statement because you define p outside of the while loop. Changing this will fix the looping issue:
valid_phone = False
while not valid_phone:
p = raw_input("Please enter your 10 digit Phone Number")
def only_numerics(p):
seq_type= type(p)
return seq_type().join(filter(seq_type.isdigit, p))
p = only_numerics(p)
if p > "0000000000" and p < "9999999999" and len(p) == 10 :
print "You have entered " + p
valid_phone=True
else:
print "You have entered an invalid choice"
def val_number(input_num):
valid_num=re.findall(r'\d+',input_num)
if len(valid_num[0])>10:
print('You have entered more than 10 digits')
else:
return(valid_num)
This python code validates an 11 digit mobile number:
valid = True
mobile_number = str(input("What is your mobile number? "))
while len(mobile_number) != 11 or mobile_number[0] != "0" or mobile_number[1:].isdigit() == False:
mobile_number = str(input("Please enter a valid mobile number: "))
valid = False
print("Your mobile number is valid")
while(True):
try:
phone_number=int(input("please enter the phone number:no spaces in between: \n"))
except ValueError:
print("mismatch")
continue
else:
phone=str(phone_number)
if(len(phone)==10):
break
else:
print("10 digits please ")
continue

Categories

Resources