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

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.

Related

User options and validation

I am trying to get the user to input either 1, 2, or 3. If none of the numbers are entered an error message will be displayed and the program will ask for input again.
How do i identify if what the user typed is either 1,2, or 3?
This is what i currently have.
while True:
try:
userInput = input("Enter a number: ")
if userInput not in range(1,4):
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
elif userInput.isdigit('1'):
print('1')
elif userInput.isdigit('2'):
print('2')
else:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
If you want your input to be in range(1, 4), it needs to be an int, not a str (which is what's returned by input():
while True:
try:
userInput = int(input("Enter a number: "))
assert userInput in range(1, 4)
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
if userInput == 1:
print('1')
if userInput == 2:
print('2')
if userInput == 3:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
break
You have to check values of the same type. Your code compares string and int. You also need to work on the syntax of basic statements: if <condition>: except: isn't legal. Keep it simple:
userInput = None
while userInput not in ['1', '2', '3']:
userInput = input("Enter a number: ")

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

How to sucsessfully ask the user to choose between two options

New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.
inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.
Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")
Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])

How to accept only 5 possible inputs

In my program I have a menu that looks like this:
MenuChoice = ''
while MenuChoice != 'x':
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
try:
MenuChoice = str(input("Please enter your choice here ----------------->>>>>"))
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
I just want to know a way in which I can insure that only the numbers 1 to 5 are accepted and that if anything else is entered then the program asks the question again.
Please dont roast me.
Thanks
You're right to use a while loop, but think of what condition you want. You want only the numbers 1-5 right? So it would make sense to do:
MenuChoice = 0
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
while not (1 <= MenuChoice <= 4):
MenuChoice = input("Please enter your choice here ----------------->>>>>")
if MenuChoice == 'x' : break
try:
MenuChoice = int(MenuChoice)
except ValueError:
print("Please enter one of the menu choices above, TRY AGAIN ")
MenuChoice = 0 # We need this in case MenuChoice is a string, so we need to default it back to 0 for the conditional to work
We make our input an integer so that we can see if it's between 1-5. Also, you should put your beginning print statements outside of the loop so it doesn't continually spam the reader (unless this is what you want).
I think he needs a While true loop . Did using python 2.X
import time
print("Type 1 to enter the first option")
print("Type 2 to enter the second option")
print("Type 3 to enter the third option")
print("Type 4 to enter the fourth option")
print("Press x to quit")
while True:
try:
print ("Only Use number 1 to 4 or x to Quit... Thanks please try again")
MenuChoice = raw_input("Please enter your choice here ----------------->>>>> ")
try:
MenuChoice = int(MenuChoice)
except:
MenuChoice1 = str(MenuChoice)
if MenuChoice1 == 'x' or 1 <= MenuChoice <= 4:
print "You selected %r Option.. Thank you & good bye"%(MenuChoice)
time.sleep(2)
break
except:
pass

Breaking out of infinite loop

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

Categories