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")
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 2 years ago.
If the user doesn't type in multiplication, addition, ect, then a string should be printed. However, if one of these words is typed it still prints this string. I've just started with python; sorry that it's such a basic question!
print ("Multiplication, Addition, Subtraction or Division?")
type = str(input("Your choice:"))
if type != "multiplication" or "addition" or "subtraction" or "division":
print("YOU DID NOT ENTER ONE OF THE ABOVE OPTIONS.\nTRY AGAIN!")
num1 = int(input("Enter your 1st number:"))
print ("Multiplication, Addition, Subtraction or Division?")
choice = input("Your choice:")
if choice.lower() not in ("multiplication", "addition", "subtraction", "division"):
print("YOU DID NOT ENTER ONE OF THE ABOVE OPTIONS.\nTRY AGAIN!")
num1 = int(input("Enter your 1st number:"))
Also type is the built-in global name. By using this name you hide it.
The problem is on your if statement. When you are testing if a value is one of multiple options, you can use the in keyword like "test" in ["hello", "test", "123"] == true.
print ("Multiplication, Addition, Subtraction or Division?")
type = str(input("Your choice:"))
if type not in ["multiplication", "addition", "subtraction", "division"]:
print("YOU DID NOT ENTER ONE OF THE ABOVE OPTIONS.")
print("TRY AGAIN!")
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
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:
How can I read inputs as numbers?
(10 answers)
How can I check if a string represents an int, without using try/except?
(23 answers)
Closed 4 years ago.
I've written a number guessing game in Python 2.7.14 and encountered something odd:
I ask for an integer as input and check for that, but the name of the variable (here "a") is always accepted, although no other strings or characters are accepted. Isn't this an issue when the user can enter variable names even though they are not allowed?
My code is:
from random import randint
a = randint(0,10)
b = input("enter a number between 0 and 10 ")
print "you entered :", b
if type(b) != int:
print "please enter only integers"
else:
if b < a:
print "b is smaller than a"
elif b == a:
print "b is equal to a"
else:
print "b is NOT smaller than a"
print "number was", a
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 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 8 years ago.
EDIT - Apparently this is a duplicate. And while I've no doubt the core problems are answered elsewhere I think that the level is pretty blatant and thus the ability to comprehend other solutions and transpose them into my own problem is diminished. I searched before asking.
I'm just having a mess about and was trying to write a little thing with user input.
However, I'm not sure how to go about this without knowing how many iterations are needed, or having two questions?
I tried to modify it to take an if condition, which I don't really want anyway but that didn't work either :
for i in range(50):
userIn = raw_input()
urlList.append(userIn)
print 'Continue? Y/N'
ynAns = raw_input()
if ynAns == 'n' or 'N':
break
Basically I'm just trying to take user input to fill up a list and then print it out.
I also tried
import sys
listOne = []
num = int(raw_input('How many'))
for x in range(num):
listOne.append(raw_input(('Entry #' + x+1 + ' '))
print listOne
pretty basic
You need to compare ynAns with both 'n' and 'N':
if ynAns == 'n' or ynAns == 'N':
An alternative syntax:
if ynAns in ('n', 'N'):
The reason why your if statement doesn't work is that ynAns == 'n' and 'N' are two separate expressions. 'N' is always evaluated to True, so the if condition is always true.
It's basically jh314's answer, but shorter:
if ynAns.lower() == 'n':
What it does is converts ynAns to lowercase, making your code more concise.
Dont use a for loop for this, you´re restricting your app to run within a limit of 50 iterations, instead use while:
userInput = None
userInput = raw_input("Enter input (N or n to stop): ")
while(userInput not in ['N', 'n']):
urlList.append(userIn)
userIn = raw_input("Enter input (N or n to stop): ")