I can't break this while loop - python

I have an assignment where I need to complete an action until the input is 'quit', 'Quit', 'q', or 'Q'. I've been trying this:
while variable != 'quit' or 'Quit' or 'q' or 'Q':
# do stuff
however when any of those strings are inputted the while loop still executes! I've tried other ways like if statements but it just times out. How can I break the loop correctly?

The way to go is probably something like this:
while str(variable).upper() not in ['QUIT', 'Q']:
This way, you can list all the values which allow the user to quit in one place and the case (upper or lower) is ignored.

If I'm understanding this correctly, you have something like the following:
while variable != 'quit' or 'Quit' or 'q' or 'Q':
# do stuff
variable = input("")
(By the way - welcome to Stack Overflow! As another user has mentioned in a comment - please provide a code example; it will help potential answerers actually know what's going wrong and what you're trying to do.)
The reason why it never breaks is because what the Python interpreter actually sees is:
while (variable != 'quit') or ('Quit') or ('q') or ('Q'):
# do stuff
variable = input("")
In Python, non-empty strings will evaluate to true - if you try bool('q') in the Python interpreter, you will get True. This means that the interpreter is running:
while (variable != 'quit') or True or True or True:
# do stuff
variable = input("")
which obviously never breaks. What you need to do is check all options; Kind Stranger has one solution but more explicitly, you could try
while variable not in ('quit', 'Quit', 'q', 'Q'):

Try this:
while (variable != "quit" and variable != "q" and variable != "Q" and variable != "Quit"):
You cannot do variable != "q" or "Q" etc.

Related

Struggling with loops and statements

So I've almost finished a calculator but after giving the results, I want it to ask if I'm still gonna use it.
At the beginning of the code I have this loop to make it start again unless I typed 'n'.
# LOOP TO MAKE IT STAY ON
import sys
from colorama import init
from colorama import Fore, Back, Style
init()
while True:
Then the rest of the code which is finished goes on.
Then, at the end, I've tried this:
answer = input()
def badanswer():
if answer != "y" or "n":
return True
else:
return False
while badanswer is True:
print ("Wrong answer")
answer = input(("Wanna keep using the calculator? y/n "))
if badanswer is False:
if answer == "y":
continue
else:
break
sys.exit()
Somehow when I test it I type a random letter (not y or n) and the program continues... What I am missing here? I'm pretty new to python so forgive my mistakes! Thanks.
One problem is the
if answer != "y" or "n":
"or" is a logical operator, and does not allow you to "double" a != comparison like you are trying to do. The actual meaning of this statement is if answer is not "y", or if "n", and "n", like any nonempty string, is always True in boolean context.
You want
if answer not in ("y", "n"):
You also need to actually call badanswer() by adding the parentheses.
There's also no reason to add the if True to the loop condition — while badanswer() does the same thing.
badanswer is a function, not a boolean. You need to call the function and get its return value, like so: if badanswer() is True
However, your logic for exiting the program is needlessly contrived. You don't need the badanswer function at all. Just get the input from the user and check whether it is 'y' or 'n'.
while True: # loop for exit prompt
answer = input("Wanna keep using the calculator? y/n ").lower()
# using .lower() to permit 'Y' and 'N' as well
if answer == "n":
sys.exit()
elif answer == "y":
break
# exits from the 'exit prompt' loop,
# returns to the outside calculator loop
else:
print("Bad answer!")
Note: As mentioned in the comments, sys.exit() is a pretty cutthroat way to exit your program. You can do it more gracefully by modifying a variable that is checked by the outer calculator loop; e.g., initialize a variable keep_running = True, run the main loop with while keep_running: (...) and if the user requests to exit from the calculator, set keep_running = False so that the main loop exits.

If statement not working properly inside a while loop [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)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 3 years ago.
So I'm doing a calculator in python, I have the code for it inside a while loop and a prompt to ask the user if they want to restart the program (that's what the while loop is for) but it does not seem to work properly, am I missing something? I'm kinda new to programming so maybe there is something blatantly wrong that I just don't see. (I did not add the full code but I did import the necessary libraries ("sys" and "math"))
var1 = True
while var1 == True:
op = eval(input("\n Your operation: "))
print(f"\n The result would be: {op}")
var2 = input("\n Would you like to do another operation? If so type yes: ")
if var2 != "yes" or "Yes" or "YES" or "y" or "Y" or "1":
print("\n Ok then, exiting... \n")
sys.exit()
So if the user types, for example, "yes" in the prompt, it should restart the program, but it executes the if statement anyways and closes the program even though the condition for it doesn't apply.
I have tried adding an "else" statement like this:
if var2 != ... :
sys.exit()
else:
print("Restarting...")
But it doesn't seem to work either.
I've also tried doing it the other way around, that is instead of checking if it does not match, check if it does match. Like this:
if var2 == ... :
print("Restarting...")
else:
sys.exit()
But that just gets stuck in the while loop and does not close the program.
I just don't see what's wrong in the code.
The correct way of doing it would be:
if var2.lower() not in ("yes", "1"):
print("Ok then, exiting...")
sys.exit()
You’re logic is backwards you need to exit if it ISNT yes also instead of using or (plus you’re using it incorrectly) use in and instead of typing all the different variations of Yes use star.lower():
var1 = True
while var1 == True:
op = eval(input("\n Your operation: "))
print(f"\n The result would be: {op}")
var2 = input("\n Would you like to do another operation? If so type yes: ")
if var2.lower() not in ("yes", "1"):
print("\n Ok then, exiting... \n")
sys.exit()

How can I use a while loop to run through several functions in python

I have two functions, one checks if you would like to add any items to a dictionary, and then checks what the value of that item is and saves that data to a file. If you are done adding new items to the dictionary it moves to the next function that checks if you would like to change the value of any currently existing items. If everything is good to go you can command the program to exit.
My problem is creating the while loop and to make it call the first function and run it but when you have no more items to add I need it to call the next function and makes sure you don't need to change any values of currently existing items. And then when the exit command is put in it exits the while loop and the program quits. I can't figure out how to make the while loop determine the first function is over and to call the next one.
I had made the program work properly by using recurrence and no while loop. But somebody told me that was sloppy. Also I made it work when I built the functions inside the while loop, but they told me that was sloppy too. So I am trying to make the while loop after the functions are built and call for the functions inside of it. Thanks in advance and hopefully my question is clear.
# current dictionary
itemNames = {}
# checks if you want to add to your dictionary
def addToDictionary():
checkIF_newItems = raw_input("Add new item? 'YES' or 'NO' \n ").upper()
if checkIF_newItems.startswith("Y"):
newItems = raw_input("What type of item would you like to add today? \n")
newItems_Name = raw_input("What is the value of your new item? \n")
itemNames[newItems] = newItems_Name
return True
elif 'PRINT' in checkIF_newItems:
print "These are your current items. \n\n"
return True
elif checkIF_newItems.startswith("N"):
print("OKAY")
exit()
elif 'Exit' in checkIF_newItems:
exit()
# checks if you want to edit your current dictionary
def check_forChanges():
#checks user intent and if YES prints current keys
checkIf = raw_input("Change item value? 'YES' 'NO' 'EXIT' 'ADD' 'PRINT' \n").upper()
print("\n")
if checkIf.startswith("Y"):
for i in itemNames.keys():
print i
print("\n")
#finds what key to access and ask for its new value
itemChoice = raw_input("what item would you like to change the value of? \n")
return True
if itemChoice in itemNames.keys():
newName = raw_input("What is the new value? \n")
itemNames[itemChoice] = newName
print("You've changed your " + itemChoice + "'s value to " + newName + ".")
return True
print('\n')
return True
#if NO then checks to exit
elif checkIf.startswith("N"):
CLOSE = raw_input("OKAY then, would you like to exit? ").upper()
if CLOSE.startswith('Y'):
exit()
return False
elif EXIT.startswith('N'):
check_forChanges()
elif EXIT is 'print':
for i in itemNames:
print i
return True
# goes back to first function
elif 'ADD' in checkIf:
addToDictionary()
return True
#prints current values
elif 'PRINT' in checkIf:
for i in itemNames.values():
print i
return True
elif 'EXIT' in checkIf:
exit()
return False
# main routine
validIntro = False
while not validIntro:
addToDictionary()
if addToDictionary() == False:
continue
else:
exit()
check_forChanges()
if check_forChanges() == False:
break
else:
continue
But I expect to be able to run this program until the user decides to quit. Also I expect the single while loop to call both of my functions but only when necessary.
My problem is creating the while loop and to make it call the first function and run it but when you have no more items to add I need it to call the next function and makes sure you don't need to change any values of currently existing items. And then when the exit command is put in it exits the while loop and the program quits. I can't figure out how to make the while loop determine the first function is over and to call the next one.
It sounds like you want to keep adding to the dictionary until the user says "nothing more to add" and then checks the values until the user quits. That would look something like:
while addToDictionary(): pass
while check_forChanges(): pass
You'd have to modify your existing functions to False when the current action is complete and to call sys.exit() when the user asks to quit. Although I don't think you need to ask for quitting -- if they don't want to add or check, then they're done and the loops have terminated.
Do you ever want the user to add to the dictionary after check_forChanges is called? If yes, but you still want to enforce adding is done, then checking, then maybe more adding, you want a loop around the whole thing:
keep_looping = True
while keep_looping:
while addToDictionary(): pass
while check_forChanges(): pass
keep_looping = askToContinue()

How do I continue a python program after a while loop exits?

I have a python3 program that guesses the last name of an individual based on the input of the user. But I figured out how to break if the user answer now, but when the user says yes it just re-enter the loop again with the same initial question.
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'no':
print("Great")
else:
time.sleep(2)
exit('Shame, thank you for playing')
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
DEMO - If the user answer 'yes'
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
etc.
So basically I want the program to exit on no, but continue on yes with the next question which is "Please tell me the first letter in your surname?"
Any idea?
I through after picking up some suggestion here, that I could use a while loop, but as the question stands, I did not get it right.
Please answer in a not so technical way, as my knowledge of python is very limited, still trying to learn.
I misunderstood the problem at first. You actually need to break the while loop when the user says Yes, so you can proceed to the 2nd question. And using an exit is fine when he says No, just remember that it will exit the whole program, so if you want to do something else after he says no, it might be better to use return and put them into functions.
Your code should be more or less like this:
import time
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
break # This will break the actual loop, so it can pass to next one.
elif answer.lower() == 'no':
# I recommend printing before so if it's running on a terminal
# it doesn't close instantly.
print('Shame, thank you for playing')
time.sleep(2)
exit()
# I suggest adding this else because users don't always write what we ask :P
else:
print('ERROR: Please insert a valid command.')
pass # this will make it loop again, until he gives a valid answer.
while True:
# code of your next question :P repeat proccess.
Feel free to ask any question you have about the code :)
As CoryKramer in the comments pointed out, use break instead of exit. Exit is a python function that exits the process as a whole and thus it shuts down the interpreter itself.
Break will close the closest loop it belongs to. Thus if you have two while loops, one written inside the other. A break will only close the inner while loop.
In general your code will go something like this
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
else:
time.sleep(2)
print("Thank you for playing!")
break
This will keep looping as long as the user keeps entering yes.
if you want to you an infinite while loop you need to control your loop state. Also i created a SurnameFunc. Using seperate functions is more readable for big projects.
def SurnameFunc():
return "Test Surname ..."
State= 0
lastname_tip = ""
while(True):
if(State== 0):
answer = input('Do you want me to guess your name? yes/no :')
if(answer == 'no') :
print ("You pressed No ! - Terminating Program ...")
break
else:
State = 1
elif(State == 1):
lastname_tip = input('Please tell me the first letter in your surname?').lower()
State = 2
elif(State == 2):
print ("Your Surname is ..." + SurnameFunc())
State = 0
print ("Program Terminated !")

Using multiple try statements with strings

Hi so I am working on a game and my game at the start asks the user if they want the rules to the game (y/n). I'm using if statements and else for this, so if user puts in y print rules and if user puts in n start game etc...it works fine, until the user puts in an integer or a word or something python doesn't recognize and it just goes and uses the else statement. My game is a math game so I used try statements before that if the user punched in something that's not a number it tells the user "Invalid, try again". The problem I'm having now is how to tell python to try multiple things...
I tried using try x = 'y' or x = 'n' but it says you can't give try multiple operations or something
Please help,
Cheers
You might want to use the following:
if inp=="Option1":
...
elif inp=="Option2":
...
elif inp=="Option3":
...
else:
print "Not known command"
You need a while loop that will keep taking input until the user inputs either y or n
while True:
inp = raw_input("Add intruction here")
if inp == "y":
# code here
elif inp == "n":
# code here
else:
print "Invalid input"

Categories