If inside while loop - python

again = True
while(again == True):
yn = input("Do you want to do it again? (y or n)").lower()
if(yn == 'y' or 'yes'):
again == True
elif(yn == 'n' or 'no):
again == False
How do I make this code work? When I run it, it will always come out to be true.. =/

Let's start from the beginning:
while(again == True):
You don't need the parentheses here
You don't need the == True bit. again is suffice as it will have a boolean value of True.
if(yn == 'y' or 'yes'):
Once again, parenthesis aren't needed.
That line of code is translated as if (yn == 'y') or ('yes'):. This will always be true as 'yes' is considered True (not an empty string)
In python, you need to do if yn == 'y' or yn == 'yes':
Or you can do if yn in ('y', 'yes')
again == True
== is for comparisons. = is for assignments
This occurs in your else block.

In the final 4 lines of your program you aren't assigning again to have the value true, you are checking if again equals True/False.
== is completely different from =.

This won't work:
if (yn == 'y' or 'yes'):
# ...
elif(yn == 'n' or 'no):
The correct way is:
if yn in ('y' or 'yes'):
# ...
elif yn in ('n' or 'no):
Also, inside the conditions the assignments are wrong, use a single =. They should look like this:
again = True
# ...
again = False

You are mistaking the equality operator == with the assignment operator =. Also the statement yn == 'y' or 'yes' is buggy, since the right hand side is a non-empty string, which evaluates to True in a boolean context.
Declaring a variable simply to handle loop termination is not pythonic. I would rewrite your code entirely to be:
while True:
yn = input("Do you want to do it again? (y or n)").lower()
if yn in ('n','no'):
break

if(yn == 'y' or 'yes'):
# ----
The value of above statement is always true independent of valu of “yn” because right side of “or” is always true in your case. so it will never execute else part. So to avoid this, You have to compare value of “yn” with each possibility.
one of the simple way is that
if(yn == 'y' or yn == 'yes'):
again == True
elif(yn == 'n' or yn == 'no):
again == False

your if else statment should be
if xxx:
again = True
elif yyy:
again = False
Note difference between = and ==.

Related

Input selection in Python using IF statements [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Im trying to create code that prints a game's difficulty level based on what the "diffChoice" value is using IF statements. However, I can't get the "gameDiff" value to correctly represent what the "diffChoice" was. Any help/feedback is appreciated.
diffChoice = 'm'
if diffChoice == 'e' or '1':
gameDiff = 'EASY'
if diffChoice == 'm' or '2':
gameDiff = 'MEDIUM'
if diffChoice == 'h' or '3':
gameDiff = 'HARD'
print(gameDiff)
In all of your Boolean conditions, the second expression after the or is truthy, so x or y will always yield True.
Consider:
if "1":
print("I'll print!")
if "2":
print("So will !")
if "":
print("I won't print; the empty string (an empty sequence of characters) is treated as False.")
if []:
print("I won't print: the empty list is treated as False.")
if False or 1:
print("I WILL print: False or 1 is treated as False or True.")
You can read more about this here. In particular:
By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object.
What you want is to test a or b, so write:
if diffChoice == 'e' or diffChoice == '1':
gameDiff = 'EASY'
or, equivalently:
if diffChoice in ('e', '1'):
gameDiff = 'EASY'
and so on.

python if statement evaluation with multiple values

I'm not exactly sure why but when I execute this section of code nothing happens.
while (True) :
choice = str(input("Do you want to draw a spirograph? (Y/N) "))
if choice == 'n' or 'N' :
break
elif choice == 'y' or 'Y' :
<CODE>
else :
print("Please enter a valid command.")
choice = input("Do you want to draw a spirograph? (Y/N)")
It won't work because the 'N' literal always evaluates to True within your if statement.
Your if condition currently stands as if choice == 'n' or 'N' :, which is equivalent to if (choice == 'n') or ('N'), which will always evaluate to True irrespective of the value of variable choice, since the literal 'N' always evaluates to True.
Instead, use one of the following
if choice == 'n' or choice == 'N' :
if choice in 'nN' :
if choice in ('n', 'N') :
The same holds for your elif block as well. You can read more about Truth Value testing here.
This expression doesn't do what you want:
choice == 'n' or 'N'
It is interpretted as this:
(choice == 'n') or 'N'
You might want to try this instead:
choice in 'nN'

If function doesn't work as expected in PYTHON [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
Here is a part of my code where the problem is.
It doesn't matter what the input is, the script will end
when I enter something.
It should restart when i enter "yes" or "y"
Without the OR it works without problem
else:
if number == rndnum:
print "Congratulations! You won."
print "Do you want to replay?"
answer = raw_input("Type y (yes) or n (no): ")
dialog = 1
while dialog == 1:
if answer == "n" or "no":
replay = 0
dialog = 0
elif answer == "y" or "yes":
dialog = 0
else:
answer = raw_input("Type y (yes) or n (no): ")
loop = 0 #Will overdo loop var and stop the loop
if answer == "n" or "no":
is interpreted by Python as:
if (answer == "n") or ("no"):
Which is always true, because the second condition in your or clause is always True (non-empty strings in Python are truthy, which means they evaluate to True in a condition):
>>> bool("no")
True
What you need is one of:
if answer in ("n", "no"):
# or
if answer == "n" or answer == "no":
Th same goes for "yes", of course.
Adjust your code like this:
if answer == "n" or answer == "no":
# ...
and:
elif answer == "y" or answer == "yes":
# ...
a or b, where a and b are strings and not both the empty string, will always evaluate to True in a boolean context, demo:
>>> '' or 'x'
'x'
>>> 'y' or 'x'
'y'
>>> '' or ''
''
>>> if 'x': print('hi')
...
hi
>>> if '': print('hi')
...
>>>
The first two expressions will evaluate to True.

Python loop keeps repeating? Why?

Another_Mark = raw_input("would you like to enter another mark? (y/n)")
while Another_Mark.lower() != "n" or Another_Mark.lower() != "y":
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
if Another_Mark == "y":
print "blah"
if Another_Mark == "n":
print "Blue"
This is not the actual code I'm using except for the 1st three lines. anyways my question is why does the while loop keep repeating even when I input a value 'y' or 'n', when it asks again if you want to input another mark on the third line. I'm stuck in a infinitely repeating loop.
It shouldn't repeat when the value for Another_Mark is changed to either "y" or "n"
Try:
while Another_Mark.lower() not in 'yn':
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
not in operator returns true if given object is not found in the given iterable and false otherwise. So this is the solution you're looking for :)
This wasn't working due to boolean algebra error fundamentaly. As Lattyware wrote:
not (a or b) (what you describe) is not the same as not a or not b
(what your code says)
>>> for a, b in itertools.product([True, False], repeat=2):
... print(a, b, not (a or b), not a or not b, sep="\t")
...
True True False False
True False False True
False True False True
False False True True
Your loop logic only every comes out true - if the input is "n", then it's not "y" so it's true. Conversely if it's "y" it's not "n".
Try this:
while not (Another_Mark.lower() == "n" or Another_Mark.lower() == "y"):
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
Your logic behind the looping is wrong. This should work:
while Another_Mark.lower() != "n" and Another_Mark.lower() != "y":
Another_Mark = raw_input("Do you want to input another mark? Please put either 'y' or 'n' this time")
You need to use AND instead of OR.
It's the way boolean logic distributes. You can say:
NOT ("yes" OR "no")
Or you can distribute the NOT into the parenthesis (which is what you're trying to do) by flipping the OR to an AND:
(NOT "yes") AND (NOT "no")

Why does my elif go back to my if?

I have written a very basic encryption program, and whilst writing the decrypting algorithm for it, I have encountered some problems with a loop I have.
from re import *
cipher = open('cipher.txt')
ciphertext = cipher.read()
keyfile = open('key.txt')
key = keyfile.read()
decoded = []
chardec = ''
inval = 1
print("Decoder for encrypt1.py")
while inval == 1:
useManKey = input("Use a manual key? Y or N\n> ")
if useManKey == 'Y' or 'y':
key = input("Please enter the key you wish to use to decrypt\n> ")
inval = 0
elif useManKey == 'N' or 'n':
inval = 0
print("OK, decrypting")
else:
print("That wasn't a valid option/nPlease re-enter")
When I run this, and declare useManKey as N or n it seems to run the if part of the loop as if I had declared it as Y or y. I am probably being stupid here, but any help would be much appreciated thanks.
useManKey == 'Y' or 'y' does not work how you think it does. What you want is useManKey in ('Y', 'y'). What you have first evaluates useManKey == 'Y', then, if that check fails, tests the string 'y' for truishness. Since non-empty strings are always truish, your if statement always evaluates to True. As is pointed out in the comments, you could also use upper() or lower() to first convert the input to a fixed case if you want.
useManKey == 'Y' or 'y'
Doesn't actually check whether useManKey value being 'Y' or 'y', Use sr2222's answer for what you need to do. ie.
useManKey in ('Y', 'y')
The earlier expression evaluates to
(useManKey == 'Y') or 'y'
Which is always True irrespective of the value of useManKey as 'y' being non-Falsy (non-None) the 'or' of these always evaluates to True,

Categories