Python Input Never Equals an Integer

Python Verifying if input is int and greater than 0

You need to convert input to an integer and then check that value. Since the user may input garbage, you have to handle the integer conversion by catching a value exception.

def get_amount():
while True:
amount = input("Enter amount: ")
try:
val = int(amount)
if val >= 0:
break
else:
print("Amount can't be negative, try again")
except ValueError:
print("Amount must be a number, try again")
return val

How can I check if string input is a number?

Simply try converting it to an int and then bailing out if it doesn't work.

try:
val = int(userInput)
except ValueError:
print("That's not an int!")

See Handling Exceptions in the official tutorial.

How to check if the input string is an integer

To check if the input string is numeric, you can use this:

s = input()
if s.isnumeric() or (s.startswith('-') and s[1:].isdigit()):
print('mission successful!')
else:
print('mission failed!')

In Python, checking if a string equals a number will always return False. In order to compare strings and numbers, it helps to either convert the string to a number or the number to a string first. For example:

>>> "1" == 1
False
>>> int("1") == 1
True

or

>>> 1 == "1"
False
>>> str(1) == "1"
True

If a string can not be converted to a number with int, a ValueError will be thrown. You can catch it like this:

try:
int("asdf")
except ValueError:
print("asdf is not an integer")

Why does this input to int does not work properly?

seems you are reading books with python2, but you have installed python3. In python2, input equals to eval(raw_input(prompt)), that's why when you input 2 * x, it evaluates the value of the expression and assign it to y.

In python3, input just get user input as strings, not to eval that as an expression, you may need explicitly eval, which is a bad practice and dangerous:

In [7]: x=2

In [8]: y=eval(input('input Y:'))

input Y:3*x

In [9]: y
Out[9]: 6

All in all, use: raw_input in py2, input in py3, never use eval (or input in py2) in your production code.

Understanding bools in Python

It is actually quite simple. All inputs from the user are considered as string values by python. In python, you can only compare a string to string, integer to integer and so on...

You could do this as well

    a = int(input())
print(a)
b = 10
if a == b:
print("Yes")
else:
print("No")

Over here int() converts the value you enter to an integer. So you don't need quotes for the variable b

How does my input not equal the answer?

I am assuming you are using python3.

The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.

string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')

Now you have the input as a integer and you can compare it to a

Edited Code:

import random
import operator

ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a

def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)

askQuestion(generateQuestion())

Python | Expecting type INT, but if STR entered?

Casting a string to an integer will only work if the string looks like an integer.

Anything else will raise a ValueError.

My suggestion is to catch this ValueError and inform the user appropriately.

try:
question1 = int(input("Enter a number: "))
except ValueError:
print("That's not a number!")
else:
print("Congratulations - you followed the instructions")

Asking the user for input until they give a valid response

The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you're satisfied.

When Your Input Might Raise an Exception

Use try and except to detect when the user enters data that can't be parsed.

while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")

Implementing Your Own Validation Rules

If you want to reject values that Python can successfully parse, you can add your own validation logic.

while True:
data = input("Please enter a loud message (must be all caps): ")
if not data.isupper():
print("Sorry, your response was not loud enough.")
continue
else:
#we're happy with the value given.
#we're ready to exit the loop.
break

while True:
data = input("Pick an answer from A to D:")
if data.lower() not in ('a', 'b', 'c', 'd'):
print("Not an appropriate choice.")
else:
break

Combining Exception Handling and Custom Validation

Both of the above techniques can be combined into one loop.

while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue

if age < 0:
print("Sorry, your response must not be negative.")
continue
else:
#age was successfully parsed, and we're happy with its value.
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")

Encapsulating it All in a Function

If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don't have to retype it every time.

def get_non_negative_int(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
continue

if value < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
return value

age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

Putting It All Together

You can extend this idea to make a very generic input function:

def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
if type_ is not None:
try:
ui = type_(ui)
except ValueError:
print("Input type must be {0}.".format(type_.__name__))
continue
if max_ is not None and ui > max_:
print("Input must be less than or equal to {0}.".format(max_))
elif min_ is not None and ui < min_:
print("Input must be greater than or equal to {0}.".format(min_))
elif range_ is not None and ui not in range_:
if isinstance(range_, range):
template = "Input must be between {0.start} and {0.stop}."
print(template.format(range_))
else:
template = "Input must be {0}."
if len(range_) == 1:
print(template.format(*range_))
else:
expected = " or ".join((
", ".join(str(x) for x in range_[:-1]),
str(range_[-1])
))
print(template.format(expected))
else:
return ui

With usage such as:

age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))

Common Pitfalls, and Why you Should Avoid Them

The Redundant Use of Redundant input Statements

This method works but is generally considered poor style:

data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
print("Sorry, your response was not loud enough.")
data = input("Please enter a loud message (must be all caps): ")

It might look attractive initially because it's shorter than the while True method, but it violates the Don't Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It's a SyntaxError just waiting to happen.

Recursion Will Blow Your Stack

If you've just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.

def get_non_negative_int(prompt):
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
return get_non_negative_int(prompt)

if value < 0:
print("Sorry, your response must not be negative.")
return get_non_negative_int(prompt)
else:
return value

This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you're underestimating the ingenuity of fools!



Related Topics



Leave a reply



Submit