While loop with multiple conditions - python

So my while loop just keeps looping even when it shouldn't, if there is only 1 condition the loop works and then proceeds to the next lines of code but when I add the OR statement it wont work, I'm sure it's something very silly but I'm only a beginner and have tried researching this.
Choice = input("What would you like to do? New Game, Continue, or Quit?").upper()
while Choice != "NEW GAME" or Choice != "QUIT":
print ("That input was invalid, please try again.")
Choice = input("What would you like to do? New Game, Continue, or Quit? ").upper()
if Choice == "QUIT":
quit()

The condition
Choice != "NEW GAME" or Choice != "QUIT"
will always be True. Any value of Choice will be either not "NEW GAME" or not "QUIT". Instead, use:
Choice != "NEW GAME" and Choice != "QUIT":

I think you are looking for
while Choice not in ["New Game", "Continue", "Quit"]
or better to allow for alternative capitalization:
while Choice.upper() not in ["NEW GAME", "CONTINUE", "QUIT"]
Also please uncapitalize the variable Choice. When other Python programmers see a variable that starts with a capital letter they assume at first that it is a class name.

I guess you want a and there, not a or…
Because Choice can't be at the same time not different from "NEW GAME" and from "QUIT". In other words, your loop condition is always True whatever the value of Choice is.

Related

How do I have my program actually activate the quiz?

What is wrong with my coding. It is a simple conditional statement where you say yes or no to taking the quiz. If you type yes, you begin answering questions and if you type no, it just exits out of the function.
play=input("\v Do you want to take the quiz or not? Yes or No? ").lower
if play == "no":
print("That's too bad")
quit(main())
question_num=0
green_point=0
mean_point=0
if play=="yes":
print("Great! Let us Begin!")
for questions,answers in QUESTIONS:
playeranswer=input("{} " .format(questions))
But the program just ends once you type in an answer for play. I thought it was pretty clear what is supposed to happen. Why is it not doing anything?
1- the indention is wrong with your coding
2- you forgot the () after .lower
your code should be like this :
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower()
if play == "no":
print("That's too bad")
quit(main())
question_num = 0
green_point = 0
mean_point = 0
elif play == "yes":
print("Great! Let us Begin!")
for questions, answers in QUESTIONS:
playeranswer = input("{} " .format(questions))
Actually it's not just the indentation. When you do this:
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower
It actually sets play to be the function lower, not the lowercase string that results from calling lower(). You need to add parentheses:
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower()
if play == "no":
print("That's too bad")
quit(main())
question_num = 0
green_point = 0
mean_point = 0
elif play == "yes":
print("Great! Let us Begin!")
for questions, answers in QUESTIONS:
playeranswer = input("{} " .format(questions))

Python 3 Menu with Quit option

I'm trying to create a sort of CLI menu in Python (very new to this) and having an issue with the quit option mostly, it won't actually quit and jumps to the "Oooops that isn't right" option instead, or repeats the last step. It does seem to work if you put it as the first choice though
I know I must be doing something daft. I've tried just putting the variable at the end of the function, as well as the menu function itself but that didn't seem to work.
Snippet below if anyone can point me in the right direction.
def my_menu():
choice = input("Please choose an choice: ")
choice = choice.lower()
while (choice != "quit"):
if choice == "b":
a_thing()
my_menu()
if choice == "quit":
break
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
Try to input the choice another time at the end of the loop, remove the call to the my_menu() function and remove the if choice=="quit" block (because the loop will automatically quit when the choice is set to "quit")
def my_menu():
choice = input("Please choose an choice: ").lower()
while (choice != "quit"):
if choice == "b":
a_thing()
else:
print("Oooops that isn't right")
choice = input("Please choose an choice: ").lower()
def a_thing():
print("a thing")
my_menu()
Or you can remove the loop and just verify using if statements and in the case of "quit" you just put return to break the loop
def my_menu():
choice = input("Please choose an choice: ").lower()
if choice == "b":
a_thing()
elif choice == "quit":
return
else:
print("Oooops that isn't right")
my_menu()
def a_thing():
print("a thing")
my_menu()
I ran your code, and on its first iteration it runs as expected. After that, the recursive call to my_menu() starts to cause problems.
Walking through it, first you enter some random string, "hi", and it will enter the while loop and use the else case. This will call my_menu(), which then calls another while loop. When you enter that new while loop, any exiting that you do (e.g. break) won't exit the first loop, only the loop that your currently in, so you're in an infinite loop because you can never "go back" and change the value of choice in the first loop.
A way you could achieve this behavior with the least amount of changes to your code would be like this:
def my_menu():
choice = ""
while (choice != "quit"):
choice = input("Please choose an choice: ")
choice = choice.lower()
if choice == "b":
a_thing()
if choice == "quit":
break
else:
print("Oooops that isn't right")
def a_thing():
print("a thing")
my_menu()
(I removed your recursive calls to my_menu(), moved the input lines to within the loop, and initialized choice before the loop)

Break if input left blank inside of an if statement

I have a school assignment for Python in which I have a backpack of items and need to make code to ask the user if they want to: a) add an item to the backpack, b) check the items in the backpack, and c) quit the program.
For my code, I want to make it so that if the user at input for adding a new item just hits return and leaves the input blank, it will re-prompt to the input again rather than continuing the code if no item is actually added. Here's what I have so far:
import sys
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if (userChoice == "1"):
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
else:
itemsInBackpack.insert(0, itemAddNew)
print("Added to backpack.")
With my code here, even if I hit return in a test and leave the input blank, the code still continues onward and doesn't break to re-prompt input again. Is it because I'm using an if statement inside of an if statement already? I'm sure in general there's a better way to do this, but as a beginner I'm stumped and could use a shove in the right direction.
The break stops everything in your loop and causes your program to end.
If you want to prompt for input until the user gives you something, change this:
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
to this:
print("What item do you want to add to the backpack?")
itemAddNew = input()
while itemAddNew == "":
#Added some output text to tell the user what went wrong.
itemAddNew = input("You didn't enter anything. Try again.\n")
This will keep going WHILE the text is empty.

How do I ask the user if they want to play again and repeat the while loop?

Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break

Code not printing what I seek

For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)

Categories

Resources