Else not coming into effect in small program - python

I've tried to make a program that randomizes meals and outputs a random dish. The only problem is, when it first asks you if you want a dish it returns a dish no matter what the response it. Any help appreciated.
print('Random Dinner Dish?')
response = input()
while True:
if response == 'Yes' or 'yes' or 'Y' or 'y':
print(dinner[random.randint(0,len(dinner) - 1)])
break
else:
print('Goodbye')
break
I'm expecting it to print Goodbye and stop the program if some form of yes isn't used.

The result of response == 'Yes' or 'yes' or 'Y' or 'y' is always truthy, so the else-block is unreachable.
You probably meant
if response in {'Yes', 'yes', 'Y', 'y'}:
or will return its left side if it is truthy, otherwise it returns its right.
So False or 'yes' returns 'yes'.

Related

Checking input against a list in python - why does one way work while the other doesn't?

Started learning python a few days ago and was doing a task with simple yes/no inputs and doing different things with the while loop depending no whether the user wants to continue using the program or not.
The whole program is fairly small so hope it's alright to post the entirety of its code here. This is what worked for me:
import random
print("=====================================")
print("I Add Numbers and Tell You the Sum v2")
print("=====================================")
while True:
rand1 = random.randint(1, 100)
rand2 = random.randint(1, 100)
result = rand1 + rand2
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()
again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()
validyes = ["yes", "y"]
validno = ["no", "n"]
if again in validyes:
print("Sure thing!")
print()
elif again in validno:
print("Okay. See you!")
break
else:
print("That's not a valid response. The program will now exit.")
break
While the relevant code that didn't work as expected was this, to do with checking the user input against the valid list:
valid = ["yes", "y", "no", "n"]
if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break
else:
print("That's not a valid response. The program will now exit")
break
The former would run just fine, while the latter will print "Sure thing" regardless of what the user inputs. Why is that the case?
On that front, I'm happy to hear any other tips you guys might have with regards to making the rest of the code better. Eager to hear from and take part in this community!
You have to show what all the string what they are comparing to
if again == "yes" or again == "y":
print("Sure thing")
elif again == "no" or again == "n":
print("Okay bye")
break
else:
print("That's not a valid response. The program will now exit")
break
Also a tip is to use "\n" for a new line. The \n will not be shown
Old:
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}")
print()
New:
print(f"I'm adding {rand1} and {rand2}. If you add them together,the result would be {result}\n")
Last is that for the lower and strip function u can use it in the same line were u get your input
Old:
again_input = input("Would you like to try again? (Y/N) ")
again = again_input.lower().strip()
New:
again = input("Would you like to try again? (Y/N) ").lower().strip()
In the second case you're using the OR operand wrong and that's why it is always printing Sure thing. Here you can take a look and understand it better.
To make the code better, i would suggest keeping the valid list with all valid inputs, and checking for yes or no using the if again in valid method, but playing with what is and isn't valid inputs.
This is how or works
operation: x or y result: if x is false, then y, else x
Explanation:
valid == "yes" will be false for obvious reason because you are comparing a list to a string. When the first condition is false operator or goes to evaluate next condition which is just "y" and will always be true(you can confirm it using bool("y")) so that's why it's always printing "Sure thing".
You use this:
if valid == "yes" or "y":
print("Sure thing")
elif valid == "no" or "n":
print("Okay bye")
break
So in the first condition you check if (valid == "yes") or ("y"), but not if valid == ("yes" or "y"). Non-empty string is always True, when you use it as bool, so the first condition is always True. If you want to do somwthing like this, you can use tuples (it's like lists, but you cant edit it): if valid in ("yes", "y")
valid is a list, so valid will never equal to "yes", so it just goes to "y", which will always equal true. You need to check if "yes" or "y" is in valid:
if "yes" in valid or "y" in valid:
print("Sure thing")
elif "no" in valid or "n" in valid:
print("Okay bye")
break
Of course, with this code it will always print "Sure thing" because valid includes all the options.

While loop with if/elif/else statement

I have just started learning Python and I have some issues with the while loop.
instruction_yes_no = ""
while instruction_yes_no.lower() != "y" or "n":
instruction_yes_no = input("Do you want to see the instruction? Please write 'Y' or 'N'\n")
if instruction_yes_no.lower() == "y":
print("You are gonna lose even if you read the instructions...")
print("\n")
time.sleep(1)
instruction()
elif instruction_yes_no.lower() == "n":
print("Do you think you are better than me? I will beat you faster since you have not read the instructions")
time.sleep(1)
else:
print("You mortal...you have not chosen a valid input. Type or 'Y' or 'N'")
time.sleep(1)
break
Basically I would like to obtain the following:
1) If the user inputs 'y', the instruction() function is called (THIS WORKS)
2) If the user inputs 'n', it prints ""Do you think you are better than me?..." (THIS WORKS)
3) If the user does not type either 'y' or 'n', I would like to keep looping until the user insert or 'y' or 'n'.
HOWEVER this is not working.
I am not understanding why. This is how I think it should work:
At the beginning the variable instruction_yes_no is set to ""
It enter the loop because instruction_yes_no != than 'y' or 'n'
Now, instruction_yes_no assumes the value that the user inputs
If the user does not input either 'y' or 'n' it should keep looping, but is does not.
If the user does not input either 'y' or 'n' it should keep looping, but is does not
Because you have the break after the if-elif-else. So it will break in any case.
Move that break inside the if block (when instruction_yes_no.lower() == "y").
Oh, this is a classic common error:
while instruction_yes_no.lower() != "y" or "n":
It's the same as
while (instruction_yes_no.lower() != "y") or True:
You want this instead:
while instruction_yes_no.lower() != "y" and instruction_yes_no.lower() != "n":
Or maybe this, it's shorter :)
while instruction_yes_no.lower() not in ["y", "n"]:

python if elif diffucltys

I am using a very simple and basic if elif in python but it only will give me the same result no mater what my input is.
answer = input('Do you like christmas? ')
if answer == 'no' or 'No':
print('Your so uncool, just leave, this is a place for festive people you
heartless monster')
elif answer == 'yes' or 'Yes':
print('Your pretty cool, you can stay, just dont get drunk on the eggnog and
make out with the dog...')
elif 'brit' or 'Brit' in answer:
print('I was gunna be mean to brit, but its christmas and I am not allowed
because a fat man in a red suit will reck me')
else:
print('MAKE UP YOUR MIND, YOU SUCK')
the outputs are place holders but at the moment all I get when I run this is the the print for the no answer, weather I answer no yes or anything else...
edit: I see now that in the question my indenting looks really terrible, that isn't how I wrote it but that is just from posting it here, please assume that indentation is correct.
You are getting this because your first if statement is actually being parsed like this:
if (answer == 'no') or ('No'):
Which means if either answer == 'no' or 'No' is considered "truthy", then the statement will go ahead. Any non-empty string in python is considered to be true so you will always get True in your first statement.
bool('')
# will output False
bool('No')
# will output True
If you actually want to perform this, you've got to run the comparison every time...
if answer == 'no' or answer == 'No':
However, there are some cleaner ways of doing this, such as
answer.lower() == 'no'
# or, if you want lots more examples
answer in ['no', 'No', 'NOPE', 'Not at all', 'Never']
Would recommend reading up
Your problem is with the if's statements:
answer = 'yes'
if answer == 'no' or 'No':
1. ^ (this is saying, 'yes' == 'no' or 'No')
2. ^ (this is saying, False or 'No')
3. ^ (this is saying, False or True)
4. ^ (this is saying True)
In python strings are truthy, meaning that they are interpreted as true in boolean statements.
So your correct statement (and for the others):
answer = 'yes'
if answer == 'no' or answer == 'No':
1. ^ (this is saying, 'yes' == 'no' or 'yest == ''No')
2. ^ (this is saying, False or False)
3. ^ (this is saying False)
So that's it! Oh, another tip, you can compare any type of no/yes this way
answer = str.lower(input('Do you like christmas? '))
if answer == 'no':
^ Even if the user types 'No', it will be turned into 'no'.

Dice simulator input - Python

I am trying to figure out why any input starting with 'y' keeps this game going....looking at the code it appears only 'y' or 'yes' should keep it going but I could enter 'yensdg', 'yyyy' etc and it still loops.
Any ideas? Thanks
from random import randint
repeat = True
while repeat:
print('You rolled', randint(1,6))
print('Do you want to roll again?')
repeat = ('y' or 'yes') in input().lower()
'y' in input().lower(), this statement will return true if 'y' is present anywhere in the input string. Like if the input is 'thisisarandominputwithy' it will return true, because it has 'y' in the end
Change the last line to:
repeat = input().lower() in ['y', 'yes']

if-if-else vs if-elif-else statement

Why is the 'else' statement getting printed even if a correct choice is picked?
ch=0
print"Do you need Ice-Cream?"
ans=raw_input()
if ans=='y':
print"Pick a flavor"
ch=raw_input() # ch is a string
if ch=='1':
print"Vanilla"
if ch=='2':
print"Chocolate"
if ch=='3':
print"Strawberry"
if ch=='4':
print"Kiwi"
if ch=='5':
print"orange"
if ch=='6':
print"mango"
if ch=='7':
print"pineapple"
if ch=='8':
print"grapes"
print"You are done picking up a flavor, pay now"
if ans=='n':
print"Good, you can go!"
else:
print"wrong choice"
Output is printing "wrong choice" even if a valid choice is selected.
Because the if-statement checking "y" and the second if-statement checking "n" are two different. The else is only connected to the second if-statement with the "n"-check. You want to have the outermost statements like
if "y":
....
elif "n":
....
else:
....
It appears that you're conflating your series of ifs with a series of if-elifs.
Note that this:
if cond0:
...
if cond1:
...
else:
bar()
is not the same as:
if cond0:
...
elif cond1:
...
else:
bar()
If cond0 is True, then the former will call bar(), while the latter will not. In the former, it is just an if followed by a completely separate if-else.
It might help to write the former like this:
if cond0:
...
# Note spacing here, emphasizing that the above construct is separate from the one below.
if cond1:
...
else:
bar()
ans isn't 'n' so the else clause fires. You probably want an elif:
if ans == 'y':
...
elif ans == 'n':
...
else:
...
The else in this chunk of code is only referring to the if ans=='n'.
It's not taking into account your first if statement. You're going to want to change it to this
elif ans=='n':
print"Good, you can go!"
else:
print"wrong choice"
You have two conditions not one.
The first condition checks ans against 'y'.
If ans is 'y' the user gets to input an integer 1-8 and the appropriate string will be printed to the console. Processing then moves to the second condition (#2).
If ans is not 'y' then the user dose not give any input and processing moves to the second condition (#2).
The second condition checks ans against 'n'.
If ans is 'n' then "Good, you can go!" is printed to the console and processing continues skipping the else block.
If ans is not 'n' (which would be the case that user entered 'y') then the else block is executed printing "wrong choice" to the console.
What is happening is you have your logic setup that any input other than 'n' will print "wrong choice" eventually. You want a single decision from the users initial input. Currently your logic makes two.
Use the if elif else construct.

Categories

Resources