Python If statement and logical operator issue [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
I'm trying to create a small python program to emulate rolling a single die. My problem arises in that I want the program to accept both upper and lower-case 'Y' to trigger a re-roll. My program works when I accept either upper or lower case y but when I try to change the line
if usr == 'Y'
to
if usr == 'Y' or 'y'
creates a problem where it never enters the else statement, making the program never terminate.
import random
def DiceRoll():
number = random.randrange(1, 7, 1)
print("Dice Roll: ", number)
AskUser()
return
def AskUser():
usr = input("Roll Again? (Y/N) \n")
if usr == 'Y':
DiceRoll()
else :
print("Thank you for playing!")
return
DiceRoll()

You must do
if usr == 'Y' or usr == 'y'.
It is currently evaluating the statement 'y' as its own condition, and in this case 'y' always evaluates to true.

Related

Python while loop breaks in every case [duplicate]

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)
Closed 6 years ago.
I'm trying to make a program that rolls a dice and checks if the user wants to continue every roll, if not, the program should halt. Although, no matter what you input, the program breaks out of the loop. Can someone explain why and give me some tips to making a program that is simpler and works? Thanks
import random
sideNumber = int(input("Enter the number of sides in the die: "))
print("Dice numbers: ")
while True:
print(random.randint(0, sideNumber))
print("Do you want to continue?")
response = input()
if response == "n" or "no":
break
That's because the statement "no" is still true.
You should do :
if response == "n" or response == "no":
or better :
if response in ["n", "no"] :
if response == "n" or "no":
makes your code fail. This checks if the boolean value of "no" is true, and it always is. replace it with:
if response == "n" or response == "no":

Why is my program doing this? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
For some reason my program keeps rolling the dice again regardless of the users answer, and it doesn't print the goodbye message.
I'll include the code below so you can test yourself (Python 3)
from random import randint
def rollthedice():
print("The number you rolled was: "+ str(randint(1,6)))
rollthedice()
shouldwecontinue = input("Do you wish to roll again? (y or n) ").lower()
if shouldwecontinue == "y" or "yes":
rollthedice()
elif shouldwecontinue == "n" or "no":
print("Goodbye.")
elif shouldwecontinue != type(str):
print("Sorry the program only accepts 'y' or 'n' as a response.")
The desired effect of the program should be that if the user enters y, it rolls the dice again, respectively starting the whole program again. Whereas, if the user enters no then it should print the Goodbye message.
or doesn't work like that. Right now your program is evaluating (shouldwecontinue == "y") or "yes", and since Python interprets "yes" as truthy, then that condition always succeeds. The simplest fix is to change it to shouldwecontinue == "y" or shouldwecontinue == "yes". And then similar changes for the other conditional expressions, of course.

If/Then statement not working inside of while loop [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
The if/else statement inside of this loop will not work. If I enter "no" it still continues the loop. I don't understand why, any help would be appreciated.
while keepPlaying == True:
play = input(str('Would you like to play rock, paper, scissors? Yes or no?\n'))
if play == str('yes') or str('Yes'):
playerChoice = input(str('Ok! what\'s your choice?\n'))
else:
keepPlaying = False
print ('Thanks for playing.')
I've put the code through a visualizer and even if the variable play != yes or Yes it still chooses the == to path.
The problem is this:
if play == str('yes') or str('Yes'):
It is equivalent to:
if (play == str('yes')) or str('Yes'):
Note that str('Yes') is always truthy (and with an or means you'll never get the false part).
You want:
if play in ('yes', 'Yes'):
Or maybe (just a tip):
if play.lower() == 'yes':
Change the if condition to play in ('Yes', 'yes', 'y', 'Y')
The issue is, the second part of the or clause (str('Yes')) always evaluates to true.

How come my program does not quit? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 9 years ago.
Alright, so I've tried this for a while now and I can't seem to find a way to close the program once it is running.
What I want it to do is to end the program if the user chooses 'no':
elif y == 'n' or 'no':
sys.exit(0)
However whatever I choose returns the program to the partOne function. I've tried different things to try and solve this, such as moving
partOne()
from the end of the program to in between the two functions but that does not work because then the PartTwo function has yet to be defined.
Thanks for your response.
import hashlib
import sys
def partOne():
x = input("\nEnter something to hash: ")
hash_object = hashlib.sha256(x.encode())
hex_dig = hash_object.hexdigest()
print("\nPlain text: ")
print(x)
print("\nHashed text: ")
print(hex_dig)
print("\nYour password: ")
print(hex_dig[::9])
partTwo()
def partTwo():
y = input("\nDo you want to make another password? (y/n): ")
if y == 'y' or 'yes':
partOne()
elif y == 'n' or 'no':
sys.exit(0)
else:
print("\nYou need to type either 'y' or 'n'.")
partOne()
partOne()
Try y == 'n' or y =='no'
instead of y == 'n' or 'no'
>>> y = 'anything'
>>>
>>> bool(y == 'n' or 'no')
True
your statement always returns True. Instead of checking y == 'no' it just checks 'no', anything converted to bool in python is True if its not None, False, or 0.
In case of strings and other iterables it returns True if its not empty, e.g. '', [], {}, () will always return False.
Or as Foo Bar User says, if y.lower() in ('n', 'no') will also do. lower() will make sure that the matching is case insensitive.

How can I make sure the user only inputs 'y' or 'n' in the program? [duplicate]

This question already has answers here:
Python And Or statements acting ..weird
(5 answers)
Closed 6 years ago.
How can I make sure the user input only 'y' or 'n' in and make the program only accept 'y' or'n' as an answer?
while True:
try:
cont = input("Do you want to continue? If so enter 'y'.")
if cont != "n" or cont !="y":
print("Please enter 'y' or 'n'")
else:
break
except ValueError:
print("Please enter 'y' or 'n'")
else:
break
A condition of the type if cont != "n" or cont !="y": will always be true as cont can not be n and y at the same time.
You should use and operator instead of or operator. To avoid such confusion, you can try and write such conditions in close to english way, like this
cont="a"
if cont not in ("n", "y"):
print "Welcome"
This can be read as "if cont is not one of...". The advantage of this method is that, you can check for n number of elements in a single condition. For example,
if cont not in ("n", "y", "N", "Y"):
this will be True only when cont is case-insensitively n or y
Edit: As suggested by Eric in the comments, for single character checking we can do something like this
if cont not in "nyNY":
Because it should be if cont != "n" and cont !="y":. Every word is either not n or not y.

Categories

Resources