How to deal with User input errors in python - python-3.x

so basically I am trying to figure out how to make an error return if the user inputs the incorrect string type. For example, if someone were to type "y" instead of the six button on the keyboard, because they were typing their score to get the grade in the program, what would I do? I tried using an else statement to say that there was an error, but PyCharm gives me the green checkmark and then my program errors out saying:
Traceback (most recent call last): line 3, in
if int(score) >= 90: ValueError: invalid literal for int() with base 10: 'H'
this is confusing to me as I would think that the code would be read by the interpreter as checking if the input was an integer and then moving on through all the elifs i typed, then into the else statement, but I am wrong. What would be a better way to do this? Here is my code I wrote.
score = input("type your score on the exam as an integer to receive your letter grade\n")
if int(score) >= 90:
print("A")
elif int(score) >= 80:
print("B")
elif int(score) >= 70:
print("C")
elif int(score) >= 60:
print("D")
elif int(score) < 60:
print("F")
else:
input("ERROR: type your score on the exam as an integer to receive your letter grade\n")

Normally, you would wrap your "user menu" with a while, like this:
while True:
score = input("type your score on the exam as an integer to receive your letter grade\n")
try:
score = int(score)
except ValueError:
print("That's not an int!")
continue
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
elif score < 60:
print("F")
else:
print("Please write a valid option")
You can also add an option for user to leave or just let them press CTRL + C to close the process.

Related

array output and error: invalid literal for int() with base 10

I am debugging the python code to get user input as an array like [89.79,55,12] and generate the output as an array [HD,D,P,F]. However, the program is not accepting the array values and showing error: invalid literal for int() with base 10.
Please help.
#Blank variable to store user input and GPA
totals = []letters = []
Get and store user input
print ("Please enter the grade for each student, or press q to quit")
while(True):
user_input =input("> ")
if(user_input.lower() == "q"):
break
totals.append(user_input)
#Caclulate letter grade for each user response
for total in totals:
if int(total)<= 59:
letters.append("F")
elif int(total) <= 69:
letters.append("P")
elif int(total) <= 79:
letters.append("C")
elif int(total) <= 89:
letters.append("D")
else:
letters.append("HD")
#Print GPA results.
print("The GPA for your students is:{}".format(letters))

ValueError: invalid literal for int() with base 10: 'sdsd'

I have written a very basic program in python
when I'm trying to enter a string so that the interpreter shows "invalid" from else block
its showing an error: ValueError: invalid literal for int() with base 10: 'sdsd'
Code:
x = int(input("Enter a number: "))
if x== 0:
print("the number is 0")
elif x<10:
print("the number is less than 10: ", x)
elif x>10:
print("the number is greater than 10: ",x)
else:
print("invalid")
Try this. I have added an exception at the bottom of the program that will give you an error that you can define, rather than a syntax error you were previously getting.
You didn't have a rule set for if the value is equal to 10 either so I have included that. I agree with the user in the comments though, it's worth reading a bit more about exceptions and error handling: execeptions and error handling in python
while True:
try:
x = int(input("Enter a number: "))
if x == 0:
print("the number is 0")
elif x < 10:
print("the number is less than 10: ", x)
elif x > 10:
print("the number is greater than 10: ",x)
elif x == 10:
print("the number is equal to 10: ",x)
break
except ValueError:
print("No string values allowed")

How do i make my input take all int and str type of data

I'm trying to get a guessing game with the user input as an answer and if the user type exit the game will show the amount of time the player tried but the program won't run because it can only take either interger or string type.
import random
while True:
number = random.randint(1,9)
guess = int(input('guess the number: '))
time = 0
time += 1
if guess == number:
print('you guessed correct')
elif guess < number:
print('your guessed is lower than the actual number')
elif guess > number:
print('your guessed is higher than the actual number')
elif guess == 'exit':
print(time)
break
something like this
import random
time = 0
number = random.randint(1,9)
while True:
guess = input('guess the number: ')
time += 1
if guess == "exit":
print(time)
break
elif int(guess) < number:
print('your guessed is lower than the actual number')
elif int(guess) > number:
print('your guessed is higher than the actual number')
elif int(guess) == number:
print('you guessed correct')
print(time)
break
note that time and number have to be initializate outside the while loop, because if not, we would get different random numbers for each iteration, and also time would be initializate to 0 each time.
You can test the input as a string first before converting it to an integer:
while True:
response = input('guess the number: ')
if response == 'exit':
break
guess = int(response)
# the rest of your code testing guess as a number

python 3 try/except exiting rather than looping

I'm not sure what I'm doing wrong here. I'm trying to limit user input to 1-6 (dice game). The logic is working but when a ValueError() is raised it doesn't prompt the user again.
try:
while True:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
Because you're exiting your loop at Exception. You should write a code like this:
while True:
try:
choice = input('Enter number to hold - type D to roll: ')
print(choice)
if choice == 'D':
return choice_list
elif len(choice) > 1 or choice not in '12345':
raise ValueError()
else:
choice_list[int(choice) - 1] = 'X'
printer(roll_list, choice_list)
except ValueError:
print ("Invalid input")
Use while loop before try code which will keep looping try and catch block like this
while True:
try:
# Your Code
except ValueError:
# Your Code

User input accepting str and int (python)

I am new to programming and trying to make the user input accept both integer and strings. I have tried the following coding.. but not sure where I am going wrong. Any suggestions?
noAdults = input("Please enter the number of adults:")
while noAdults.isalpha():
print("Number must be valid and >= 0")
if noAdults.isdigit() and noAdults < 0:
print("Error")
noAdults = input("Please enter the number of adults:")
ValueError: invalid literal for int() with base 10:
I am guessing there is a ValueError because I have used the variable noAdults with isalpha and is making an error because it is in an int?
You need to verify that the input string is valid integer before you can check if it is non-negative
while True:
noAdults = input("Please enter the number of adults:")
try:
noAdults = int(noAdults)
except ValueError:
print("Not a valid number")
continue
if noAdults >= 0:
break
else:
print("Number must be >= 0")
It's throwing the exception before you handle the bad case of string inputs, it fails on the first line. You can check isalpha() before attempting the int(), or you can catch the ValueError exception.
To expand on chepner's solution, with a few extra print lines to show you what is going on:
while True:
noAdults = input("Please enter the number of adults:")
try:
noAdults = int(noAdults)
except ValueError:
print("Not a valid number")
continue
if noAdults >= 0:
break
else:
print("Not greater than 0")
print(noAdults)
This is a fully working version in Python 3.

Resources