Breaking out of infinite loop - python

My code is not allowing me to break out of the infinite loop, and therefore exit the program. Here is my code:
while True:
print("\n1. Surname\n2. D.O.B\n3. Quit")
try:
select = int(input("Please select an option: "))
if select == 1:
surnameSearch()
elif select == 2:
DOB_search(BkRdr)
elif search == 3:
break
except:
print("That was an incorrect option, please try again:")
Here is what the input/output looks like:
1. Surname
2. D.O.B
3. Quit
Please select an option: 3
That was an incorrect option, please try agan:
1. Surname
2. D.O.B
3. Quit
Please select an option:

It should be select not search:
while True:
print("\n1. Surname\n2. D.O.B\n3. Quit")
try:
select = int(input("Please select an option: "))
if select == 1:
surnameSearch()
elif select == 2:
DOB_search(BkRdr)
elif select == 3:
break
except:
print("That was an incorrect option, please try again:")
Also, I suggest you use an else statement instead of a generic except clause as follows:
while True:
print("\n1. Surname\n2. D.O.B\n3. Quit")
try:
select = int(input("Please select an option: "))
except ValueError:
print("Not a valid input")
else:
if select == 1:
surnameSearch()
elif select == 2:
DOB_search(BkRdr)
elif select == 3:
break
else:
print("That was an incorrect option, please try again:")

Related

How to print superscript in Python

I'm aware of the sympy module in python and I know how to use it most of the time, however, I need to append different values to a list and then join it into a string. I need to append the superscript 'x' at the end of the list. Here's my code:
from functions import *
from subprocess import run
from sympy import pretty_print as pp
from sympy.abc import x
try:
run("clear", shell=True)
print("\033[92m[*] Initializing Exponential Equation Calculator", end='', flush=True)
print_dots(3)
while True:
print("\n\n================================Select Option================================")
print("1. Create exponential equation\n2. Calculate exponential growth\n3. Calculate exponential decay\n4. Exit")
try:
option = int(input(">>> "))
except ValueError:
handle_error("Please enter an option from above")
continue
if option == 1:
equation = ["y = "]
while True:
points_table = get_points()
for j in points_table:
i = 0
status = 0
while i < len(j):
if j[i] == 0:
yInt = j[i + 1]
status += 1
break
i += 1
if status == 1:
break
growth_rate = find_pattern(points_table)
if growth_rate is None:
handle_error("There is no exponential pattern in the table provided. Try again", 1)
continue
equation.append(str(yInt))
equation.append(" * ")
equation.append(str(growth_rate))
result = ''.join(equation)
print(f"\033[93m[*] Equation Calculated! The equation is \033[96m{result}\033[92m")
sleep(2)
while True:
try:
print("================================Select Option================================")
print("Would you like to:\n\n1. Calculate another equation\n2. Choose a different option\n3. Exit")
choice = int(input(">>> "))
if choice == 1 or choice == 2:
break
elif choice == 3:
raise KeyboardInterrupt
else:
handle_error("Please enter a valid option")
continue
except ValueError:
handle_error("Please enter a valid option")
continue
if choice == 2:
break
elif option == 2:
pass
elif option == 3:
pass
elif option == 4:
raise KeyboardInterrupt
else:
handle_error("Please enter an option from above")
continue
break
except KeyboardInterrupt:
print("\n\033[96m[*] Shutting down...\n\033[0m")
exit(0)
In the lines where there's 3 append functions, I don't know how I'm supposed to add the superscript 'x' to the end of the list. Can someone help me please?

ValueError: invalid literal for int() with base 10: 'E' [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I was trying to use an "Input" function to prompt a user to select an option.
print("1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
option = input("Please select an option: ")
while option != "E" and int(option) < 1 or int(option) > 2:
option = input("Please select a valid option: ")
if int(option) == 1:
dataset = pd.read_csv("portfolioStock.csv")
with open("portfolioStock.csv", newline='') as file:
for row in csv.reader(file):
stock.append(row)
elif int(option) == 2:
filename = input("Please enter filename with the extension:")
dataset = pd.read_csv(filename)
with open(filename, newline='') as file:
for row in csv.reader(file):
stock.append(row)
elif option == "E":
print("Press enter to return to menu.")
However when I debug the code, input 1 and 2 works well but an input E generated an error message "ValueError: invalid literal for int() with base 10: 'E'"
I have tried to print out the type of my input and it gives me "str" as expected. So I have no idea where my code goes wrong. Can anyone help me with this issue?
The line
while option != "E" and int(option) < 1 or int(option) > 2:
will always convert option to int to verify the second half of the and condition.
You do not even need the integers - simply compare for string values.
Not using integers at all - they are not needed for your usecase:
print("1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
while True:
option = input("Please select an option: ") # add .upper()?
if option not in ('1', '2', 'E'):
print("Invalid choice. 1, 2 or 'E' allowed.")
continue
if option == "1":
print(" Choice --> ", option)
elif option == "2":
print(" Choice --> ", option)
else: # "E"
print(" Choice --> ", option)
print("Quitting\n")
break
Or do it like it is done in Change your logic according to Asking the user for input until they give a valid response:
Using try: .. except: ... and integer conversion:
print("\n1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
while True:
try:
option = input("Please select an option: ")
option = int(option)
if option not in (1, 2):
raise ValueError() # outside bounds
print(" Choice --> ", option)
except ValueError:
if option == "E":
print("Quitting\n")
break
else:
print("Invalid choice. 1, 2 or 'E' allowed.")
(Indentical) Output for both codes:
1. Default Data Sheet
2. Upload Data Sheet
E. Exit
Please select an option: 4
Invalid choice. 1, 2 or 'E' allowed.
Please select an option: e
Invalid choice. 1, 2 or 'E' allowed.
Please select an option: 1
Choice --> 1
Please select an option: 2
Choice --> 2
Please select an option: E
Choice --> E
Quitting
"E" is a string, not a number. When you choose "E", the code stops at the while condition. Try to convert the variable "option" as a string type. You must change also the while condition
print("1. Default Data Sheet\n2. Upload Data Sheet\nE. Exit")
option = input("Please select an option: ")
while (option != "E" and str(option) != "1" and str(option) != "2"):
option = input("Please select a valid option: ")
if str(option) == "1":
print("you press 1")
elif str(option) == "2":
print("you press 2")
elif str(option) == "E":
print("Press enter to return to menu.")
Hope that helps.

How can i make this script shorter?

This is my first small python task when i found out about speedtest-cli.
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 2:
print(st.upload())
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
i am just a beginner so i could't find any way to shorten this code. Any tips would be helpful :)
If you don't care about execution time but only about code length:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
st.get_servers([])
tst_results = [st.download(), st.upload(), st.results.ping]
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option >= 1 and option <= 3:
print(tst_results[option-1])
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
else:
print("Please enter the correct choice")
else:
print("Test is ended")
Did not really make it smarter, just shorter by creating a list and take option as index in the list
First, you can look at this line:
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
this line happens on each of the options, so we don't need to repeat it. instead you can add it at the end of the "while" clause. also add "continue" to your "else" clause to avoid asking this when wrong input is entered.
also, the "else" clause for the "while" loop is not needed
e.g:
import speedtest
q = 1
while q == 1:
st = speedtest.Speedtest()
option = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice")
continue
q = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))
print("Test is ended")
second, there is an error in your logic. your prompt says enter 1 to continue or 2 to quit, and indeed when you enter 2 the loop will end, but also when the user enters 3 or any other number. Even worse, if a user will enter a character that is not a number or nothing at all, they will get an exception. For this we use try-except clauses. another way to do this kind of loop is using "while "True" and then using "break" to exit.
while True:
... your code here ...
q = input("enter 1 or 2:")
try:
q = int(q)
except ValueError:
print("Invalid input")
if q == 2:
break
print("Test is ended")
This is helpful to you if:
you are a pentester
or you (for some other arbitrary reason) are looking for a way to have a very small python script
Disclaimer: I do not recommend this, just saying it may be helpful.
Steps
Replace all \n (newlines) by \\n
Replace two (or four) spaces (depending on your preferences) by \\t
Put """ (pythons long quotation marks) around it
Put that oneline string into the exec() function (not recommended, but do it if you want to)
Applied to this questions code
exec("""import speedtest\n\nq = 1\nwhile q == 1:\n\t\tst = speedtest.Speedtest()\n\t\toption = int(input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: "))\n\t\tif\toption == 1:\n\t\t\t\tprint(st.download())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 2:\n\t\t\t\tprint(st.upload())\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telif option == 3:\n\t\t\t\tservernames =[]\n\t\t\t\tst.get_servers(servernames)\n\t\t\t\tprint(st.results.ping)\n\t\t\t\tq = int(input("Enter '1' if you want to continue or Enter '2' if you want to stop the test"))\n\n\t\telse:\n\t\t\t\tprint("Please enter the correct choice")\nelse:\n\t\tprint("Test is ended")\n""")
I have found the solution to that by using the sys module. i suppose this could work if a wrong data is input.
import speedtest
import sys
#Loop for options
while True:
st = speedtest.Speedtest()
option = input("What do you want to test:\n 1)Download Speed\n 2)Upload Speed \n 3)Ping \n Please enter the number here: ")
#To check if the input value is an integer
try:
option = int(option)
except ValueError:
print("Invalid input")
continue
if option == 1:
print(st.download())
elif option == 2:
print(st.upload())
elif option == 3:
servernames =[]
st.get_servers(servernames)
print(st.results.ping)
else:
print("Please enter the correct choice: ")
continue
q = 0
#Choice to continue or to end
while (q != 1) or (q != 2):
q = input("Enter '1' if you want to continue or Enter '2' if you want to stop the test: ")
try:
q = int(q)
except ValueError:
print("Invalid input")
continue
if q == 1:
break
elif q == 2:
sys.exit("Test is ended")
else:
print("Invalid input")
continue

While loop stopping even if it's False?

I thought the logic of my while loop made sense, but it abruptly stops after the first loop.
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
valid = False
while valid == False:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
return choice
if choice ==1:
valid=True
display_modules_average_scores()
menu()
elif choice ==2:
valid=True
display_modules_top_scorer()
menu()
elif choice==0:
exist=True
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
If I enter 5, it does:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
But if I enter 5 again, it stops the program. What am I doing wrong?
if I enter 5 again, it stops the program
Because you have a return statement that immediate ends the function you're running within.
You seem to be trying to create an infinite loop. You can start with testing exit and invalid conditions with this. Note:choice will never equal an empty string
while True:
choice=int(input("Enter choice (0 to exit):"))
if choice == 1:
pass # do something
elif choice == 2:
pass # do something else
elif choice == 0:
break
else:
print("Invalid choice, please enter again")
print("Thanks")
To exit the loop, you can use break, which executes code after the loop. Use return to end the function, as mentioned. There is a difference
If you're running this loop inside of the menu() function, you do not need to actually call the menu function again. That's the point of the while loop
By defining the function we can perform this task easily with no code duplication.
The Below code calls the function inputchoice() and then the inputchoice() will check the value entered by the user and if there the value is not valid then the inputchoice will call itself and the process continues untill the user enter correct input.
def inputchoice():
choice=int(input("Enter choice: "))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice!")
choice = inputchoice()
return choice
def menu():
choice = inputchoice()
print(choice)
if choice ==1:
valid=True
print("Do something if Valid = True")
elif choice ==2:
valid=True
print("Do something if Valid = True")
elif choice==0:
valid=True
print("Do something if Valid = True")
menu() #implementing menu function
I prefer making a dictionary with your functions, keeps the code clean in my eyes.
Consider this code here:
def choice1():
return 'choice1'
def choice2():
return 'choice2'
def defaultchoice():
return 'default'
choicedict = {
'1': choice1,
'2': choice2
}
while True:
choice = input("Enter choice (0 to exit):") # maintain as str to avoid error!
if choice == '0':
break
value = choicedict.get(choice, defaultchoice)()
print(value)
Single Function Code
def menu():
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice, please enter again")
menu()
elif choice ==1:
print("Oh, its working")
menu()
elif choice ==2:
print("Oh, its working")
menu()
elif choice==0:
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
menu()
Hi i would use a while loop like this. It would seem from this assignment that we are from the same institution. This is what i use for my code, I hope this helps.
while True:
user_input = input("Enter choice: ")
if (user_input == "0"):
print("=====================================================")
print("Thank You for using Students' Result System")
print("=====================================================")
break
elif(user_input == "1"):
display_modules_average_scores()
elif(user_input == "2"):
display_modules_top_scorer()
else:
print("Invalid choice, please enter again")

Loop back to a user entry point after running a script

Sorry quite new to python in the grand scheme of things, basically I want to be able to have an input screen that users have a selection of choices, when a choice has been made a command will run, then give the user the option to go back to the choices to choose another one, or to exit the program completely.
Currently I have
print ("1.")
print ("2.")
print ("3.")
errorch=0
while not errorch :
try :
choice = int ( input('Please Choose from Options below :') )
errorch = 1
except ValueError as e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
if choice == 1:
print ("CODE:")
elif choice == 2:
print ("OTHER:")
elif choice == 3:
print ("OTHER:")
else:
print ("Invalid Choice. Please Try Again:")
k=input('Press close to exit')
In each choice I do have code that runs, but to save space I have omitted this
Use a while loop.
while True: # this loop runs forever
print("1.")
...
print("4.") # this is for exit
# get input
if choice == 1:
...
# if choice is 4, then break out of this loop
elif choice == 4:
break # breaks out of the loop
else:
...
You can just wrap the whole thing in another while loop:
while True:
...
if k.lower() == "close":
break
You can use this same form to make your existing loop neater, removing the errorch flag:
while True:
try:
choice = int(input('Please Choose from Options below :'))
except ValueError as e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
else:
break

Categories