我需要制作两个不同的错误消息:一个是用户输入数字,一个是输入操作数(一个是方程式计算器)。 到目前为止我的代码如下:
#If user just presses enter:
if len(theParts) == 0 :
print("You have not entered an equation. Please, try again!")
# If input is a word:
elif equation.isalpha():
print("You have entered a word instead of an equation!")
elif len(theParts) == 1 :
print("You have only entered an operand/operator. Please, try again!")
elif len(theParts) == 2 :
print("You have not entered a complete equation. Please, try again!")
我也尝试过equation.isnumeric(),但也包括符号。有没有办法区分数字和符号,或者我必须为每个操作数做这样的事情:
elif '*' in theParts and len(theParts) == 1:
print("error")
答案 0 :(得分:2)
我认为有两种方法可以做到这一点:
str.isdigit()
。"12345".isdigit() # true
"123.45".replace('.', '').isdigit() # true
"12*4.3".isdigit() # false
def is_good_number(s):
for char in s:
if not char in '1234567890.':
return False
return True
is_good_number("12345") # true
is_good_number("123.45") # true
is_good_number("12*4.3") # false