Python isalpha()if语句被忽略
由于某种原因,当我尝试在if语句中使用isalpha时,它一直被忽略并继续到下一行。如果我使用isdigit,代码将按预期工作。我只是想弄明白为什么isalpha不在这里工作Python isalpha()if语句被忽略,python,python-3.x,Python,Python 3.x,由于某种原因,当我尝试在if语句中使用isalpha时,它一直被忽略并继续到下一行。如果我使用isdigit,代码将按预期工作。我只是想弄明白为什么isalpha不在这里工作 user_input1 = input("Enter the first number") if user_input1 == user_input1.isalpha(): print ("Please use only numbers") user_input2 = input("Enter the second
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)
代码中有两个错误 首先,doing user_input1==user_input1.isalpha比较字符串和布尔值,这将始终为False 其次,检查user_input1.isalpha检查字符串是否仅由字母字符组成。如果只有部分字符按字母顺序排列,则不会打印此项
'123a'.isalpha() # False
您要做的是,如果任何字符不是带有not和str.isdigit的数字,则打印
或者,您可以始终尝试将输入转换为int并捕获异常
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...")
user_input1.isalpha返回True或False。您的输入不可能是这两个值中的任何一个,因此ceeck将始终失败。如果不是用户,您希望输入1。isdigit:。另见。
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...")