How to end program if input == "quit" with many if statements? - python

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":

Related

Python: Functions & Loops. Error: ValueError: invalid literal for int() with base 10:

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 ")

I'm having trouble with a continue statement

import json
import difflib
from difflib import get_close_matches
data = json.load(open("data.json"))
def Translate (w):
x= 3
while x != 0:
w = w.lower()
if w in data:
return data [w]
elif len(get_close_matches(w, data.keys())) > 0:
yn = input ("Did you mean %s Instead? Enter Y for yes, or no press N if not: "% get_close_matches(w, data.keys())[0])
if yn == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif yn == "N":
return "The word doesn't exist. Please check your spelling."
elif w.upper() in data: #in case user enters words like USA or NATO
return data[w.upper()]
elif w.title() in data: #if user entered "texas" this will check for "Texas" as well.
return data[w.title()]
else:
return "The word doesn't exist. Please double check it."
word = input("Enter word:")
print(Translate(word))
x -= 1
This what I trying to add in:
if x == 0:
input(" Would you like to keep searching? Y or N?")
elif yn == "Y":
continue
x+=3
elif yn == "N":
return "Have a nice day."
I trying to add a while loop to keep searching until the user wants to stop.
I'm still new to python if anybody can help me thankyou in advance!
You can do it in the following way!
while True:
in_put=input("Enter your word here or simply press return to stop the program\t")
if in_put:
"""DO stuff here"""
print(in_put)
else:
break
Change the program accordingly for your task!

How to "restart" the loop so that both Python lists are complete before the program ends?

I am trying to create a program in which the user enters 3 fruits and 3 nonfruits into two different lists.
The user first chooses the first list by typing in "fruits" or "nonfruits".
The user then enters each qualifying item until the first list is full.
My issue is that once the first selected list is full, the program ends.
I want the user to be prompted to enter in data into the other list until it also is full.
I thought that adding in the "while len(fruits) < 3 and len(notfruits) < 3:" would work, but it doesn't seem to make a difference.
How can I do this?
fruits = []
notfruits = []
print(fruits)
print(notfruits)
print("Please enter fruits or notfruits:")
y = str(input(": "))
while len(fruits) < 3 and len(notfruits) < 3:
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)
else:
print("Not a valid option!")
Consider using or instead of and
Move the input part inside the loop, or else y will never change
Here's what I mean:
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)
else:
print("Not a valid option!")

Python error in changing item in 2d list

I am making a Tic Tac Toe game and can't assign the sign of player/computer to 2d list.
array = []
player_choice = 0
computer_choice = 0
player_move_col = 0
player_move_row = 0
def starting_array(start_arr):
for arrays in range(0, 3):
start_arr.append('-' * 3)
def print_array(printed_arr):
print printed_arr[0][0], printed_arr[0][1], printed_arr[0][2]
print printed_arr[1][0], printed_arr[1][1], printed_arr[1][2]
print printed_arr[2][0], printed_arr[2][1], printed_arr[2][2]
def player_sign():
choice = raw_input("Do you want to be X or O?: ").lower()
while choice != 'x' and choice != 'o':
print "Error!\nWrong input!"
choice = raw_input("Do you want to be X or O?: ").lower()
if choice == 'x':
print "X is yours!"
return 2
elif choice == 'o':
print "You've chosen O!"
return 1
else:
print "Error!\n Wrong input!"
return None, None
def player_move(pl_array, choice, x, y): # needs played array, player's sign and our col and row
while True:
try:
x = int(raw_input("Which place do you choose?: ")) - 1
y = int(raw_input("What is the row? ")) - 1
except ValueError or 0 > x > 2 or 0 > y > 2:
print("Sorry, I didn't understand that.")
# The loop in that case starts over
continue
else:
break
if choice == 2:
pl_array[x][y] = 'X'
elif choice == 1:
pl_array[x][y] = "O"
else:
print "Choice didn't work"
return pl_array, x, y
starting_array(array)
print_array(array)
# print player_choice, computer_choice - debugging
player_move(array, player_sign(), player_move_col, player_move_row)
print_array(array)
It gives me an error :
pl_array[x][y] = "O"
TypeError: 'str' object does not support item assignment
How can i change the code to make it change the item I show the program to write "X" or "O" in it?
Just like the error says, 'str' object does not support item assignement, that is you cannot do:
ga = "---"
ga[0] = "X"
But you can use lists in your example by changing:
start_arr.append('-' * 3)
to
start_arr.append(["-"] * 3)

Ending a Python Script

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.

Categories

Resources