In Python 3.2, I'm writing up a basic menu program, and when the option to quit is entered, the function is not ending.
When quit is chosen, it ends the loop the rest of the script is in, and should terminate the script, but it isn't, for whatever reason?
Am I missing an 'end' function that kills the script, or is the new Python Shell just buggy?
Pretty sure this wasn't necessary in Python 2.7.
import random
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
while choice != "q" or choice != "Q":
while choice != "i" and choice != "I" and choice != "c" and choice != "C" and choice != "q" and choice != "Q":
print("Invalid menu choice.")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
if choice == "i" or choice == "I":
print("blahblah.")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>"))
if choice == "c" or choice == "C":
x = int(input("Please enter the number of x: "))
while x < 0:
x = int(input("Please enter the number of x: "))
y = int(input("Please enter the number of y: "))
while y < 0:
y = int(input("Please enter the number of y: "))
z = str(input("blah (B) or (P) z?: "))
while z != "b" and z != "p" and z != "B" and z != "P":
z = str(input("blah (B) or (P) z?: "))
if z == "b" or z == "B":
total = x*10 + y*6 + 0
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
#function that outputs the cost of premium z
if z == "p" or z == "P":
luck = random.randrange(1, 11, 1)
if luck == 10:
total = x*10 + y*6
print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
#below is the normal function, for when the customer is not a lucky winner
if luck != 10:
total = x*12.50 + y*7.50
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate\n(Q)uit\n>>>"))
Your condition is wrong:
while choice != "q" or choice != "Q": # this should be "and"!
always returns True, creating an infinite loop.
Also, you've got quite a convoluted bit of logic here. This can be simplified a lot:
import random
while True:
choice = str(input("\nMenu:\n(I)nstructions\n(C)alculate blah\n(Q)uit\n>>>")).lower()
if choice == "i":
print("blahblah.")
continue
elif choice == "q":
break
elif choice == "c":
while True:
x = int(input("Please enter the number of x: "))
if x >= 0: break
while True:
y = int(input("Please enter the number of y: "))
if y >= 0: break
while True:
z = str(input("blah (B) or (P) z?: ")).lower()
if z in "bp": break
if z == "b":
total = x*10 + y*6 + 0
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
#function that outputs the cost of premium z
else: # z must be "p"
luck = random.randrange(1, 11, 1)
if luck == 10:
total = x*10 + y*6
print("\nblah$", total, " blah z for ", x, " x and ", y, " y. blah!")
#below is the normal function, for when the customer is not a lucky winner
if luck != 10:
total = x*12.50 + y*7.50
print("blah $", total, " blah ", x, " x and ", y, " y. blah!")
else:
print("Invalid menu choice.")
continue
One way to perform quit operations in Python is to throw a custom exception and catch that exception explicitly. Please correct me if I am wrong, AFAIK this doesn't put a big over-head on your python program. It could done as simple as the what I show below:
...
class QuitException(Exception);
...
def MyMenuProgram():
...
...
...
if __name__ == '__main__':
try:
MyMenuProgram()
catch QuitException:
pass
catch Exception, e:
raise
As #Tim answered, your loop condition is wrong.
while choice != "q" or choice != "Q":
Let's take a look at this, logically:
if choice == "q", choice != "Q", loop condition evaluates to false or true, which is true
if choice == "Q", choice != "q", loop condition evaluates to true or false, which is true
if choice != "q" or "Q", loop condition evaluates to true or true, which is true
You need to change this loop condition to:
while choice != "q" and choice != "Q":
or
while choice.lower() != "q":
Edit: Redacted - input() is indeed the way to get user input in Py3k. Another of the glorious differences between Python 2.7 and Python 3.2.
Related
I am learning Python functions and loops; however, I am running in to an error when trying to calculate two variables assigned to an integer within a loop, I post my code below as well as a draw.io diagram so better explain what I am trying to accomplish:
in the included image the green represents a working loop, or function and the red represent a broken loop or function, the white represents not yet coded
in the included code, the loops work on input option m and l, however the loop does not work on option q. the q option will also not work with additions with the w,e and r options.
P.S I have coded nothing in the w, e, r or y options yet (as you can see) however I have assigned integers to the q,w,e and r variables.
q = 1
w = 2
e = 3
r = 4
def exitprogram():
print ("exiting...")
def q_function():
Q_loop = True
while Q_loop:
print("Q function selected, select addition - press k to go back or x to exit")
print("")
Q_addition = int(input("Add Q with "))
#exit program
if Q_addition =="x":
exitprogram()
break
#additions
elif Q_addition == "w":
q_w = q+w
print(q_w)
if Q_addition == "k":
start()
#invalid input
else:
print("invalid input - try again")
continue
def w_function():
print("W function operational")
W_addition = int(input("Add W with - to exit select x "))
def e_function():
print("E function operational")
E_addition = int(input("Add E with - to exit select x "))
def r_function():
print("R function operational")
R_addition = int(input("Add R with - to exit select x "))
def t_function():
T_loop = True
while T_loop:
T_selection = input("T function operational - press k to go back or x to exit ")
if T_selection == "k":
more()
elif T_selection == "x":
exitprogram()
break
else:
print("invalid input - try again")
continue
def y_function():
print("Y function operational")
def more():
moreloop = True
while moreloop:
l = input ("select t or y - to go back select k to exit select x ")
if l =="t":
t_function()
break
if l =="y":
y_function()
break
if l =="x":
exitprogram()
break
elif l =="k":
start()
else:
print("invalid input - try again")
continue
def start():
loop1 = True
while loop1:
a = input("select q, w, e or y - for more options select m or to exit select x ")
if a == "x":
exitprogram()
break
elif a == "q":
q_function()
break
elif a == "w":
w_function()
break
elif a == "e":
e_function()
break
elif a == "r":
r_function()
break
elif a =="m":
more()
break
else:
print("invalid input - try again")
continue
start()
Error traceback included below
Traceback (most recent call last):
File "x:/xxx/xxx/xxxx/xxxx.xx", line 115, in <module>
start()
File "x:/xxx/xxx/xxxx/xxxx.xx", line 95, in start
q_function()
File "x:/xxx/xxx/xxxx/xxxx.xx"", line 16, in q_function
Q_addition = int(input("Add Q with "))
ValueError: invalid literal for int() with base 10: 'w'
You have Q_addition = int(input("Add Q with ")) so are attempting to cast the input (x, k, e, etc) to an int. This throws the error. Also your logic checks for strings not int
#exit program
if Q_addition =="x":
Q_loop = False #set the loop variable to false to exit the loop and return to main function
#changed to elif as Q_addition can only be one option
elif Q_addition =="x":
...
elif Q_addition == "w":
#if you'd like addition with the other variables need to add them
elif Q_addition == "e":
q_e = q+e
print(q_e)
elif Q_addition == "r":
q_r = q+r
print(q_r)
...
#changed to elif, see above
elif Q_addition == "k":
remove the int() cast so Q_addition = input("Add Q with ")
This question already has answers here:
Python: Test if value can be converted to an int in a list comprehension
(3 answers)
Closed 1 year ago.
I wonder, if it's possible to show a message "Invalid...", whenever a user tries to input string in x or y instead of integers?
Here's the code :
print("Enter a operator first ('+-*/') or 'q' to Exit! ")
while True:
choice = input("Enter choice (one of these): '+', '-', '/', 'x': ")
if choice in ('x+-/'):
x = int(input("First number: "))
y = int(input("Second number: "))
if choice == "+":
print(x, "+", y, "=", x + y)
elif choice == "-":
print(x, "-", y, "=", x - y)
elif choice == "/":
print(x, "/", y, "=", x / y)
elif choice == "x":
print(x, "x", y, "=", x * y)
elif choice == 'q':
break
else:
print("Invalid choice. Try again.")
I tried these code to solve my problem but didn't succeed
if x != int:
print("invalid...")
# And Also
if x == str:
print ("invalid...")
Using these also, doesn't solves my problem:
Here's the error I get:
x = int(input("First number: "))
ValueError: invalid literal for int() with base 10: 'as'
I guessed it's because I indicated in the beginning that x =input must be in integer, but if i take away this "int" the whole project won't work and I'll get this error:
TypeError: can't multiply sequence by non-int of type 'str'
Yes, it is possible. Use a try/except block as follows:
try:
x = int(input("First number:"))
y = int(input("Second number: "))
except ValueError:
print('Invalid...')
You can do it this way:
while True:
choice = input("Enter choice (one of these): '+', '-', '/', 'x': ")
if choice in ('x+-/'):
x = input("First number: ")
y = input("Second number: ")
if x.isalpha() or y.isalpha():
print("invalid...")
else:
x=int(x)
y=int(y)
if choice == "+":
print(x, "+", y, "=", x + y)
elif choice == "-":
print(x, "-", y, "=", x - y)
elif choice == "/":
print(x, "/", y, "=", x / y)
elif choice == "x":
print(x, "x", y, "=", x * y)
elif choice == 'q':
break
else:
print("Invalid choice. Try again.")
I want the user to be able to quit this program at any point by typing in "quit".
Is there a way to do this with one instance of a break statement, or do I need to add a break to every "if y ==" statement in my code?
fruits = []
notfruits = []
print(fruits)
print(notfruits)
while len(fruits) < 3 or len(notfruits) < 3: # replaced `and` with `or`
print("Please enter fruits or notfruits:") #
y = str(input(": ")) # moved the input here
if y == "fruits":
while len(fruits) < 3:
x = str(input(": "))
x = x.strip()
if x in notfruits:
print(x + " is not a fruit!")
elif x in fruits:
print(x + " is already in the list!")
else:
fruits.append(x)
print(fruits)
elif y == "notfruits":
while len(notfruits) < 3:
x = str(input(": "))
x = x.strip()
if x in fruits:
print(x + " is a fruit!")
elif x in notfruits:
print(x + " is already in the list!")
else:
notfruits.append(x)
print(notfruits)
elif y == "clearfruits":
del fruits[:]
elif y == "clearnotfruits":
del notfruits[:]
elif y == "quit":
break
else:
print("Not a valid option!")
Create a function, use it each time you taker an input, call "exit()" to leave
For example
import sys
def check_quit(inp):
if inp == 'quit':
sys.exit(0)
You can use
import sys
sys.exit(0)
to immediately stop executing further program statements, so something like
elif y == "quit":
import sys
sys.exit(0)
should work.
Documentation: https://docs.python.org/3.5/library/sys.html#sys.exit
I think that both writing a function and using sys.exit are overkill for what OP asked, depending whether you're trying to break out of the loop or exit the program entirely
Specifically regarding your question, you can break right after your input() and it will exit the loop without executing the rest of the run. (BTW, you don't need to cast input to a string, input is a string by default)
y = input(": ")
if y.lower() == "quit":
break
if y == "fruits":
I'm a step away from completing my binary converter, though it keeps on repeating, it's and endless loop.
def repeat1():
if choice == 'B' or choice == 'b':
while True:
x = input("Go on and enter a binary value: ")
try:
y = int(x, 2)
except ValueError:
print("Please enter a binary value, a binary value only consists of 1s and 0s")
print("")
else:
if len(x) > 50:
print("The number of characters that you have entered is", len(x))
print("Please enter a binary value within 50 characters")
z = len(x)
diff = z - 50
print("Please remove", diff, "characters")
print(" ")
else:
print(x, "in octal is", oct(y)[2:])
print(x, "in decimal is", y)
print(x, "in hexidecimal is", hex(y)[2:])
print(" ")
def tryagain1():
print("Type '1' to convert from the same number base")
print("Type '2' to convert from a different number base")
print("Type '3' to stop")
r = input("Would you like to try again? ")
print("")
if r == '1':
repeat1()
print("")
elif r == '2':
loop()
print("")
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
else:
print("You didn't enter any of the choices! Try again!")
tryagain1()
print("")
tryagain1()
I'm looking for a way to break the loop specifically on the line of code "elif r== '3':. I already tried putting 'break', but it doesn't seem to work. It keeps on asking the user to input a binary value even though they already want to stop. How do I break the loop?
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
return 0
else:
print("You didn't enter any of the choices! Try again!")
choice = try again()
if choice == 0:
return 0
print("")
tryagain1()
return is suppose to be used at the end of the Function or code when you have nothing else to do
I wanted to add a confirmation for my code so that the user will be able to change their input. I haven't yet added the loop for the question but for some reason when I run this it fails to run def calc() and therefore the calculations I created cannot continue. Help!!
n=0
x=0
while True:
numbers = input("Please enter a, b,c, or, d to select a equation")
if numbers == "a":
n =3
x = 2
break
elif numbers =="b":
n = 4
x = 5
break
elif numbers == "c":
n=5
x=6
break
elif numbers == "d":
n=6
x=7
break
else:
print("Please enter a,b,c, or d")
w = float(input("Please enter weight"))
choice = input("Is this your answer?")
if choice == "yes":
def calc():
if n > w :
weight = (x - w)
weight2 = weight/n
print(weight)
elif w < x:
weight = (w - x)
weight2 = weight/n
print(weight)
calc()
elif choice =="no":
print ("Lets change it")
else:
print("Please respond with 'yes' or 'no'")