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.
Related
This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 1 year ago.
I have been trying to figure out what is wrong with the below code but in vain. The following code when run throws NameError when input is not a number. The error expected is ValueError.
The except field should catch any error but does not.
print ("Enter a number")
num = input()
try:
if int(num) > 10:
print ("Number is greater than 10")
elif int(num) == 10:
print ("Number equal to 10")
else:
print ("Number is less than 10")
except:
print ("Enter valid number")
output:
Enter a number
q
Traceback (most recent call last):
File "1-try-ex.py", line 2, in <module>
num = input()
File "<string>", line 1, in <module>
NameError: name 'q' is not defined
The same code when checked on http://pythontutor.com/ gives expected behavior.
Please help to understand the issue.
Thanks in advance.
You think you're running Python 3 but you're actually running Python 2. input() in Python 2 is equivalent to eval(input()).
This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
Say I want to create a function that asks the user to input float data. The program checks if the input is float or not, if it is not, it returns to the beginning and if it is then it returns the data, bringing the function to an end. It works fine to check the data type and it does if the data is float, but if I first input invalid data and then input valid one, gives me error.
def function1():
try:
data1 = float(input("Please type in pi with its first 2 digits"))
status = 1
except ValueError:
status = 0
if status == 0:
print("Please enter a valid answer.")
function1()
else:
return data1
x = float(function1())
if x == 3.14:
print("Correct!")
else:
print("Incorrect, please try again.")
function1()
The error it gives me is:
TypeError: float() argument must be a string or a number, not
'NoneType'
Note again. This ONLY happens when I first input invalid data (such as "no") and THEN inputting valid (3.14, 2.71 etc.). Otherwise, the 'program' works fine.
You're supposed to return function1 like:
def function1():
try:
data1 = float(input("Please type in pi with its first 2 digits"))
status = 1
except ValueError:
status = 0
if status == 0:
print("Please enter a valid answer.")
return function1()
# ^^^^ Here
else:
return data1
This also makes the function recursive. When you don't return anything from a funciton, None is returned automatically.
Also you're catching the exception, so you should do the recursion from there:
def function1():
try:
data1 = float(input("Please type in pi with its first 2 digits"))
except ValueError:
print("Please enter a valid answer.")
return function1()
# ^^^^ Here
else:
return data1
This also removes the redundant status to track validity.
As an aside, Python does not have tail call optimization so you could reach the max stack size when using recursion.
You're not returning from recursive function so you get None
if status == 0:
print("Please enter a valid answer.")
return function1()
`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!
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
I am working on a collatz sequence code in python. The code should give me a sequence of numbers that end in 1. The code I have here does that when I enter a number.
try:
number = int(input('Pick a number'))
except ValueError:
print('Error! input a number')
def collatz(number):
if number % 2 == 0:
x = number // 2
return x
else:
x = 3 * number + 1
return x
while number != 1:
number = collatz(number)
print(number)
However, when I try to invoke the try and except function by entering a letter,I get the desired error message but I also get a NameError.
Traceback (most recent call last):
File "/home/PycharmProjects/collatz/collatz.py", line 14, in <module>
while number != 1:
NameError: name 'number' is not defined
Error! input a number *Desired Error Message*
I dont get this error when I remove the try and except function. I have tried defining 'name' as a global variable and also played around with the indentation but nothing seems to work. I would greatly appreciate any kind of help.
I am using python 3.6.
If your ValueError get raised, then I think you don't really define number in any other place. That's why your while loop raises a NameError.
The reason you get the NameError is because number is simply not defined. The call to int fails, thus the assignment to number never happens, you catch and print the error but then just proceed. To force the user to enter a valid number you have to repeat the prompt until the user enters the correct input.
def read_number():
while True:
try:
return int(input('Pick a number'))
except ValueError:
print('Error! Input a number')
Then, to read a sequence of numbers you do:
while True:
number = read_number()
if number == 1:
break