Unable to get desired outcome of a while True loop - python

Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break

You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...

Related

How to make it my code go back to a specific while loop in python?

I'm new to Python and I am trying to create a simple calculator. Sorry if my code is really messy and unreadable. I tried to get the calculator to do another calculation after the first calculation by trying to make the code jump back to while vi == true loop. I'm hoping it would then ask for the "Enter selection" again and then continue on with the next while loop. How do I do that or is there another way?
vi = True
ag = True
while vi == True: #I want it to loop back to here
op = input("Input selection: ")
if op in ("1", "2", "3", "4"):
vi = False
while vi == False:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
break
#Here would be an If elif statement to carry out the calculation
while ag == True:
again = input("Another calculation? ")
if again in ("yes", "no"):
ag = False
else:
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
exit()
elif again == "yes":
print("okay!")
vi = True #I want this part to loop back
Nice start. To answer your question about whether there's another way to do what you're looking for; yes, there is generally more than one way to skin a cat.
Generally, I don't use while vi==True: in one section, then follow that up with while vi==False: in another since, if I'm not in True then False is implied. If I understand your question, then basically a solution is to nest your loops, or call one loop from within the other. Also, it seems to me like you're on the brink of discovering the not keyword as well as functions.
Code
vi = True
while vi:
print("MENU")
print("1-Division")
print("2-Multiplication")
print("3-Subtraction")
print("4-Addition")
print("Any-Exit")
op = input("Input Selection:")
if op != "1":
vi = False
else:
x = float(input("insert first number: "))
y = float(input("insert Second Number: "))
print("Placeholder operation")
ag = True
while ag:
again = input("Another calculation? ")
if again not in ("yes", "no"):
print("Please input a 'yes' or a 'no'")
if again == "no":
print("Done, Thank you for using Calculator!")
ag = False
vi = False
elif again == "yes":
print("okay!")
ag = False
Of course, that's a lot of code to read/follow in one chunk. Here's another version that introduces functions to abstract some of the details into smaller chunks.
def calculator():
vi = True
while vi:
op = mainMenu()
if op == "\n" or op == " ":
return None
x, y = getInputs()
print(x + op + y + " = " + str(eval(x + op + y)))
vi = toContinue()
return None
def mainMenu():
toSelect=True
while toSelect:
print()
print("\tMENU")
print("\t/ = Division; * = Multiplication;")
print("\t- = Subtract; + = Addition;")
print("\t**= Power")
print("\tSpace or Enter to Exit")
print()
option = input("Select from MENU: ")
if option in "/+-%** \n":
toSelect = False
return option
def getInputs():
inpt = True
while inpt:
x = input("insert first number: ")
y = input("insert second number: ")
try:
tmp1 = float(x)
tmp2 = float(y)
if type(tmp1) == float and type(tmp2) == float:
inpt = False
except:
print("Both inputs need to be numbers. Try again.")
return x, y
def toContinue():
ag = True
while ag:
again = input("Another calculation?: ").lower()
if again not in ("yes","no"):
print("Please input a 'yes' or a 'no'.")
if again == "yes":
print("Okay!")
return True
elif again == "no":
print("Done, Thank you for using Calculator!")
return False

I am Facing a problem i Python where a user says "yes" or "no" the loop still executes anyhow. Why is it so?

I am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???
print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")
def addition():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number. !!"))
result = num1 + num2
return result
def subtraction():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number.!!"))
result = num1 - num2
return result
def multiplication():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 * num2
return result
def division():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 / num2
return result
print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"
while select:
choice = str(input("You Choose The Operation."))
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select=str(input('Continue Yes or No '))
print("Thank you..!")
You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping
In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.
To fix this, you should have the while loop check if select is "yes":
while select.lower().strip() == "yes":
choice = input("You Choose The Operation. ")
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select = input("Continue Yes or No ")
print("Thank you..!")
Also, input() returns a string so you don't need to wrap it in a str() call.

Breaking out of loop - Python

I've tried googling and searching on SO, but I cant figure out why my break on the second to last line is not heading out of the while loop. Better yet, I cant figure out why the loop is not continuing either. My intention is to give the user the possibiltiy to head to the main menu after the last choice (basically the while loop for menuchoice (which is one loop above what I have pasted here).
Any suggestions? Thank you in advance. It feels like I'm missing something essential.
#this is going to show how many exercise weapons you need for next magic level
if menuchoice == "4":
#these functions returns the amount of magic wands/rods that is needed to be spent for next magic level
print("Select vocation")
print("Press P for Royal Paladin")
#ask user to input vocation:
while True:
vocationchoice = input()
if vocationchoice == "P" or vocationchoice == "p":
#ask user to input magic level for paladin
num1 = float (input("Enter your magic level: "))
#ask for own training dummy
print("Do you have your own exercise dummy? Type Y for yes and N for no.")
while True:
trainingdummy = input()
if trainingdummy == "y" or trainingdummy == "Y":
#list the different exercise weapons
print("Select exercise weapon:")
print("1. Training rod")
#loop, where we ask user to input what exercise weapon they want to calculate
while True:
while True:
weaponchoice = input()
if weaponchoice == "q":
sys.exit() #quit the program
if weaponchoice == "1" or weaponchoice == "2" or weaponchoice == "3" or weaponchoice == "f":
break #break out of the input loop
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")
if trainingdummy == "n" or trainingdummy == "N":
#list the different exercise weapons
print("Select exercise weapon:")
print("1. Training rod")
#loop where ask user to input what exercise weapon they want to calculate
while True:
weaponchoice = input()
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpal(num1))) + ".")
elif weaponchoice == "f":
break
print("\nGo to main menu? Press F.")
This will help you I think. Break only breaks from current loop. If you want to go up on levels you need to break from each loop separately.
A suggestion is to turn a loop into a function and use return which will effectively exit any loop. A little bit of code refactor will be needed though.
If not the case can you maybe provide some more info and possibly the full code (there is a higher loop that we dont see here?)
First, you should print things in the input() command as it will be cleared in intend: input("Text to display").
Second, if you want to exit to the main menu, you need to break every nested loop. Here you only break the most inner loop.
As in Python there is no goto instruction nor named loops, you can use a flag. A flag is set to true when the used presses 'F' and this flag is then used at the beginning of every outer nested loop to break them. It can look like this:
while True: # This is your menu loop
menuFlag = False # Declare and set the flag to False here
menu = input("Choose the menu: ")
# ...
while True: # Choose character loop
if menuFlag: break # Do not forget to break all outer loops
character = input("Choose a character: ")
# ...
while True: # Any other loop (choose weapon, ...)
weapon = input("Choose weapon: ")
# Here you want to return to the menu if f is pressed
# Set the flag to True in this condition
if weapon == "f":
menuFlag = True
break
In your game this ressembles to:
goToMainMenu = False
while True:
if goToMainMenu: break
vocationchoice = input("Select vocation.\nPress P for Royal Paladin: ")
if vocationchoice == "P" or vocationchoice == "p":
#ask user to input magic level for paladin
num1 = float (input("Enter your magic level: "))
#ask for own training dummy
while True:
if goToMainMenu: break
trainingdummy = input("Do you have your own exercise dummy?\nType Y for yes and N for no: ")
if trainingdummy == "y" or trainingdummy == "Y":
#loop, where we ask user to input what exercise weapon they want to calculate
while True:
while True:
weaponchoice = input("Select exercise weapon:\n1. Training rod: ")
if weaponchoice == "q":
sys.exit() #quit the program
if weaponchoice == "1" or weaponchoice == "2" or weaponchoice == "3" or weaponchoice == "f":
break #break out of the input loop
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")
if trainingdummy == "n" or trainingdummy == "N":
#list the different exercise weapon
#loop where ask user to input what exercise weapon they want to calculate
while True:
weaponchoice = input("Select exercise weapon (press F for main menu):\n1. Training rod: ")
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")
elif weaponchoice == "f" or weaponchoice == "F":
goToMainMenu = True
break
Add a break for weaponchoice == "1" to get out of the loop.

How to sucsessfully ask the user to choose between two options

New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.
inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.
Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")
Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])

how to add restart command in python? [duplicate]

This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 4 years ago.
This is a simple calculator i wrote but after finishing it won't restart the application
this is my code:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
choice = input("Enter choice(a/s/m/d):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd':
print (" the letter you intered is not in our lists!")
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
input("press enter to close")
when its finished i want it to ask the user if they want to restart or not . i used different while looping its not working.
Just loop until the user wants to quit:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = input("Enter choice(a/s/m/d) or q to quit:")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue # if invalid input, ask for input again
elif choice == "q":
print("Goodbye.")
break
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
I used str.format to print your output, if choice not in {"a", "s", "m", "d","q"} uses in to test for membership replacing the long if statement.
You might want to wrap the int input inside a try/except to avoid your program crashing if the user does not enter the correct input.
try:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
except ValueError:
continue
If you want to do it like the example in your comment:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = raw_input("Enter choice(a/s/m/d)")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
inp = input("Enter 1 to play again or 2 to exit")
if inp == "1":
main()
else:
print("thanks for playing")
break
Instead of this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
Use this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
elif choice==e:
print("goodbye")
break
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
You'll need to wrap the part that's processing user input in a while loop. You'll also need an option to break that while loop in your selection process. I added an input value of e that handles exiting the loop. Your first if statement and the else statement at the end were redundant, so I switched them around a little as well.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
while True:
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
print("E.Exit")
choice = input("Enter choice(a/s/m/d/e):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == 'e':
print("Goodbye")
break

Categories