This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
So I'm creating a part of my program that raises a error when the user doesn't input a integer. Below is my code...
try:
pw_length_ask = int(raw_input("How long would you like your password to be? "))
final_pw_length = pw_length + int(pw_length_ask.strip())
print("Pass length set to " + str(final_pw_length))
except ValueError:
print("You must enter a number.")
int(raw_input("How long would you like your password to be? "))
It works great until the user is asked to enter a number again...
ValueError
It just throws a ValueError then crashes. So how do I make it so that instead of giving the Value Error it repeats the question until the user gives correct input?
You could put it in a while loop, like this:
while True:
try:
pw_length_ask = int(raw_input("How long would you like your password to be? "))
final_pw_length = pw_length + int(pw_length_ask)
print("Pass length set to " + str(final_pw_length))
break
except ValueError:
print("You must enter a number.")
The error likely came from the input you placed in the except block.
Related
This question already has answers here:
Recursive function does not return specified value
(2 answers)
Closed last month.
Issue is when I test my error handling, entering the unexpected inputs multiple times and then proceeding to enter the acceptable number of lines to bet on the return is recived as "None" the variable seems to not stay stored or is somehow over written. Any Ideas?
I would place the other half of the code but am forced to type everything due to company policies. I apologize for any inconvenience, I thank everyone for ther time in viewing this post.
MAX_LINES = 3
def get_number_of_lines():
try:
while True:
lines = ("Enter the number of lines to be on (1-" + str(MAX_LINES) + ")? ")
if lines.isdigit:
lines = int(lines)
if 1 <= lines <= MAX_LINES:
break
else:
print("Enter a valid number of lines.")
return lines
except ValueError:
print("Please enter a number. ")
get_number_of_lines()
def main():
lines = get_number_of_lines()
print(lines)
Expected the number entered 1-3 to be printed from the return line even if moved from and to the except statment.
Add return before get_number_of_lines(). Otherwise your function will return None.
print("Please enter a number")
return get_number_of_lines()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I am working on a Paycheck calculator as a little side project for my portfolio and I have it so that users can input their own information (i.e. pay rate, hours worked, shift differentials, etc.) and parts of my code have inputs for variables:
payrate = float(input("What is your current payrate? $"))
When the code is run it asks the user to enter a value for their pay, but if they enter $20 instead of 20, I get:
ValueError: could not convert string to float: '$20'
How can I optimize my code so that it either ignores the $ when a user inputs something other than a float or it gives a rejection message to the user that I can write out myself in plain English so they know what to do?
Thank you!
Github link in case anyone wants to check it out for themselves (warning: still a massive WIP... so be gentle)
You an define a method called isfloat:
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
payrate = input("What is your current payrate? $")
if isfloat(payrate):
payrate = float(payrate)
# Do some math
else:
print("Please enter a number.")
exit()
print(payrate)
Something like this should do what your question asks:
while True:
s = input("What is your current payrate? $")
try:
payrate = float(s)
break
except ValueError:
print("Couldn't parse you input as a number. Please try again")
print(f"Thanks, payrate is {payrate}")
The loop keeps going until a float is successfully parsed. Each time a parse fails (in other words, each time our attempt to convert the string s to a float raises an exception), it prints an informational message in the except block.
This question already has answers here:
Restrict inputs to only integer in python and display error message
(2 answers)
How to protect my python code when a user inputs a string instead of an integer?
(3 answers)
Closed 11 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
var=int(input("Enter anything ==>"))
if(var%2==0):
print(var," is a Even number")
elif((var>="a" and var<="z") or (var>="A" and var<="Z")):
print(var," is String")
print("Enter a number to find it is even or odd")
else:
print(var," is a Odd number")
OUTPUT
C:\Users\HP\OneDrive\Desktop\All Desktop
apps\Python>python input.py Enter an enter code everything ==>6 6 is a Even
number
C:\Users\HP\OneDrive\Desktop\All Desktop apps\Python>python
input.py Enter anything ==>sdsd Traceback (most recent call
last): File "C:\Users\HP\OneDrive\Desktop\All Desktop
apps\Python\input.py", line 5, in
var=int(input("Enter anything ==>")) ValueError: invalid literal for int() with base 10: 'sdsd'
#if the user enters anything like any alphabet or special character, then how can we show msg to the user that the input is invalid or its
an alphabet or a special character or an integer or about specific
data type
==> var=int(input("Enter anything ==>"))
==> #var=input("Enter anything ==>")
Incorrect Code -->
Incorrect Output -->
Correct code using exception handling-->
Correct output-->
The simplest way is try/except:
var = input("Enter anything ==>")
try:
if int(var) % 2:
print(f"{var} is an odd number")
else:
print(f"{var} is an even number")
except ValueError:
print(f"{var} is not a number")
If you want to re-prompt the user when they enter something that's not a number, put the whole thing in a while loop and break it when they enter a valid number.
while True:
var = input("Enter anything ==>")
try:
if int(var) % 2:
print(f"{var} is an odd number")
else:
print(f"{var} is an even number")
break
except ValueError:
print(f"{var} is not a number")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am a beginner in python and made a couple of programs, one of the same things I see, is that when ever I make a code like this
do = int(input("Enter number >"))
I accidentally type a letter, I want to be able to give like a wrong input message and try again, but python would always detect the difference in variable container.
You can catch ValueError:
success = False
while not success:
try:
do = int(input("Enter number >"))
success = True
except ValueError:
print("Wrong input, please try again")
I would suggest having a validation function. You can then use this function in other Python programs in the future.
def validate_int(inp):
try:
int(inp)
return True
except Exception:
print('Invalid input')
return False
This function will return true or false depending on whether a number has been entered.
You can then call the function like this:
inp = input('Enter number >')
while validate_int(inp) == False:
inp = input('Enter number >')
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I have this code:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
phone = int(input("Enter your telephone no. : "))
I want the user to enter their telephone number. But if they type anything else apart from integers an error message comes up saying that you can only type integers. What I want to do is to loop this section of the code so that every time the user enters a non-integer value the error message comes up. So far all this code does is, it prints the error message only for the first time. After the first time if the user enters a non-integer value the program breaks.
Please provide a not too complicated solution...I'm just a beginner.
I'm thinking you're meant to use a while loop but I don't know how?
I believe the best way is to wrap it in a function:
def getNumber():
while True:
try:
phone = int(input("Enter your telephone no. : "))
return phone
except ValueError:
pass
You can do it with a while loop like this
while True:
try:
phone = int(input("Enter your telephone no. : "))
except ValueError:
print("You must enter only integers!")
else: # this is executed if there are no exceptions in the try-except block
break # break out of the while loop