Reputation: 27
I am failing at an optional task where i check the input of int(input("my string"))
with .isdigit()
without this optional task i solved task but i want to learn efficient so i need your help guys.
The task
get input of 2 integer numbers cast the input and print the input followed by the result Output Example: 9 + 13 = 22
Optional: check if input .isdigit() before trying integer addition to avoid errors in casting invalid inputs
My code so far
int_nmbr1 = int(input("Enter first number: "))
int_nmbr2 = int(input("Enter second number: "))
if int_nmbr1.isdigit() & int_nmbr2.isdigit() == True: #Here i check it with is.digit() twice
print(int_nmbr1, " + ", int_nmbr2, " = ", int_nmbr1 + int_nmbr2)
Console Error Output
AttributeError Traceback (most recent call last) in () 3 int_nmbr2 = int(input("Enter second number: ")) 4 ----> 5 if int_nmbr1.isdigit() & int_nmbr2.isdigit() == True: 6 print(int_nmbr1, " + ", int_nmbr2, " = ", int_nmbr1 + int_nmbr2)
AttributeError: 'int' object has no attribute 'isdigit'
Upvotes: 0
Views: 772
Reputation: 477
You’re trying to implement isdigit
on int
data type while it is a method of str
.
By using int(input())
, your input is already an int
value if you enter any value with base10. So you don’t need to use isdigit
. isdigit
is used to check if it is any digit in string format.
If you’ve still any doubt, you can check dir(str)
and dir(int)
. And furthermore, you can check the print(help(str.isdigit))
.
And now, in case of wrong data type entered, you can use exception handelings
.
You can use it like this:
try:
int(input(“enter any number:”))
except ValueError:
print(“Please enter any integer value only”)
int(input(“enter any number:”))
Above code will not return error if you’ll enter any other data type instead of integer for first time.
Upvotes: 0