While loop not breaking? - python

I have written a main script that has a menu with 5 different options, the fifth option is if the user wants to quit the program. If the user types 5 in the main menu the program is supposed to quit, but it doesn't... It just keeps on looping through the menu. Can anyone help me resolve this issue??
menuItems = np.array(["Load new data", "Check for data errors", "Generate plots", "Display list of grades","Quit"])
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
break

You have nested loops, and break only breaks out of the inner loop.
To remedy this delete the nested loop and the break from the else block:
while True:
choice = displayMenu(menuItems)
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")

In your code, when you call break, it breaks from the inner while loop and goes to the outer while loop which causes the whole thing to go on again. If for some cases you want both of the while loops to break then you can use some sort of a flag.
Example,
flag = False
while True:
while True:
if (1 == var):
flag = True
break
if flag:
break
//Your code
flag = False
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
flag = True
break
elif (choice == 2):
checkErrors(grades)
flag = True
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
flag = True
break
else:
print("Invalid input, please try again")
flag = True
break
if True == flag:
break

Related

Python keyboard Input will be visible on the next input Statement

(im noob) I'm having a problem using the keyboard module, every time I use it all the input I enter will be visible on the next input statement.
while pamatoChooser:
pamatoChooser = True
pamatoScreen = True
piliCardo()
ownedChecker()
backUseNext()
inputChooser = keyboard.read_key()
if inputChooser == ("1"):
inputPamato = ('1')
break
elif inputChooser == ("b"):
# nothing here yet
pass
elif inputChooser == ("Esc"):
bMain = False
pamatoScreen = False
break
elif inputChooser == "n":
transition1()
johnnyLoop = True
while johnnyLoop:
piliJohnny()
ownedChecker()
backUseNext()
inputChoose1 = str(input("Choose your pamato: "))
if inputChooser == ('1'):
inputPamato = ('2')
pamatoChooser = False
break
elif inputChooser == ('b'):
transition2()
break

while loop printing everything twice, Python --checking if an input is an intiger AND in range (0-10)--

I am doing an excercise, created a while loop but it is printing everything twice. I'm pretty new at programming, so excuse me if this is some kind of stupid easy mistake.
def user_choice():
choice = "wrong"
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a number (0-10): ")
if choice.isdigit() == False:
print("Please enter a digit!")
if within_range == False:
print("Please enter a number in range (0-10)")
if choice.isdigit() == True:
within_range = int(choice) in range(0,10)
return int(choice)
Having multiple if statements means that it's possible the code will hit all 3 depending on the conditions.
Changing them to an if else block means it can only use one of them.
It's checks for a condition match from the top down so if it finds the conditions match in the first if then It would skip the remaining 2 options.
Your way, it would check the first if, and if it evaluates to True it would fire the code in the if block and then check the second if statement etc etc and so on.
Try this:
`def user_choice():
choice = "wrong"
within_range = False
while choice.isdigit() == False or within_range == False:
choice = input("Please enter a number (0-10): ")
if choice.isdigit() == False:
print("Please enter a digit!")
elif within_range == False:
print("Please enter a number in range (0-10)")
elif choice.isdigit() == True:
within_range = int(choice) in range(0,10)
return int(choice)`
You are evaluating the responses in the wrong order to be handled by the while statement.
Here is one way:
def user_choice():
choice_is_digit = False
within_range = False
while choice_is_digit == False or within_range == False:
choice = input("Please enter a number (0-10): ")
choice_is_digit = choice.isdigit()
if choice_is_digit == False:
print("Please enter a digit!")
continue # skip rest of loop
within_range = int(choice) in range(0,10)
if within_range == False:
print("Please enter a number in range (0-10)")
return int(choice)

Menu and submenu python

How can I return from a sub menu to a main menu?
Also I want to keep the data generated in the submenu.
Main menu:
1. Load data
2. Filter data
3. Display statistics
4. Generate plots
5. Quit
On option 2 I have a submenu:
1. S. enterica
2. B. cereus
3. Listeria
4. B. thermosphacta
5. Quit
def mainMenu():
menuItems = np.array(["Load data", "Filter data", "Display statistics", "Generate plots", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria", "B. thermosphacta", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
data = data[data[:,2] == 1] # 1 - S. enterica
elif choice == 2:
data = data[data[:,2] == 2] # 2 - B. cereus
elif choice == 3:
data = data[data[:,2] == 3] # 3 - Listeria
elif choice == 4:
data = data[data[:,2] == 4] # 4 - B. thermosphacta
elif choice == 5:
return data
continue
if choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
I implemented the break statement in the submenu and placed the menuItems inside the loops. This worked and data created in the submenu (subchoice) can be used in the mainMenu options 3 & 4.
import numpy as np
from displayMenu import *
from dataLoad import *
from dataStatistics import *
from dataPlot import *
from bFilter import *
def mainMenu():
while True:
menuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta", "Back to main menu"])
subchoice = displayMenu(menuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
if subchoice == 5:
break
continue
elif choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
Replace your code with this:
def mainMenu():
mainMenuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
subMenuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta"])
while True:
choice = displayMenu(mainMenuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
subchoice = displayMenu(subMenuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
break
# The answer is not a correct one
continue
elif choice == 3: # instead of if
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
You donĀ“t need a "Quit" option in your submenu - you want to repeat the nested loop (the submenu) only in the case of wrong answer (other as 1, 2, 3 or 4).
No action is needed to save the contents of your data variable as all action you perform are inside of your mainMenu() function. But if you need it outside of your function, use the return data statement as the very last in your function, outside of any loop.

Variable not being assigned value when returned from subprogram? Python 3?

I am trying to return a value from my subprogram, but when trying to use the variable in the main program, it comes up with an error saying it has not been assigned a value.
correct = 0
def subprogram():
correct2 = 0
loop = 0
while loop == 0:
loop2 = 0
memberID = input("Please enter your member ID: ")
if memberID == "1495":
print("Login successful!")
loop = 1
correct2 = 1
else:
print("Login unsuccessful.")
while loop2 == 0:
decision = input("<T>ry Again or <E>xit to Menu? ")
if decision == "t" or decision == "T":
print("Ok, restarting.")
print("")
loop2 = 1
elif decision == "e" or decision == "E":
print("Ok, exiting to main menu.")
print("")
loop2 = 1
loop = 1
correct2 = 0
else:
print("-----------------------------------------------------")
print("Sorry, this is not a valid answer. Please try again.")
print("-----------------------------------------------------")
continue
return correct2
#main
while correct == 0:
print ("Are you a member?")
member = input("<Y>es or <N>o? ")
if member == "y":
correct = subprogram()
if correct2 == 0:
correct = 0
elif correct2 == 1:
correct = 1
elif member == "Y":
correct = subprogram()
if correct2 == 0:
correct = 0
elif correct2 == 1:
correct = 1
elif member == "n" or member == "N":
print("Ok, not a problem! Welcome!")
correct = 1
else:
print("-----------------------------------------------------")
print("Sorry, this is not a valid answer. Please try again.")
print("-----------------------------------------------------")
correctVIP = 0
print("END")
How would I fix this error? Thankyou.
In your main while loop you don't define the correct2 variable so it throws an error when you try to do:
if correct2 == 0:
You assign the result of subprogram to correct:
correct = subprogram()
where you probably mean to do:
correct2 = subprogram()

indentation errors in main function for connect four in python

A few minutes ago my program was fine until I tried adding in a way to make the user be asked to play again. When I put in the loop and indented everything, something got messed up really bad when I took out this part since it didn't work. Now I cant fix the indentation and nothing will work correctly. Can anyone see obvious problems?
def main():
lastRow = 0
won = 0
draw = False
player1turn = True
print("Welcome to Connect Four!")
rows = input("Please enter a number of rows: ")
check = True
while check == True:
try:
if int(rows) <= 4:
while int(rows) <= 4:
rows = input("Please enter a Valid choice: ")
else:
check = False
except ValueError:
rows = input("Please enter a Valid choice: ")
columns = input("Please enter a number of columns: ")
check2 = True
while check2 == True:
try:
if int(columns) <= 4:
while int(columns) <= 4:
columns = input("Please enter a Valid choice: ")
else:
check2 = False
except ValueError:
columns = input("Please enter a Valid choice: ")
myBoard = []
myBoardTemp = []
for i in range(int(columns)):
myBoardTemp.append(0)
for i in range(int(rows)):
myBoard.append([0] * int(columns))
printBoard(myBoard)
check3 = True
while won == 0 and draw == False:
move = input("Please enter a move: ")
while check3 == True:
try:
if int(move) < 0 or int(move) > len(myBoard[0]):
while int(move) < 0 or int(move) > len(myBoard[0]):
move = input("Please enter a valid choice: ")
else:
check3 = False
except ValueError:
move = input("Please enter a valid choice: ")
myBoard, player1turn, lastRow = move2(myBoard,int(move) - 1,player1turn)
printBoard(myBoard)
won = checkWin(myBoard,int(move) - 1, lastRow)
draw = isDraw(myBoard, won)
if won == 1:
print("Player 1 has won!")
elif won == -1:
print("Player 2 has won!")
elif draw == True:
print("It is a draw!")
The line after while check3 == True: is not indented correctly
The try after while check3 == True: isn't properly indented, although I can't tell if that is a transcription error or was in your original code.

Categories