This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 20 days ago.
I'm trying to compare a input that the user receives that checks if the input is actually a number. Here's what I have so far:
numstring = input("Choose a number between 1 and 10")
and then to compare I have it in a method like this:
def check(a):
if int(a) == int:
print("It's a number!")
else:
print("It's not a number!")
It always prints out that it's not a number, even though it is.
Goal of this program:
I'm making a guessing game:
import random
numstring = input("Choose a number between 1 and 10")
def check(a):
if int(a) == int:
print("It's a number!")
else:
print("It's not a number!")
if abs(int(a)) < 1:
print("You chose a number less than one!")
elif abs(int(a)) > 10:
print("You chose a number more than ten!")
else:
randomnum = random.randint(1, 10)
randomnumstring = str(abs(randomnum))
if randomnum == abs(int(a)):
print("You won! You chose " + a + "and the computer chose " + randomnumstring)
else:
print("You lost! You chose " + a + " and the computer chose " + randomnumstring)
check(numstring)
Thanks for any help! The actual code works, but it just fails at checking it.
You can just use str.isdigit() method:
def check(a):
if a.isdigit():
print("It's a number!")
else:
print("It's not a number!")
The above approach would fail for negative number input. '-5'.isdigit() gives False. So, an alternative solution is to use try-except:
try:
val = int(a)
print("It's a number!")
except ValueError:
print("It's not a number!")
int(a) and int are not equal because int() returns an integer and just int with no () is a type in python2.(or class in python3)
>>> a = '10'
>>> int(a)
10
>>> int
<type 'int'>
If you're only dealing with integers then use try-except with int as others have shown. To deal with any type of number you can use ast.literal_eval with try-except:
>>> from ast import literal_eval
>>> from numbers import Number
def check(a):
try:
return isinstance(literal_eval(a), Number)
except ValueError:
return False
>>> check('foo')
False
>>> check('-100')
True
>>> check('1.001')
True
>>> check('1+1j')
True
>>> check('1e100')
True
Try to cast an input to int in try/except block:
numstring = input("Choose a number between 1 and 10")
try:
a = int(numstring)
print("It's a number!")
except ValueError:
print("It's not a number!")
If you are using python 2, consider switching to raw_input() instead of input(). input() accepts any python expression and this is bad and unsafe, like eval(). raw_input() just reads the input as a string:
numstring = raw_input("Choose a number between 1 and 10")
try:
a = int(numstring)
print("It's a number!")
except ValueError:
print("It's not a number!")
Note that raw_input() has been renamed to input() in python 3.
Also see:
Python: user input and commandline arguments
Is it ever useful to use Python's input over raw_input?
What's the difference between raw_input() and input() in python3.x?
Hope that helps.
Related
This question already has answers here:
Python Palindrome
(3 answers)
Closed 1 year ago.
I am currently struggling with a homework problem and I need some help, as I feel like I'm a bit confused. I work on creating a program that looks for palindromes within integers only. The program I've made I know will accurately identify palindromes within integers, but I cannot get the program to identify when the input is not an integer (float, bool, str, etc.). I specifically want the program to note when an integer is not the input and print "The input is not an integer" before breaking. Here is my code below:
def Palindrome(n):
return n == n[::-1]
n = input("Please enter an integer: ")
ans = Palindrome(n)
if ans == True:
print("The number " + n + " is a palindrome")
elif ans == False:
print("The number " + n + " is NOT a palindrome")
I know this is kind of basic, but everyone needs to start somewhere! If anyone could explain what I could do to create the program and understand how it works, it would be very appreciated :)
Your palindrome() function has some indentation issues.
def palindrome(n):
return n == n[::-1]
This function can basically check whether a string str is a palindrome, and not just limited to integers.
n = input("Please enter anything: ")
is_palindrome = palindrome(n)
if is_palindrome:
print(n + " is a palindrome.")
else:
print(n + " is not a palindrome.")
Output
Test case A for racecar.
Please enter anything: racecar
racecar is a palindrome.
Test case B for 123.
Please enter anything: 123
123 is not a palindrome.
When you get an input it's always a string value, so a possible solution is to modify Palindrome. First, try to cast the input to int and then print and exit if it throws a ValueException in this way.
def Palindrome(n):
try:
int(n)
except ValueError as e:
raise ValueError('The value must be an integer')
return n == n[::-1]
if __name__ == "__main__":
try:
n = input("Please enter an integer: ")
ans = Palindrome(n)
if ans == True:
print("The number " + n + " is a palindrome")
elif ans == False:
print("The number " + n + " is NOT a palindrome")
except ValueError as e:
print(str(e))
I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True
I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)
I wrote this script but it always returns the same answer ("Your guess is too high"), no matter what the user inputs. Any insight would be helpful.
import random
number = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
if type(guess == int):
print(number) # this prints the randint to show the code isn't working
while(number != 0):
if(guess > number):
print("Your guess is too high!")
break
elif(guess < number):
print("That's too low.")
break
elif(guess == number):
print("Thats's right!")
break
else:
print("Please enter a number.")
Your while loop is useless, the problem of testing the input as an int is better handled with a try/except.
All together the correct answer is in Python3 :
import random
number = random.randint(1, 10)
found = False
while not found:
try:
guess = int(input("Guess a number between 1 and 10: "))
if guess > number:
print("Your guess is too high!")
elif guess < number:
print("That's too low.")
elif guess == number:
print("Thats's right!")
found = True
except ValueError:
print("Please enter a number.")
if type(guess == int):
This isn't doing what you expect. It always returns True because it's the equivalent to bool(type(False)). First make sure to convert your input to an int
guess = int(input("Guess a number between 1 and 10: "))
and then remove this if statement:
if type(guess == int):
Your problem is that this code:
if(guess > number)
is always comparing a string to an int, so once you correct that your code will be fixed.
I have just copied and pasted your code and it seems to function mostly correctly. There are some issues with it though. First, it appears that this is written for python 2 based on the way you are using the input function. However this is bad practice as the input() function in python 2 includes an implicit call to the eval() function which could allow for arbitrary code to be run.
In python 2 the better practice would be to use guess = int(raw_input("Guess a number between 1 and 10: ")).
In python 3, raw_input() has been removed and input() replaces it. So in python 3 you would use guess = int(input("Guess a number between 1 and 10: ")).
Your final else block is also indented where it should not be, although if you revise your code to make use of the advice given above, your if...else block is no longer necessary.
That's because input returns a string in Python 3. You need to call int() to make it an integer type:
guess = int(input("Guess a number between 1 and 10: "))
You're also using the type() function incorrectly. You probably want the function isinstance(): if isinstance(guess, int):
Also, in Python, we don't need parentheses like you've used. You can simply do if guess > number:
I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.