This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 9 months ago.
I am trying to make it so that if either input value is not a number, it will print an error message saying that an integer must be entered. And whenever no error is caught, it will multiply x by y. How would I do this?
Here is what I have so far:
def main():
try:
x = int(input("Please enter a number: "))
y = int(input("Please enter another number: "))
except:
It's good practice to not have empty except as it makes debugging difficult
def main():
try:
x = int(input("Please enter a number: "))
y = int(input("Please enter another number: "))
print(x*y)
except ValueError:
print("An integer must be entered. ")
main()
you could try this:
def main():
while True:
try:
x = int(input("Please enter a number: "))
y = int(input("Please enter another number: "))
print(x*y)
break
except:
print("Please input an integer")
while True:
try:
x, y = map(int, input("Please enter two number: ").strip().split())
return x * y
except:
print("two integer must be entered")
Try, except, finally is the most pythonic way of doing this. Note that the code below will only raise an error if the value entered isn't a base 10 integer (which is probably what you want, but worth noting).
try:
x = int(input("Please enter a number: "))
y = int(input("Please enter another number: "))
except ValueError:
print("Entered values must be a base 10 integer")
finally:
print(x*y)
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 completely new to python and I just completed the first python project in the book. However, I am trying to improve my code so that the program will continue running until the user enters a valid integer. Currently if a user provides an input that's not an integer, the program just says 'Please enter an integer' and exits. How do I achieve this? I have been trying for hours but is still unable to get to a conclusion.
#! python3
def collatz(number):
if (number % 2) == 0:
result = number // 2
print(result)
return(result)
else:
result = (3 * number) + 1
print(result)
return(result)
try:
givenNumber = int(input('Enter a number: '))
while givenNumber != 1:
givenNumber = collatz(givenNumber)
except ValueError:
print('Please enter an integer.')
You can wrap your logic inside a while loop:
while True:
try:
givenNumber = int(input('Enter a number: '))
# break here if condition True
except ValueError:
print('Please enter an integer.')
I'm not sure it related to python programming specific, but try to learn from the exampls as this one:
def collatz(number):
if (number % 2) == 0:
result = number // 2
print(result)
return(result)
else:
result = (3 * number) + 1
print(result)
return(result)
givenNumber = None
while not isinstance(givenNumber,int):
givenNumber = input('Enter a number: ')
try:
givenNumber = int(givenNumber)
except ValueError:
print("this is not an integer number")
givenNumber = collatz(givenNumber)
output for example:
Enter a number: 3.2
this is not an integer number
Enter a number: 2
1
This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I am working my way through Python for Everyone and I am stuck at this junction. To my eye I have stated that the ValueError is only to be raised if 'num' is anything other than a integer. However when I run the code the error is raised everytime regardless of input. Can anyone nudge me in the right direction?
Extensively googled but I'm not entirely too sure what specifically I should google for...
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num != int : raise ValueError
elif num == "done" : break
except ValueError:
print("Error. Please enter an integer or type 'done' to run the program.")
quit()
print("Maximum", largest)
print("Minimum", smallest)
The code always raises ValueError even when the input is an integer.
This line checks if the inputted string is literally equal to the builtin type int:
if num != int : raise ValueError
Other problem is that the input() function always returns a string. So if you want to raise a ValueError when the user inputs anything but a number, simply do:
inputted = input("Enter a number: ")
num = int(inputted) # raises ValueError when cannot be converted to int
If you want to check if the string entered can be converted into an int, just try it:
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = int(num)
except ValueError:
continue
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
Beginner here, looking for info on input validation.
I want the user to input two values, one has to be an integer greater than zero, the next an integer between 1-10. I've seen a lot of input validation functions that seem over complicated for these two simple cases, can anyone help?
For the first number (integer greater than 0, I have):
while True:
try:
number1 = int(input('Number1: '))
except ValueError:
print("Not an integer! Please enter an integer.")
continue
else:
break
This also doesn't check if it's positive, which I would like it to do. And I haven't got anything for the second one yet. Any help appreciated!
You could add in a simple if statement and raise an Error if the number isn't within the range you're expecting
while True:
try:
number1 = int(input('Number1: '))
if number1 < 1 or number1 > 10:
raise ValueError #this will send it to the print message and back to the input option
break
except ValueError:
print("Invalid integer. The number must be in the range of 1-10.")
Use assert:
while True:
try:
number1 = int(input('Number1: '))
assert 0 < number1 < 10
except ValueError:
print("Not an integer! Please enter an integer.")
except AssertionError:
print("Please enter an integer between 1 and 10")
else:
break
class CustomError(Exception):
pass
while True:
try:
number1 = int(raw_input('Number1: '))
if number1 not in range(0,9):
raise CustomError
break
except ValueError:
print("Numbers only!")
except CustomError:
print("Enter a number between 1-10!)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I need to check whether what the user entered is positive. If it is not I need to print an error in the form of a msgbox.
number = input("Enter a number: ")
###################################
try:
val = int(number)
except ValueError:
print("That's not an int!")
The above code doesn't seem to be working.
Any ideas?
while True:
number = input("Enter a number: ")
try:
val = int(number)
if val < 0: # if not a positive int print message and ask for input again
print("Sorry, input must be a positive integer, try again")
continue
break
except ValueError:
print("That's not an int!")
# else all is good, val is >= 0 and an integer
print(val)
what you need is something like this:
goodinput = False
while not goodinput:
try:
number = int(input('Enter a number: '))
if number > 0:
goodinput = True
print("that's a good number. Well done!")
else:
print("that's not a positive number. Try again: ")
except ValueError:
print("that's not an integer. Try again: ")
a while loop so code continues repeating until valid answer is given, and tests for the right input inside it.