Why is the error raised regardless of input? [duplicate] - python

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

Related

'Perfect factorial' python program [duplicate]

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.

Exception message not printing when I give a string character

`I'm trying to get this exception to trigger so I can see if python can handle when I input a string instead of an int.
I've tried changing the ValueError statement to a different type of exception such as TypeError instead of Value Error. I've also checked for syntax issues.
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this
#not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
I'm trying to get the program to print my last line shown when I input a string character, such as a (k) or something, instead it's throwing an error message.
Here's the full code that someone asked for:
u_list = []
list_sum = 0
for i in range(10):
userInput = int(input("Gimme a number: "))
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
ValueError will be thrown when failing to convert a string to an int. input() (or raw_input() in Python 2) will always return a string, even if that string contains digits, and trying to treat it like an integer will not implicitly convert it for you. Try something like this:
try:
userInput = int(userInput)
except ValueError:
...
else:
# Runs if there's no ValueError
u_list.append(userInput)
...
Add the userInput in the try-except block and check it for ValueError. If its an integer then append it to the list.
Here's the Code:
u_list = []
list_sum = 0
for i in range(10):
try:
userInput = int(input("Gimme a number: "))
except ValueError:
print("da fuq!?!. That ain't no int!")
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
I hope it helps!

Python input validation: how to limit user input to a specific range of integers? [duplicate]

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!)

Python ValueError exception - Name "a" is not defined error [duplicate]

This question already has answers here:
Python 2.7 getting user input and manipulating as string without quotations
(8 answers)
Closed 6 years ago.
I am trying to implement a try exception in Python which when inputting a char/string instead of an int, catches the exception.
However, when inputting the letter 'a' the program crashes, returning the following error:
num = input('Enter integer number: ') File "<string>", line 1, in
<module> NameError: name 'a' is not defined
This is my code:
if __name__ == '__main__': #main function
num = input('Enter integer number: ')
try:
num = int(num)
except ValueError:
print "Invalid input."
You're trying to catch a ValueError but the function is raising a NameError instead. So you're no catching it. Try:
if __name__ == '__main__': #main function
num = input('Enter integer number: ')
try:
num = int(num)
except Exception as e:
print "Invalid input: {}".format(e.message)
from the documentation input() interprets the given input.
https://docs.python.org/2/library/functions.html?highlight=input#input
so if you give the input as "a" it would interpret it as a string and proceed.
since you are give the value as a, it expects a variable named a.
if you directly want to use the user input, as suggested in the comments by #Lafexlos use raw_input instead.

Check if input is positive integer [duplicate]

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.

Categories