ValueError: invalid literal for int() with base 10: 'sdsd' - python-3.x

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

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

How to deal with User input errors in python

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.

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

If statement error: ValueError: invalid literal for int() with base 10: ' ' and out of order int()

My code is as follows:
allnums = []
odds = []
evens = []
number = 0
while True:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '"+str(allnums[0])+"'")
break
if int(number) % 2 == 0:
evens.append(number)
evens.sort()
allnums.append(number)
allnums.sort()
if int(number) % 2 != 0:
odds.append(number)
odds.sort()
allnums.append(number)
allnums.sort()
else:
print("Invalid input")
I'm trying to create a program that reads a list of numbers and determines the lowest value, while also offering a list of even and odd numbers. I'm running into two issues with my code where the lowest number is not often correct, for example:
Enter a number or type 'done':33
Enter a number or type 'done':4
Invalid input
Enter a number or type 'done':6
Invalid input
Enter a number or type 'done':4
Invalid input
Enter a number or type 'done':6
Invalid input
Enter a number or type 'done':7
Enter a number or type 'done':44
Invalid input
Enter a number or type 'done':88
Invalid input
Enter a number or type 'done':done
=============================
Your even numbers are ['4', '4', '44', '6', '6', '88']
Your odds numbers are ['33', '7']
=============================
Your smallest number is '33'
I also get the following error when I use just a space(' ') as an answer, which I would like to write a print("Invalid input") response to something that is not a number or done, but always results in:
Traceback (most recent call last):
File "XXXX", line 17, in <module>
if int(number) % 2 == 0:
ValueError: invalid literal for int() with base 10: ' '
I know this has mostly to do with order of events, but what am I missing?
allnums = []
odds = []
evens = []
number = 0
while True:
try:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(sorted(evens)))
print("Your odds numbers are", str(sorted(odds)))
print("=============================")
print("Your smallest number is '"+str(sorted(allnums)[0])+"'")
break
elif int(number) % 2 == 0:
evens.append(number)
#evens.sort()
allnums.append(number)
#allnums.sort()
elif int(number) % 2 != 0:
odds.append(number)
#odds.sort()
allnums.append(number)
#allnums.sort()
pass
except:
print("Invalid input")
pass
are you sure, this is my output
deathnote#deathnote:~/Desktop/d$ python3 code.py
Enter a number or type 'done':12
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':qwe
Invalid input
Enter a number or type 'done':
Invalid input
Enter a number or type 'done':wqew
Invalid input
Enter a number or type 'done':done
=============================
Your even numbers are ['12']
Your odds numbers are []
=============================
Your smallest number is '12'
The error message is pretty clear: number contains a space, which can't be parsed into an integer. If you want to flag such input as invalid, you have to test it before trying to convert it to an integer (or catch the error that doing so generates).
You have two issues:
Need check for space before you are trying to get a number from it.
Then you are appending number input as string into your list, which will end with wrong sorting result as it will sort string instead of number.
allnums = []
odds = []
evens = []
number = 0
if number.lower() == 'done':
evens.sort()
odds.sort()
allnums.sort()
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '"+str(allnums[0])+"'")
break
if number.isspace():
print("Invalid input")
else:
number = int(number)
if int(number) % 2 == 0:
evens.append(number)
allnums.append(number)
elif int(number) % 2 != 0:
odds.append(number)
allnums.append(number)
allnums = []
odds = []
evens = []
number = 0
while True:
number = input("Enter a number or type 'done':")
if number.lower() == 'done':
print("=============================")
print("Your even numbers are", str(evens))
print("Your odds numbers are", str(odds))
print("=============================")
print("Your smallest number is '" + sorted(allnums)[0] + "'")
break
if not number.isnumeric():
print("Invalid input")
continue
if int(number) % 2 == 0:
evens.append(number)
evens.sort()
allnums.append(number)
allnums.sort()
if int(number) % 2 != 0:
odds.append(number)
odds.sort()
allnums.append(number)
allnums.sort()

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