Let me explain with a quick bit of code.
Code:
choice = raw_input("Do you like pineapple? Y/N: ")
if choice == "y".lower() or choice == "ye".lower() or choice == "yes".lower():
print("Sammmmeee")
else:
print("Nani! You criminal!")
How could I make it so instead of doing:
if choice == "y".lower() or choice == "ye".lower() or choice == "yes".lower():
it automatically accepts, "y", "ye" or "yes" without needing to do or so much?
First of all, you shouldn't be applying lower to the right hand side, which is a constant and already lowercase. You should be applying it to the variable input:
choice = raw_input(...).lower()
There are a number of ways to check for the match you are looking for. The easiest is to use startswith:
if 'yes'.startswith(choice):
Another way would be to explicitly check for containment in a set or tuple:
if choice in ('y', 'ye', 'yes'):
This is only necessary for cases that don't fit into a simple method check, like if you wanted to add ok to the list of options.
If you wanted to have multiple function checks, you could use any with a generator expression:
if any(f(x) for f in ('yes'.startswith, 'ok'.startswith)):
All of the tests here are properly short circuiting, just like your original expression.
You can use startswith to achieve this:
if 'yes'.startswith(choice.lower().strip()):
print('You said "yes"!')
This will case-insensitively match exactly 'y', 'ye', and 'yes':
choice = raw_input("Do you like pineapple? Y/N: ")
if choice.lower() == 'yes'[:len(choice)]:
print("Sammmmeee")
else:
print("Nani! You criminal!")
You can just pick the first character of the input to compare with 'y'. Also note that you need to make the input lowercase. So the code becomes:
choice = raw_input("Do you like pineapple? Y/N: ")[0]
if choice.lower() == "y":
print("Sammmmeee")
else:
print("Nani! You criminal!")
Related
# Dice Rolling Random Number and Guessing Game
import random
user_choice = 'y'
while user_choice != 'N' or user_choice != 'n':
print(random.randint(1,6))
user_choice = input("Do you want to continue: ")
print("You are exited")
The logic of the while condition is wrong.
Your loop runs forever, because the character will ALWAYS be different from one of the suggested characters. So the while condition is always true as at least one of the two parts is always true.
You want something like
while user_choice != 'N' and user_choice != 'n':
...
If you want to go for a more 'pythonic' way, query a set in the while condition:
while user_choice not in {'n', 'N'}:
....
There are many similar ways with tuples, lists, ... to express the condition other than querying every character individually in a chain of 'and' conditions.
As far as coding is concerned, the question is answered already, but I'd like to offer a more deep explanation of why the answer was the and operation instead of or.
The question "Did the user enter neither 'n' or 'N'?" can be expressed using Boole Algebra as
Answer = Not('n' or 'N'), and using the DeMorgan theorem this can be rewritten as
Answer = Not('n') and Not('N')
In your code, the first of the two ways to write this would look like
while !(user_choice == 'N' or user_choice == 'n'):
I hope this clears up the logic behind your question.
This is my Python code:
choice = (input("Are you signed up? (y/n) "))
print(choice)
while True:
if choice != "y" or choice != "n":
choice = (input("Are you signed up? (y/n) "))
print(choice)
else:
break
I want the program to keep asking the user for input until they input "y" or "n". The problem is it never accepts the input, even if they do input "y" or "n".
When I print what they inputted (that's a real word) it says that it's "y" or "n" but it still won't accept it.
I've been using Python for some time now and I'm just trying something out today but I can't figure this out for some reason, I feel like it's something simple and obvious but I'm stupid to notice it.
Can someone explain this to me, please? Thank you.
Since choice cannot be 'y' and 'n' at the same time, one of choice != 'y' and choice != 'n' is always true.
You need to use and, not or.
Well, suppose the user inputs "y".
Your code will enter the while True loop and encounter the if condition
Is choice != "y" or choice != "n", where choice == 'y', true or false?
"y" != "y" is false, check the next condition
"y" != "n" is true, so the whole condition is true
Ask for input again
Goto (1)
Same thing happens for choice == "n".
However, you want a condition that says not (choice == "y" or choice == "n"). According to De Morgan's laws:
not (a or b) == (not a) and (not b)
So your code translates into:
(not (choice == "y")) and (not (choice == "n"))
=> choice != "y" and choice != "n"
As everyone has already pointed out the problem in your code, I am just adding a cleaned version of your code.
while True:
choice = (input("Are you signed up? (y/n) "))
if choice == "y" or choice == "n":
print(f"Your choice is {choice}")
break
You need and instead of or in this case.
if choice != "y" and choice != "n":
or if you prefer you can do
if not (choice == "y" or choice == "n"):
You can also do:
if choice not in ("y", "n"): # THIS ONE IS PROBABLY THE BEST
or because these are each 1-character you can do:
if choice not in "yn":
You can also do:
if choice not in "Randy!" or choice in "Rad!":
I'm learning python and I found myself lost trying to create a an if statement that should be true if the user input y or yes.
#!/usr/bin/env python3
user_input = input('Would you like to go on?')
lowui = user_input.lower
if lowui == ('y' or 'yes'):
print('You want to go on')
else
print('See you later, bye')
The problem is that it becomes true only if I type y but not for yes. If I remove the parenthesis it becomes always false. Ok, I can do a workaround like
if lowui == 'y' or lowui == 'yes':
but I was wondering if there is any trick that don't force me to write so many times tha variable.
Thank you in advance.
Change it to
if lowui in ('y', 'yes'):
Also this is wrong:
lowui = user_input.lower
it should be:
lowui = user_input.lower() # Actually call the lower function
What I'm trying to do is that, if I ask a question only answerable by Yes and
No, I want to make sure that yes or no is the answer. Otherwise, it will stop.
print("Looks like it's your first time playing this game.")
time.sleep(1.500)
print("Would you like to install the data?")
answer = input(">").lower
if len(answer) > 1:
if answer == "no":
print("I see. You want to play portably. We will be using a password system.")
time.sleep(1.500)
print("Your progress will be encrypted into a long string. Make sure to remember it!")
else:
print("Didn't understand you.")
elif len(answer) > 2:
if word == "yes":
print("I see. Your progress will be saved. You can back it up when you need to.")
time.sleep(1.500)
else:
print("Didn't understand you.")
First:
answer = input(">").lower
should be
answer = input(">").lower()
Second, len(answer) > 1 is true for both "no" and "yes" (and anything larger than one character, for that matter). The elif block will never be evaluated. Without modifying significantly the logic of your current code, you should do instead:
if answer == 'no':
# do this
elif answer == 'yes':
# do that
else:
print("Didn't understand you.")
Something like:
if word.lower() in ('yes', 'no'):
would be the simplest approach (assuming case doesn't matter).
Side-note:
answer = input(">").lower
Is assigning a reference to the lower method to answer, not calling it. You need to add parens, answer = input(">").lower(). Also, if this is Python 2, you need to use raw_input, not input (In Python 3, input is correct).
I'm new to python and am taking a class so far my program looks like:
if choice=="1":
def addition():
print("You are doing addition. X+Y=Z")
X = int(input("Enter X:"))
Y = int(input("Enter Y:"))
sum = X + Y
print ("your total is:")
print (sum)
Well = "y"
while Well == "y":
again = input("Would you like to go again? (y/n)")
if again == "y":
addition()
if again == "n":
project()
else:
print("sorry re-enter choice")
it asks if I wan to go again before showing the actual addition part. how do I fix this? Thanks for your help :)
Lots of ways, but you could put your addition() function at the top like this:
Well = "y"
while Well == "y":
addition()
again = input("Would you like to go again? (y/n)")
if again == "n":
project()
if again not in ("n", "y"):
print("sorry re-enter choice")
Just add a flag which changes from false to true on first run, so that you don't see the "again" statement on first run.
A few points:
You shouldn't use sum as a variable name. It is a Python built in.
Look at what variable you use for your loop check, you will notice it quickly.
I think it would make more sense to ask if you want to go again at the end of the loop, after you do your stuff:
while loop_condition:
#do_your_stuff:
bla bla bla
#see if you should go again
bla bla = raw_input("Do you want to go again")
In fact, 99% of the time your while loops will follow this pattern (check condition, run body of loop, update condition) and if you are doing things in a different order (like iupdating the condition before running the body) its usually a sign you might be doing something wrong.