Getting Error : 'int' object has no attribute 'isnumeric' - python

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

If you write on the top: scoreinput = int(input('Score lesson: ')) you won't have to verify if scoreinput is numeric or alphabetic.

Related

How to validate an integer with python that needs to be used in calculations

I'm trying to validate that a user input int is numbers only. This has been my most recent try:
while True:
NumCars = int(input("Enter the number of cars on the policy: "))
NumCarsStr = str(NumCars)
if NumCarsStr == "":
print("Number of cars cannot be blank. Please re-enter.")
elif NumCarsStr.isalpha == True:
print("Number of cars must be numbers only. Please re-enter.")
else:
break
With this, I get the following error:
line 91, in <module>
NumCars = int(input("Enter the number of cars on the policy: "))
ValueError: invalid literal for int() with base 10: 'g'
(I entered a "g" to test if it was working)
Thanks in advance!
Use try / except, and then break the loop if no exception is raised, otherwise capture the exception, print an error message and let the loop iterate again
while True:
try:
NumCars = int(input("Enter the number of cars on the policy: "))
break
except ValueError:
print("You must enter an integer number")
Thank you everyone for your suggestions! Unfortunately none of these answers did quite what I wanted to do, but they did lead me down a thought process that DID work.
while True:
NumCars = (input("Enter the number of cars on the policy: "))
if NumCars == "":
print("Number of cars cannot be blank. Please re-enter.")
elif NumCars.isdigit() == False:
print("Number of cars must be numbers only. Please re-enter.")
else:
break
After changing the NumCars input to a string, I validated with isdigit, and then when I needed the variable for the calculations, I converted it to integers at the instances where the variable would be used for calculations.
I don't know if it was the easiest or fastest way of doing this, but it worked!
if type(input) == int: do_code_if_is_numbersonly() else: print("Numbers Only")
This checks the type of the input, and if it is integer (number) it does example code, otherwise it prints Numbers Only. This is a quick fix but in my opinion it should work well.
You can utilize the .isnumeric() function to determine if the string represents an integer.
e.g;
NumCarsStr = str(input("Enter the number of cars on the policy: "))
...
...
elif not NumCarsStr.isnumeric():
print("Number of cars must be numbers only. Please re-enter.")

How to exit loop when input is nothing

I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.

Code doing arithmetic in loop even though it should be out of the loop

Once I enter q, I get the error:
Traceback (most recent call last):
File "C:\Users\Ossama\Desktop\Pytho\class_code\averages.py", line 9, in <module>
given4math=float(given)
ValueError: could not convert string to float: 'q'
This is the code:
count=0
summ=0.0
given4math=0.0
given="a"
while given != 'q':
given=str(input("Enter a number to be added to the average then hit enter to add the next one, or enter q to quit and have the average calculated: "))
count+1
summ=given4math+summ
given4math=float(given)
else:
print(summ/count)
You need to check for "q" before you use the value. You need to convert given to float BEFORE you add it in to the sum. The statement count+1 does nothing; it computes count + 1 and throws it away. This should work.
count=0
summ=0.0
while True:
given=input("Enter a number to be added to the average then hit enter to add the next one, or enter q to quit and have the average calculated: ")
if given == 'q':
break
count += 1
given4math=float(given)
summ=given4math+summ
print(summ/count)
While #Tim Robert's answer is correct, it will break your code if the user gives an input other than a number, or the letter 'q'. So if the user enters 'a' by mistake, it will throw an error. To address that, use try-except blocks to handle these errors.
count=0
summ=0.0
while True:
given=input("Enter a number to be added to the average then hit enter to add the next one, or enter q to quit and have the average calculated: ")
if given == 'q':
break
count += 1
try:
given4math=float(given)
except:
print("Invalid Input, please try again!")
continue
summ=given4math+summ
print(summ/count)

Checking min max without using function or list in python

min1=0
max1=0
while True:
num=input("enter a number")
if (num=='done'):
break
elif (num.isdigit()==False):
print("sorry enter integers or done")
elif (int(num)>max1):
max1=num
elif (int(num)<min1):
min1=num
print(max1)
print(min1)
This is throwing error '>' not supported between instances of 'int' and 'str'. I cannot take integer input as I have to break when the user enters done. Also, I have to account for non-integer values entered by user. How to rectify this code.
Assume num='5'. Then elif (int(num)>max1): holds and you assign '5' to max1. In the next iteration, max1 is a string and therefore you get an error. The solution is - max1=int(num) (and same for min1).
Another way to solve this is to convert the input to an integer once rather than using int(num) multiple times throughout the code.
This makes it easier to read later on.
An example of this is is changing
elif (num.isdigit()==False):
to
elif (num.isdigit()==True): or elif (num.isdigit()) (they do the same thing).
Then you can convert the string to an integer with
num = int(num)
Example:
min1=0
max1=0
while True:
num=input("enter a number")
if (num=='done'):
break
if num.isdigit():
num = int(num)
else:
print("sorry enter integers or done")
continue
if (num>max1):
max1=num
elif (num<min1):
min1=num
print(max1)
print(min1)

How to find random numbers in input?

I want the print statement to print the number in the range between the low and upper.
I keep getting the error code:
Traceback (most recent call last):File "python", line 5, in <module> ValueError: non-integer arg 1 for randrange()
From the program:
from random import*
lowRange = input('What is the lower range number?')
hiRange = input('What is the higher range nunmber?')
ran = randrange (lowRange,hiRange)
print (ran)
The input() function always returns a string. If you want to use integers, as in this case, you have to convert those strings to integers using int(). However, if the user enters something that cannot be converted to an integer (e.g. 'hi', or just hitting return), you will get an error when trying to convert. To deal with that, you will want to look into try and except statements. Hope that helps!
Try this:
In here until you enter a number it wouldn't stop. Inputs other than int will take as an invalid input.
What's wrong in your code is everything reads from input is taken as a string.
from random import*
while True:
try:
lowRange = int(input('What is the lower range number?'))
break
except:
print("That's not a valid input!")
while True:
try:
hiRange = int(input('What is the higher range nunmber?'))
break
except:
print("That's not a valid input!")
ran = randrange (lowRange,hiRange)
print (ran)

Categories

Resources