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":
Related
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)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 17 days ago.
I have written this very simple code. I am new to programming. But I seem to dont understand why this loops doesnt break when I give it "N" for an answer when I run it.
while (True):
name = input("What is your name?\n")
print(f"Hello {name}, how are you today?")
answer = input("would you like to continue with the conversation? Reply with 'Y' or 'N'\n")
if answer == "y" or "Y":
continue
elif answer == "N" or "n":
break
else:
print("Kindly only answer with 'Y' or 'N'")
I wanted this to get out of loop and break the program when I enter "N"
You need to include answer == in both sides of the conditionals.
i.e.
while (True):
name = input("What is your name?\n")
print(f"Hello {name}, how are you today?")
answer = input("would you like to continue with the conversation? Reply with 'Y' or 'N'\n")
if answer == "y" or answer == "Y":
continue
elif answer == "N" or answer == "n":
break
else:
print("Kindly only answer with 'Y' or 'N'")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
Background:
I'm experimenting with while loops and I just made a simple program nested in a while loop.
Code:
while True:
userinput = input("Is nem jeff? ")
if userinput == "y" or "yes" or "Y" or "Yes":
print ("YAY!")
elif userinput == "n" or "no" or "N" or "No":
print ("das sad :(")
else:
print ("wrong input")
break
Problem:
My program should be looping until the user types in an invalid input, but instead, it always returns the value nested in the if statement, no matter what I type in. What am I doing wrong?
Your conditionals aren't doing what you think they are.
In Python, a non-zero-length string evaluates to True in a boolean
context. The or operator performs a boolean or operation between
the lefthand operand and the righthand operand.
So when you write this:
if userinput == "y" or "yes" or "Y" or "Yes":
What you are saying is this:
if (userinput == "y") or True or True or True:
Which will always evaluate to True. You want to write instead:
if userinput == "y" or userinput == "yes" or userinput == "Y" or userinput == "Yes":
Or more simply:
if userinput.lower() in ['y', 'yes']:
The reason false down to truthsy or falsy in if conditions.
based on your initial code block
print('y'=='yes'or'y')
[output] y
print('n'=='yes'or'y')
[output] y
based on the above you can see that regardless of you input, your first if statement would be evaluated as True.
rather than doing that, try doing this instead.
while True:
userinput = input("Is nem jeff? ").lower()
if userinput in ['yes','y']:
print ("YAY!")
elif userinput in ['no','n']:
print ("das sad :(")
else:
print ("wrong input")
break
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.
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.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
This is a small experiment I am trying in learning Python. Its meant to be a text based slot machine, where 3 slots are 'rolled' and 1 of the 4 possible choices is chosen for each
If the 2 numbers match, 5 points are given. If all 3 match, 10 are given.
After running this function the game prints their current score asks if the user wants to play again. At this portion of the code:
def ask():
play_again = raw_input ("Do you want to play again? (Yes or No):")
if play_again == "yes" or "Yes":
run_machine()
elif play_again == "No" or "no":
print "Bye!"
sys.exit(1)
else:
print "I don't know what that means"
ask()
Where run_machine() is the main function. However regardless of the input, the program repeats. I am new to python so this might be something simple but I wanted to see what so far might be the problem.
If it isn't something in this block then here is the full program:
import random
slot_1 = [1,2,3,4]
slot_2 = [1,2,3,4]
slot_3 = [1,2,3,4]
points = 0
def role(slot):
return (random.choice(slot))
def run_machine():
print "ROLLING!"
first = role(slot_1)
second = role(slot_2)
third = role(slot_3)
global points
if (first == second) or (first == third) or (second == third):
if (first == second) and (second == third):
print "You got 10 points! Full matches!"
points = points + 10
else:
print "You got 5 points, 2 matched!"
points = points + 5
else:
print "Sorry try again!"
print "You now have %s points" % points
ask()
def ask():
play_again = raw_input ("Do you want to play again? (Yes or No):")
if play_again == "yes" or "Yes":
run_machine()
elif play_again == "No" or "no":
print "Bye!"
else:
print "I don't know what that means"
ask()
run_machine()
This does not do what you think it does.
if play_again == "yes" or "Yes":
The correct way to say this would be the following (I added parentheses for emphasis)
if (play_again == "yes") or (play_again == "Yes"):
The way you originally wrote it means the following in pseudo-code
if (play_again == "yes")
or
if ("Yes") # this always evaluates to True