This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I am just messing around with Python trying to do a simple guessing program. The code inside my if statement never runs, and I can't figure out why. I've tried printing both variables at the end, and even when they're the same, the comparison never resolves to true. I've also tried just setting y as 2 and guessing 2 as the input, and it still doesn't work.
import random
x = input("Guess a number 1 or 2: ")
y = random.randint(1,2)
if x==y:
print("yes")
The problem here is that x is a string and y is an int:
x = input("Try a number ") # I chose 4 here
x
'4'
x == 4
False
int(x) == 4
True
input will always return a string, which you can convert to int using the int() literal function to convert that string into the required value
Related
This question already has answers here:
Comparing a string to multiple items in Python [duplicate]
(3 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 2 years ago.
Hi I'm new to python and I'm having some trouble with logical operators. In the code I want the user to input one of three choices A, S , or D and reject anything else. The problem Im having is that when I input A, S, or D it still prints out Invalid Input.
guess = input("Lower (a), Same (s), Higher (d): ")
if guess != "a" or "s" or "d":
print ("Invalid Input")
Im using python version 2.7 if that helps
Here or short circuit operator compares the two True values + the condition guess != 'a' (Because non empty values evaluate to True in Python), so use not in:
guess = input("Lower (a), Same (s), Higher (d): ")
if guess not in ['a','s','d']:
print("Invalid Input")
This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
Closed 2 years ago.
I'm trying to learn some Python and had a question about a really small "program" I made as a test.
a = input()
print(a)
b = '10'
if a == b:
print("Yes")
else:
print("No")
This works, but my question is why does the value for b have to have the quotes around it.
Python input() function will by default take any input that you give and store it as a string.
why does the value for b have to have the quotes around it
Well, it doesn't have to have quotes. But if you need the condition to evaluate to True, then you need quotes. So, since a is a string, you need to have b = '10' with the quotation mark if you need a == b to evaluate to True.
If your input is an integer, you could also do a = int(input()) and in this case, b=10 would work as well. Simple !
So, the following two can be considered to be equivalent in terms of the result they give -
a = input()
b = '10'
if a == b:
print("Yes")
else:
print("No")
AND
a = int(input())
b = 10
if a == b:
print("Yes")
else:
print("No")
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
The value of input() is a string, therefore you must compare it to a string. Everyone learning programming starts off with many questions, and it is the only way to learn, so do not feel bad about it.
In python default input type is string. if you want it as int you must cast it:
a = int(input()) #change type of input from string to int
print(type(a))
b = 10
if a == b:
print("Yes")
else:
print("No")
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I want to make a program where I need to check the input of the user
so, the question is How do I check the input value, if it`s a string or an integer?
Here's some experimental code that didn't work:
a = 10
print(type(a))
if (a==10):
print("aaaaa")
else:
if(type(a)== "<class 'int'>"):
print("12345")
You can do it in the following way:
a = 10
if type(a) is int:
print("Yes")
else:
print("No")
input() will always return string, i.e type(input()) will be str
from my understanding, you want to validate input before proceeding further
, this is what you can do
foo = input()
if not foo.isdigit():
raise ValueError("Enter a valid integer")
foo = int(foo)
this will not work for a negative number, for that you can check if foo startswith "-"
if foo.lstrip("-").isdigit():
multiply_by = -1 if foo.startswith("-") else 1
foo = multiply_by * int(foo.lstrip("-"))
and if you want to check type of variable
a = 10
if isinstace(a, int):
pass
This question already has answers here:
Two values from one input in python? [duplicate]
(19 answers)
Closed 2 years ago.
I want to use one line to get multiple inputs, and if the user only gives one input, the algorithm would decide whether the input is a negative number. If it is, then the algorithm stops. Otherwise, the algorithm loops to get a correct input.
My code:
integer, string = input("Enter an integer and a word: ")
When I try the code, Python returns
ValueError: not enough values to unpack (expected 2, got 1)
I tried "try" and "except", but I couldn't get the "integer" input. How can I fix that?
In order to get two inputs at a time, you can use split(). Just like the following example :
x = 0
while int(x)>= 0 :
try :
x, y = input("Enter a two value: ").split()
except ValueError:
print("You missed one")
print("This is x : ", x)
print("This is y : ", y)
I believe the implementation below does what you want.
The program exits only if the user provides a single input which is a negative number of if the user provides one integer followed by a non-numeric string.
userinput = []
while True:
userinput = input("Enter an integer and a word: ").split()
# exit the program if the only input is a negative number
if len(userinput) == 1:
try:
if int(userinput[0]) < 0:
break
except:
pass
# exit the program if a correct input was provided (integer followed by a non-numeric string)
elif len(userinput) == 2:
if userinput[0].isnumeric() and (not userinput[1].isnumeric()):
break
Demo: https://repl.it/#glhr/55341028
This question already has answers here:
python: while loop not checking the condition [closed]
(3 answers)
Closed 8 years ago.
In the following code:
def foo(n):
print "n value before if:",n #displays given num
if n <= 2:
print "n value:",n #not displayed even n is less than 2
num = raw_input()
print foo(num)
The if statement does not execute on giving inputs less than 2 for num.
So, why is if statement not executing?
raw_input returns a string, you are then comparing it to an integer.
Try converting it to an int:
num = int(raw_input())