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 last year.
I'm currently writing a program for a school project.
The purpose is for it to work as an online cash register.
answer = "a"
qty1 = 0
while True:
answer = str(input("\nDo you really wish to buy this? (Y/N) "))
if answer == "Y" or "y":
qty1 = int(input("\nHow much quantity of this item would you like to buy? "))
print("\nDo you really wish to buy", qty1, "pieces? (Y/N) ")
answer = str(input(""))
if answer == "Y" or "y":
print("Confirming order and returning to menu.")
break
else:
qty1=0
print("Cancelling order and returning to menu")
break
elif answer == "N" or "n":
print("Okay, returning to menu.")
break
else:
print("not valid answer")
Here is the code for the part of the program I'm having trouble with.
Whenever I reach this part of the program, the input seems to ignore whatever I put and it always goes through the if path.
Does anyone know why this is?
I'm new to programming, so sorry if this is just an easy fix.
Here's the working code which needed some formatting:
Changed these lines -> answer in ("Y", "y") and answer in ("N", "n"). This is because if answer == 'Y' or 'y' is used then 'y' will always evaluate to True which means the first if statement always executes. Also, the error in the print statement has a colon: print: - this was corrected.
answer = "a"
qty1 = 0
while True:
answer = str(input("\nDo you really wish to buy this? (Y/N) "))
print(answer)
if answer in ("Y", "y"):
qty1 = int(input("\nHow much quantity of this item would you like to buy? "))
print("\nDo you really wish to buy", qty1, "pieces? (Y/N) ")
answer = str(input(""))
print(answer)
if answer in ("Y", "y"):
print("Confirming order and returning to menu.")
break
else:
qty1=0
print("Cancelling order and returning to menu")
break
elif answer in ("N" ,"n"):
print("Okay, returning to menu.")
break
else:
print("not valid answer")
Related
This question already has answers here:
How to make user input not case sensitive?
(4 answers)
Closed 6 months ago.
I am adding a few ways of checking user input to my code. Instead of writing if Answer == ("Yes") or Answer == ("yes"), is there any way I could make the variable input case-insensitive, so that I don't have to type the word yes twice? Additionally, would there be any way I could make the every variable input option in the line case-insensitive? if Answer == ("Yes") or Answer == ("yes") or Answer == ("Y") or Answer == ("y"):.
def Repeat():
Answer = input ("\nDo you want to play again? (Y/N): ")
if Answer == ("Yes") or Answer == ("yes") or Answer == ("Y") or Answer == ("y"):
print ("")
if Answer == ("No") or Answer == ("no") or Answer == ("N") or Answer == ("n"):
exit()
if Answer == "Options" or Answer == "options" or Answer == "o" or Answer == "O":
print ("")
else:
print ("Invalid Input")
Repeat()
Repeat()
You can change the case of the user input and just check against that:
answer = input("\nDo you want to play again? (Y/N): ").lower()
if answer in ("yes", "y"):
...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So I'm fairly new to this whole coding scene and I'm doing some beginner projects to build upon what I've learned.
Essentially what I'm trying to do is get the program to restart back at the top of the loop if the user wants to roll again, or accidently types something else that is not "yes" or "no".
In addition, is there a way to skip a certain line of code, so that way the user isn't asked if they want to roll twice?
Should I be using functions instead?
Couldn't find any info that helped me directly so thought I would ask, any info at all would be helpful, thanks!
import random
useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
lets_play = input('Do you wish to roll? Yes or no: ')
if lets_play.lower() == 'yes':
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
ask = input('Do you wish to roll again? ')
if ask.lower() == 'yes':
# How do I return to give the user another chance?
elif ask.lower() == 'no':
print('Alright, later!')
break
elif lets_play.lower() == 'no':
print('Alright, later!')
break
else:
print('Not any of the options, try again...')
# how do I return to the top to give the user another chance?
(Original code as image)
You've asked a couple of questions in one, but I'll try and answer them with an example. First off, to have an infinite running while loop, you can just set it to True (basically the same as your 1=1 statement, just easier).
Your second question regarding functions is typically yes - if some code needs to be repeated multiple times, it's usually good to extract it to a function.
Your third question regarding skipping a line of code - easiest way to do this is if/else statements, like you've already done. One thing that can be improved, is by using continue; it restarts the loop from the beginning, whereas break breaks out of the loop.
Here's a simple code example for your scenario:
import random
def roll():
print('First roll:', random.randint(1, 6))
print('Second roll:', random.randint(1, 6))
play = input('Do you wish to roll? Yes or no: \n')
while True:
if play.lower() == 'yes':
roll()
play = input('Do you wish to roll again? \n')
elif play.lower() == 'no':
print('Alright, later!')
break
else:
play = input('Not any of the options, try again... Yes or no: \n')
Hey I would do it like this
import random
useless_variable = 1
lets_play = input("Do you want to roll. yes or no: ")
if lets_play.lower() == "yes":
while useless_variable == 1:
useless_variable == 0
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print("You got a: ", d1, "from the first dice")
print("You got a: ", d2, "from the seond dice")
ask = input("Wanna roll again(yes or no):")
if ask.lower() == "yes":
useless_variable = 1
else:
break
If you want to do an infinite loop then while True: Otherwise you can put in your while something like while condition == true and in your answer when is "no" change the condition to false.
I would do it like this
def roll():
if(lets_play.lower() == "yes"):
//Code here
elif lets_play.lower() == "no":
//Code here
else:
print("invalid")
while True:
lets_play = input("Roll?")
if lets_play.lower() == "exit":
break
else:
roll()
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
Hello everyone so I started working on a dice rolling game that rolls the dice then displays the value and asks if the user would like to re-roll. I know how to do all that but I wanted to put in a part that would loop if the user put in a value that was not Y(Yes) or N(No). So I created another while statement to accomplish this. If you input an invalid response the program asks you to type Y or N. Then if you type an invalid response again it keeps asking until the expected value is entered. Here is the code and I'll highlight the part where I don't understand. I commented why I think it works but I'm not sure. If someone could explain why it works I appreciate it thanks a lot!
import random
value = random.randint(1, 2)
run = True
while run:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = input("Do you want to play again? (Y or N) \n")
if answer == "Y":
continue
if answer == "N":
print("Thanks for playing \n")
exit()
# after you type an invalid response it's stored in variable answer
# the program then goes to answer2 input which asks please enter Y or N
# if the program then detects an invalid answer it goes back to the top
# of the while statement and uses answer ones response which is still
# an invalid response???? I'm guessing since answer is always invalid and the
# decisions only two options that are yes or no it goes back to the top of the 2nd while loop
# Not sure tho.
# 2nd while loop
while answer != "Y" or "N":
answer2 = input("Please enter Y or N \n")
while answer2 == "Y":
print("You roll a six sided dice \n")
print("The dice landed on " + str(value) + "\n")
answer2 = input("Do you want to play again \n")
continue
if answer2 == "N":
print("THanks for playing")
exit()
I've commented out why I think it works but
import random
value = random.randint(1, 2)
def getans():
while True:
answer = raw_input("Do you want to play again? (Y or N) \n")
if answer == "Y":
return True
elif answer == "N":
return False
else:
print ("Please enter Y or N \n")
continue
while True:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = getans()
if answer == True:
continue
elif answer == False:
print("Thanks for playing \n")
exit()
else:
print ("this will never run")
I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
When I type no into the input on the terminal. It goes through the if choice == "yes" part.
I want it to go through the else. Please help.
choice=raw_input("Will you help us? Yes or no?")
if choice == "yes" or "Yes":
print "Yeah! You are a hero!"
name = raw_input("What is your name?")
print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."
else:
print "You're a coward. :("
quit()
What's wrong?
The bug is in this line of code:
if choice == "yes" or "Yes":
Python sees this as an "or" of two conditions:
if (choice == "yes") or ("Yes"):
Which is same as:
if (choice == "yes") or True:
because a non-empty string is always True.
And this finally reduces to:
if True:
as "or"ing with True always evaluates to True.
This would give you the desired result:
if choice == "yes" or choice == "Yes":
However, that is considered C-style and the pythonic way of comparing multiple values is:
if choice in ("yes", "Yes"):
But in this case, you just want to do a case-insensitive match. So the right way to do that would be:
if choice.lower() == "yes":
And this would even handle odd capitalization in inputs like "yEs" or "YEs".
choice=raw_input("Will you help us? Yes or no?")
if choice == "yes" or choice == "Yes":
print "Yeah! You are a hero!"
name = raw_input("What is your name?")
print "Alright, " + str(name) + " ,let's go choose a weapon from the blacksmith."
else:
print "You're a coward. :("
quit()
The above is the correct format. You did not have the logic set up correctly. Note the following:
a = 1
if a == 2 or 3 :
print 'OK'
It prints 'OK'. Why?
The reason is that python values are evaluated in a left to right fashion. If any value is true then that value is returned. However if all values are false then the last value is returned, in your case 'Yes'. This is what is causing you problems as far as I understand it. You need basically two 'or' conditions, not one....