-4

For some reason when I try to use isalpha() here in the if statement, it keeps being ignored and proceeds to the next line. If I use isdigit(), the code works as expected. I'm just trying to understand why isalpha() doesn't work here?

user_input1 = input("Enter the first number")
if user_input1 == user_input1.isalpha():
    print ("Please use only numbers")
user_input2 = input("Enter the second number")
add_ints = int(user_input1) + int(user_input2)
print (user_input1,"+" ,user_input2, "=", add_ints)
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Kevan
  • 3
  • 1
  • 6
    `user_input1.isalpha()` returns either `True` or `False`. There's no way your input could be either of those values, so the ceeck will always fail. – Patrick Haugh Jun 18 '18 at 18:22
  • 5
    You want `if not user_input1.isdigit():`. See also [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). – glibdud Jun 18 '18 at 18:24

1 Answers1

0

There are two errors in your code.

First, doing user_input1 == user_input1.isalpha() compares a string and a boolean, this will always be False.

Second, checking user_input1.isalpha() checks if the string is composed only of alphabetical characters. This will not print if only some characters are alphabetical.

'123a'.isalpha() # False

What you want to do is to print if any character is not numerical with not and str.isdigit.

user_input1 = input("Enter the first number: ")
if not user_input1.isdigit():
    print ("Please use only numbers")

Alternatively, you can always try to cast your inputs to int and catch the exception.

try:
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    print(f'{num1} + {num2} = {num1 + num2}')
except ValueError:
    print("Please use only numbers...")
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73