我尝试使用以下代码创建计算器:
number_1 = " "
while number_1 not in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
number_1 = raw_input("Please enter your first number:")
if number_1 not in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
print "ERROR: Please type a valid number:"
print number_1
operator_symbol = " "
while operator_symbol not in ["+", "-", "*", "/"]:
operator_symbol = raw_input("Please enter an appropriate operator symbol:")
if operator_symbol not in ["+", "-", "*", "/"]:
print "ERROR: Please type one of the following operator symbols: +, -, *, /."
print operator_symbol
number_2 = " "
while number_2 not in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
number_2 = raw_input("Please enter your second number:")
if number_2 not in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
print "ERROR: Please type a valid number"
print number_2
当我处理它们时,它们是间隔开的。对于number_1
和number_2
我已经定义了我想要使用的字符('0'
- '9'
),但是当我使用大于9
的数字时,它给出了一个错误。
我想使用'0'
- '9'
作为可用字符,而不是特定数字。
答案 0 :(得分:0)
您正在检查number_1
是否为单个数字(列表中的某个元素)。
您要做的是检查number_1
是否只包含数字的字符串
您可以使用.isdigit()方法执行此操作。
此外,您应该只进行一次检查,而不是双重检查(在while和if中):
number_1 = raw_input("Please enter your first number:")
while not number_1.isdigit()
number_1 = raw_input("ERROR: Please type a valid number:")
答案 1 :(得分:0)
使用字符串的.isdigit()方法,您可以检查提供的输入是否为数字。
关于如何使用它,您可以执行以下操作:
number_1= raw_input("Enter your first number")
while not number_1.isdigit():
number_1 = raw_input("Error: Please enter a valid number: ")
同样对于number_2 ..诀窍是首先要求输入数字,如果数字不是数字,则继续询问用户输入数字
应该这样做。