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
Related
My program takes an input from the user about what they want to add. This works fine, but the problem arises when it comes down to the nested while loop that promps the user if they wish to add more items (y/n). I want y to start the loop from the beginning, n to exit the loop and continue the program, and any other input to give an error whilst restarting the y/n prompt.
I can't seem to figure out how to get out of the nested while loop nor can I figure out how to throw an error if the input is neither y or n. How would I go about fixing this?
elif user_input == "a":
while True:
try:
add_item = input("What item would you like to add? ").lower()
if not re.match("^[a-z, A-Z]*$", add_item):
print("ERROR: Only letters A-Z are allowed!")
continue
elif len(add_item) < 1 or len(add_item) > 20:
print("Item name is too long, only a maximum of 20 characters are allowed!")
continue
else:
item_amount = int(input("How many of these would you like to add? "))
shopping_list[add_item] = item_amount
print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
while True:
try:
add_more = input("Would you like to add more items? (y/n): ").lower()
if add_more == "y":
break
elif add_more == "n":
break
except TypeError:
print("ERROR: Expected y or n in return! Try again!.\n")
break
except ValueError:
print("\nERROR: Amount must be an integer! Try adding an item again!\n")
use boolean variable(keep_adding for below code) to decide while loop's terminal condition. It will be set to False iff add_more == "n"
use raise TypeError to raise error if user input is neither "y" nor "n".
You should remove break from except TypeError in order to keep asking "Would you like to add more items? (y/n): " if input is invalid.
elif user_input == "a":
keep_adding = True
while keep_adding:
try:
add_item = input("What item would you like to add? ").lower()
if not re.match("^[a-z, A-Z]*$", add_item):
print("ERROR: Only letters A-Z are allowed!")
continue
elif len(add_item) < 1 or len(add_item) > 20:
print("Item name is too long, only a maximum of 20 characters are allowed!")
continue
else:
item_amount = int(input("How many of these would you like to add? "))
shopping_list[add_item] = item_amount
print(f"{item_amount}x {add_item.title()} added to the shopping list.\n")
while True:
try:
add_more = input("Would you like to add more items? (y/n): ").lower()
if add_more == "y":
break
elif add_more == "n":
keep_adding = False
break
else:
raise TypeError
except TypeError:
print("ERROR: Expected y or n in return! Try again!.\n")
except ValueError:
print("\nERROR: Amount must be an integer! Try adding an item again!\n")
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
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".
In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.
import random
import sys
loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
print('Thank you!! Visit again.')
sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')
lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)
while loop == 'yes':
user_input1 = int(input('Please enter the first number: '))
user_input2 = int(input('Please enter the second number: '))
user_input3 = int(input('Please enter the third number: '))
print('Your numbers are: ', user_input1, user_input2, user_input3)
def check():
if lotto_numbers != [user_input1, user_input2, user_input3]:
return False
else:
return True
def fbcheck():
if lotto_numbers == [user_input1, user_input2, fireball_number]:
return True
elif lotto_numbers == [fireball_number, user_input2, user_input3]:
return True
elif lotto_numbers == [user_input1, fireball_number, user_input3]:
return True
else:
return False
retry += 1
result = check()
if (result == True):
print("Congratulations!! You won!!")
else:
print("Oops!! You lost.")
if (fireball == 'yes'):
fb_result = fbcheck()
if (fb_result == True):
print("Congratulations, you won a fireball!!")
else:
print("Sorry, you lost the fireball.")
print('No of retries remaining: ', (3 - retry))
if (retry == 3):
sys.exit()
loop = input('Do you want to try again? yes/no: ')
continue
else:
pass
print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
You don't need anything at all. Code inside the if block will execute and the script will run code after the if block.
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.
I.e.:
if some_condition:
# Do stuff
# Stop indent and do some more stuff
I think I gotcha your willing.
You want to execute something after the if condition is executed? So, create a subtask, and call it!
def finish_program():
print("something")
a = "foo"
print("finish program")
loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
print('Thank you!! visit again.')
finish_program()
I check to see if input can be changed into an integer if it can't it starts back from the beginning of UI(). I followed it through pycharm's debugger and it will pass the try, but when I try using 4 to exit.It will go through to the end, and then go back up to the except block.
I think the parts I commented after are the only relevant parts. Thanks for any help.
def UI():
global exitBool
global newBool
if not TV.tvList:
tv = TurnOnTV()
if TV.tvList:
l = list(TV.tvList.keys())
tv = TV.tvList.get(l[0])
print("1)change channel\n2)change volume\n3)Turn on another TV\n4)Exit\n5)Choose TV") #print accepted answers
choice = input()
try:
choice = int(choice) #try block and exception block
except:
print("\nInvalid Choice\n")
UI()
choice = int(choice)
if choice == 1:
if tv:
tv.changechannel(input("enter channel: "))
else:
print('sorry no tvs are available\n')
elif choice == 2:
if tv:
tv.changevolume(input("Enter in volume: "))
else:
print('Sorry no Tvs available')
elif choice == 3:
TurnOnTV()
elif choice == 4:
exitBool = True # exit bool to exit main loop
elif choice == 5:
tv = ChooseTV(input("Enter in TV name: "))
else:
print("Invalid Choice")
if tv:
tv.display()
def Main():
while exitBool == False: #Main Loop
UI()
When you catch the error and print "invalid choice" you must not call UI() again. That way you are making a recursive call, and when the inner UI() terminates the code goes on on the outer one.
Use a "while" statement to repeat a block of code until the user makes a valid choice.
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.