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$): ")
Related
def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue
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
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()
I need to be able to prompt the user to enter an empty string so it can check if the answer is correct. but every time I do that I can error saying invalid literal for int()
so I need to change my user_input so it can accept int() and strings(). how do I make that possible ?
# program greeting
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
#print("Enter coins that add up to 81 cents, one per line.")
import sgenrand
#prompt the user to start entering coin values that add up to 81
while True:
total = 0
final_coin= sgenrand.randint(1,99)
print ("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
while total <= final_coin:
user_input = int(input("Enter next coin:"))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
if total > final_coin :
print("Sorry - total amount exceeds", (final_coin))
elif total < final_coin:
print("Sorry - you only entered",(total))
else:
print("correct")
goagain= input("Try again (y/n)?:")
if goagain == "y":
continue
elif goagain == "n":
print("Thanks for playing ... goodbye!" )
break
Store the value returned by input() in a variable.
Check that the string is not empty before calling int().
if it's zero, that's the empty string.
otherwise, try int()ing it.
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