This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I want to be able to check that an input is an integer between 1 and 3, so far I have the following code:
userChoice = 0
while userChoice < 1 or userChoice > 3:
userChoice = int(input("Please choose a number between 1 and 3 > "))
This makes the user re-enter a number if it is not between 1 and 3, but I want to add validation to ensure that a user cannot enter a string or unusual character that may result in a value error.
Catch the ValueError:
Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value
Example:
while userChoice < 1 or userChoice > 3:
try:
userChoice = int(input("Please choose a number between 1 and 3 > "))
except ValueError:
print('We expect you to enter a valid integer')
Actually, since the range of allowed numbers is small, you can operate directly on strings:
while True:
num = input('Please choose a number between 1 and 3 > ')
if num not in {'1', '2', '3'}:
print('We expect you to enter a valid integer')
else:
num = int(num)
break
Alternatively try comparison of input in desired results, and break from the loop, something like this:
while True:
# python 3 use input
userChoice = raw_input("Please choose a number between 1 and 3 > ")
if userChoice in ('1', '2', '3'):
break
userChoice = int(userChoice)
print userChoice
Using Try/Except is a good approach, however your original design has a flaw, because user can still input like "1.8" which isn't exactly an integer but will pass your check.
Related
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 trying to make my program print(invalid input, try again) if the user types a string instead of an integer.
num_dice = 0
while True:
if num_dice < 3 or num_dice > 5 or num_dice:
num_dice = int(input("Enter the number of dice you would like to play with 3-5 : "))
print("")
print("Please enter a value between 3 and 5.")
print("")
continue
else:
break
You can simply use the isnumeric keyword to check if it is an absolute number or not.
Example:
string1="123"
string2="hd124*"
string3="helloworld"
if string1.isnumeric() is True:
#Proceed with your case.
inputs=string1
Documentation reference : https://www.w3schools.com/python/ref_string_isnumeric.asp
P.S. this will require you changing your input to string format, as isnumeric validates only string.
This below part I mean.
num_dice = str(input("Enter the number of dice you would like to play with 3-5 : "))
This question already has answers here:
Determine whether integer is between two other integers
(16 answers)
Check if numbers are in a certain range in python (with a loop)? [duplicate]
(3 answers)
Closed 4 years ago.
Let's say I want the user to input a number between 1 and 50, so I do:
num = input("Choose a number between 1 and 50: ")
But if the user inputs a number that does not fall between 1 and 50, i want it to print:
Choose a number between 1 and 50: invalid number
How can I do that?
num = input("Choose a number between 1 and 50: ")
try:
num = int(num) #Check if user input can be translated to integer. Otherwise this line will raise ValueError
if not 1 <= num <= 50:
print('Choose a number between 1 and 50: invalid number')
except ValueError:
print('Choose a number between 1 and 50: invalid number')
You need the input to be set to an integer since otherwise it would be a string:
num = int(input("Choose a number between 1 and 50: "))
Check what num has been set to:
if 1 < num < 50:
print(1)
else:
print("invalid number")
This is what I might do:
validResponse = False
while(not validResponse):
try:
num = int(input("Choose a number between 1 and 50: "))
if(1 <= num <= 50):
validResponse = True
else:
print("Invalid number.")
except ValueError:
print("Invalid number.")
This is, if you want to prompt them until a correct number has been entered. Otherwise, you can ditch the while loop and validResponse variable.
The try will run the statement until it runs into an error. if the error is specifically that the number couldn't be interpereted as an integer, then it raises a ValueError exception and the except statement tells the program what to do in that case. Any other form of error, in this case, still ends the program, as you'd want, since the only type of acceptable error here is the ValueError. However, you can have multiple except statements after the try statement to handle different errors.
In addition to the above answers, you can also use an assertion. You're likely going to use these more so when you're debugging and testing. If it fails, it's going to throw an AssertionError.
num = input('Choose a number between 1 and 50') # try entering something that isn't an int
assert type(num) == int
assert num >= 1
assert num <= 50
print(num)
You can use an if statement, but you need to assign the input to a variable first then include that variable in the conditional. Otherwise, you don't have anything to evaluate.
num = input('Choose a number between 1 and 50')
if type(num) == int: # if the input isn't an int, it won't print
if num >= 1 and num <= 50:
print(num)
By default, the input provided is going to be a string. You can call the built-in function int() on the input and cast it to type int. It will throw a ValueError if the user enters something that isn't type int.
num = int(input('Choose a number between 1 and 50'))
You could also implement error handling (as seen in Moonsik Park's and Ethan Thomas' answers).
I feel like the question is not well worded for a question, but this is what I really want:
I am writing this code where a 'user' can enter as many integers from 1 to 10 as he/she wants. Every time after the user has entered an integer, use a yes/no type question to ask whether he/she wants to enter another one. Calculate and display the average of the integers in the list.
Isn't 'while' supposed to running part of a program over and over and over again until it stops when it is told not to?
num_list = []
len()
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
It stops after the 2nd time even if the user types in 'y'. It then gives me the 'Number List: ".
Once again, you guys have been great assisting my classmates and I. Im in an introduction to Python course and we are learning about loops and lists.
One while loop is sufficient to achieve what you want.
num_list = []
again = 'y'
while again=='y':
no = int(input("Enter a number between 1 and 10: "))
if not 1 <= no <= 10:
continue
num_list.append(no)
again = input("Enter another? [y/n]: ")
print("Average: ", sum(num_list) / len(num_list))
The while loop runs as long as again == 'y'. The program asks for another number if the user inputs an integer not between 1 and 10.
Try this:
num_list = []
again = "y"
while again == "y":
try:
integer_pushed = float(input("Enter as many integers from 1 to 10"))
if integer_pushed > 0 or integer_pushed <= 10:
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print("Number list:", num_list)
else:
print('You must type in an integer between 0 and 10')
except ValueError:
print('You must type in an integer not a str')
I'm not sure why you had two different while loops, let alone three. However, this should do what you want. It will prompt the user for a number, and try and convert it to a float. If it can't be converted, it will prompt the user again. If it is converted it will check to see if it's between 0 and 10 and if it is, it will add it to the list, otherwise, it will tell the user that that's an invalid number.
This question already has an answer here:
Simple Python IF statement does not seem to be working
(1 answer)
Closed 6 years ago.
I have my first program I am trying to make using python. The IF ELSE statement is not working. The output remains "Incorrect" even if the correct number is inputted by the user. I'm curious if it's that the random number and the user input are different data types. In saying that I have tried converting both to int with no avail.
Code below:
#START
from random import randrange
#Display Welcome
print("--------------------")
print("Number guessing game")
print("--------------------")
#Initilize variables
randNum = 0
userNum = 0
#Computer select a random number
randNum = randrange(10)
#Ask user to enter a number
print("The computer has chosen a number between 0 and 9, you have to guess the number!")
print("Please type in a number between 0 and 9, then press enter")
userNum = input('Number: ')
#Check if the user entered the correct number
if userNum == randNum:
print("You have selected the correct number")
else:
print("Incorrect")
On Python 3 input returns a string, you have to convert to an int:
userNum = int(input('Number: '))
Note that this will raise a ValueError if the input is not a number.
If you are using Python 3, change the following line:
userNum = input('Number: ')
to
userNum = int(input('Number: '))
For an explanation, refer to PEP 3111 which describes what changed in Python 3 and why.
This question already has answers here:
Integers as the only valid inputs
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
In python is there a way to redo a raw input and if statement if the answer is invalid?
So for instance if you ask the user to guess 1 or 2, and they guess 3 you create the additional elif or else to tell the user that the answer is invalid and go through the raw input / if statement again?
I believe you want something like this:
# Loop until a break statement is encountered
while True:
# Start an error-handling block
try:
# Get the user input and make it an integer
inp = int(raw_input("Enter 1 or 2: "))
# If a ValueError is raised, it means that the input was not a number
except ValueError:
# So, jump to the top of the loop and start-over
continue
# If we get here, then the input was a number. So, see if it equals 1 or 2
if inp in (1, 2):
# If so, break the loop because we got valid input
break
See a demonstration below:
>>> while True:
... try:
... inp = int(raw_input("Enter 1 or 2: "))
... except ValueError:
... continue
... if inp in (1, 2):
... break
...
Enter 1 or 2: 3
Enter 1 or 2: a
Enter 1 or 2: 1
>>>
Use a while statement:
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
while x != 1 and x != 2:
print 'Invalid!'
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
This code starts off by taking the necessary input. Then, using a while loop, we check to see if x is 1 or 2. If not, we enter the while loop and ask for input again.
You could also do this:
while True:
try:
x = int(raw_input('Enter your number: '))
except ValueError:
print 'That is not a number! Try again!'
if x in [1, 2]:
break