I was writing a code to get a student grade point average but I got an error. here is the piece of my code getting error :
scoreinput=input("Score lesson: ")
while True:
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
scoreinput = int(input("This number is too big. Try again: "))
elif scoreinput < 0:
scoreinput = int(input("This number is too low. Try again: "))
else:
print("please write number correctly...")
This is the output of this code which has got an error :
Score lesson: 5
Traceback (most recent call last):
File "e:\TEST PYTHON\test3.py", line 3, in <module>
if scoreinput.isnumeric():
AttributeError: 'int' object has no attribute 'isnumeric
please help me. thanks
If the input is a positive number below 20, which is what you want to have, after scoreinput=int(scoreinput)
you have the number, but instead of doing something, you continue to the next iteration of the while loop. On the next iteration, scoreinput
is an int
and not str
this is why you get an error. If scoreinput
is in the correct range, you should use break
to stop the loop.
Another problem occurs when the input is wrong. If the input is not a number, you are not getting a new input and will be stuck in an infinite loop. If the input is a number, but not between 0 to 20, you get new input and imminently cast it to int
. If the input is not a number you will get an exception. If it is a number, it will fail as soon as you reach the next iteration since scoreinput
should be str
at the beginning of the iteration, but it will be int
.
I would suggest you will use the following code:
while True:
scoreinput=input("Score lesson: ") # using input only one time at the beggining of the loop instead of input command for each case of bad input
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
print("This number is too big. Try again.")
elif scoreinput < 0:
print("This number is too low. Try again.")
else:
break # input is valid
else:
print("please write number correctly...")