Why is my program doing this? [duplicate] - python

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.

Related

Create a conversation that has a Y/N answer [duplicate]

This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed 6 days ago.
I am trying to create a small bit of code in Python that runs a conversation, then asks a Y/N question i.e "Do you believe the sky is blue?"
When I run the code, it works well until I reach the question. It ignores my parameters for Y/N answers to print specific responses. It gives me the print response attached to my "else" statement.
I am confused if I am writing my If/elif/else statements wrong?
My code is written as follows:
x = input('do you believe the sky is blue')
if x == "yes":
print("I believe you are correct")
elif x == "no":
print('I think you have a unique perspective.')
else:
print('Please answer Yes or No.)
You use .lower() to obtain a lower case version of a string, and you are missing a ' in the last print():
x = input('do you believe the sky is blue ').lower()
if x == "yes":
print("I believe you are correct")
elif x == "no":
print('I think you have a unique perspective.')
else:
print('Please answer Yes or No.')

Python If statement and logical operator issue [duplicate]

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.

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

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.

Python ignores input for raw_input and continues to repeat function [duplicate]

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

Categories

Resources