While loop with if/elif/else statement - python

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"]:

Related

Python and vs or in while loop

choice = input('Enjoying the course? (y/n)')
while choice != "y" or choice != "n":
choice = input("Sorry, I didn't catch that. Enter again: ")
im trying to understand why the code above doesnt exit the while loop if i input 'y' or 'n', but if i change the or to and and input 'y' or 'n' the while loop exits? To my understanding it should have worked both.
In or case its read as
while choice is not 'y' or choice is not 'n' -> exit
just like and
while choice is not 'y' and choice is not 'n' -> exit
You should use and instead of or:
while choice != "y" and choice != "n":
choice = input("Sorry, I didn't catch that. Enter again: ")
choice != "y" or choice != "n" always evaluates to True since choice cannot be y and n at the same time.
while choice != "y" or choice != "n":
choice = input("Sorry, I didn't catch that. Enter again: ")
You want the while loop to repeat
until choice equals "y" or choice equals "n"
So you want it to last
while choice doesn't equal "y" and choice doesn't equal "n"
So the correct code in your case would be
while choice != "y" and choice != "n":
Note
In Python a better practice would be writing this
while choice not in ("y", "n"): # Easier to understand, right?
Look at it this way:
if you enter "y" on or operator below happens
while "y" != "y" or "y" != "n":
which translates to below
while False or True:
and its or operator so (True or False) will always be True
if you enter "y" on and operator below happens
while "y" != "y" and "y" != "n":
which translates to below
while False and True:
and as its and operator so (True and False) will always be False
hence you should use and if you want to leave the loop
There are exactly 3 cases:
source is 'x'
source is 'y'
source is something else. Not one of {'x', 'y'}.
In all of these 3 states the OR condition holds, and therefore the loop continues.
In other words, the condition is always True, because choice can be only one of the two values. And therefore it is always not one of them, at least. Hence, the OR condition always holds, and the loop continues.

Convert All String Values to Lower/Uppercase in Python

I want to use a list of string values in an if statement and convert any input given by the user to lowercase- the only way I can do this now is by making a list that includes all lowercase and uppercase values and then use the "in" and "not in" operators in the if statement. Here's my code:
yes = [
"Y", "y", "yes", "YES"]
no = [
"N", "n", "no", "NO"]
start = input("Hello there! Press 'y' to start, or 'n' to stop. ")
if start in yes:
main()
elif start in no:
print("Hope you can play some other time!")
There are other longer lists in the same program and this makes it very inconvenient to type different variations of the same word. Is there any way I can convert all values to lower/upper case either in the list itself, or in the if statement?
You can use the builtin function lower:
start = input("Hello there! Press 'y' to start, or 'n' to stop. ").lower()
if start in ['y', 'yes']:
main()
elif start in ['n', 'no']:
print("Hope you can play some other time!")
And if you want without the list at all, you can check only the first letter:
start = input("Hello there! Press 'y' to start, or 'n' to stop. ").lower()
if start[0] == 'y':
main()
elif start[0] == 'n':
print("Hope you can play some other time!")
inp = input('Enter: ').upper()
print(inp)
This will print the input in uppercase. user lower() to convert in lowercase.
You might like to use strtobool. This will obviate the need to upper()|lower() and will convert truthy values into True|False for you.
from distutils.util import strtobool
start = input("Hello there! Press 'y' to start, or 'n' to stop. ")
if strtobool(start):
main()
else:
print("Hope you can play some other time!")
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
I would do it like this:
start = input("Hello there! Press 'y' to start, or 'n' to stop. ").upper()[0]
if start == "Y":
print("put main program here")
else:
print("Hope you can play some other time!")

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.

Python, How do I use a string in a while loop and then an if statement?

I cannot figure out why this won't work, I have gone as far as to apply integer variables, I would prefer to keep it purely to strings. I'm new, what am I doing wrong?
x = int(2)
y = int(1)
while userinput != (1,2):
userinput = input("Do you wish to continue, to start from scratch?")
if input == 1:
print("y")
if input == 2:
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
I presume you want to check directly on the "y" and "n" characters, note that, among the other things, in your code you are checking the wrong input, you should check the variable userinput that you assign in the loop with the user input.
Here is a working example, note that i convert to lowercase in order to accept both "y\n" and "Y\N" with a single if statement.
userinput = ""
while (userinput !="y" and userinput !="n"):
userinput = input("Do you wish to continue, to start from scratch?").lower()
if userinput == "y":
print("y")
elif userinput == "n":
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
EDIT: if statement fixed as suggested by #Kumar

Command "Break" doesnt work for some reason

number=input("enter a whole number")
if number.isdigit():
print("Good one")
else:
print ("haha, really clever")
answer=str(input("Wanna try again? y/n"))
if answer == 'n':
print("Ok loser")
break
elif answer== 'y':
print("ok...good luck")
continue
I tried to make a code that would react if the input is integer or float, and if its float it would restart if the person wants it to; but the command 'break' doesnt want to work for some reason please help... (make it simple please)
You just need to wrap your code with a while loop.
while True:
number=input("enter a whole number")
if number.isdigit():
print("Good one")
else:
print ("haha, really clever")
answer=str(input("Wanna try again? y/n"))
if answer == 'n':
print("Ok loser")
break
elif answer== 'y':
print("ok...good luck")
continue
To use a break, you need it to be in a loop (while, for, ...). A break stop the execution of the loop if it's condition is met. In your casse you only have ifs, so you don't need a break as it will not check the other conditions if the first one is met.
You need to use a while loop.
answer = 'y'
while answer == 'y':
number = input("Please enter a whole number: ")
if number % 1 == 0:
print("Good one!")
else:
print("Haha, really clever.")
answer = input("Wanna try again? (y/n) ")
Set the answer to y so the loop runs at least once.
If the user wants to try again they enter y and the condition will be true meaning the loop wil run again.
Hope this helped!

Categories

Resources