如何防止用户输入超过999的值?

时间:2014-06-15 14:25:31

标签: python python-2.7

我正在为python做一个计算器用于学校作业但问题是,我的老师一无所知。我已经制作了计算器,但我需要添加一些代码,这样用户就无法输入大于999的数字,如果他们这样做,就会创建一个循环,软件询问用户输入的是什么。有什么帮助吗?

# Program make a simple calculator
# that can add, subtract, multiply
# and divide using functions

# define functions
def add(x, y):
   """This function adds two numbers"""

   return x + y

def subtract(x, y):
   """This function subtracts two numbers"""

   return x - y

def multiply(x, y):
   """This function multiplies two numbers"""

   return x * y

def divide(x, y):
   """This function divides two numbers"""

   return x / y

# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Invalid input")

我尝试过各种各样的东西,但没有任何作用 附:我有点像新手所以很容易 感谢

2 个答案:

答案 0 :(得分:2)

while True:
    num = int(raw_input('enter an integer <= 999: '))
    if num <= 999:
        break
    print('invalid input, please try again!')

print('you entered: {}'.format(num))

答案 1 :(得分:2)

MAX_VALUE = 999

def read_number(message):
    n = MAX_VALUE
    while (n >= MAX_VALUE):
        n = int(raw_input(message))
    return n

num1 = read_number("Enter first number:")
num2 = read_number("Enter second number:")

示例运行:

Enter first number: 1000
Enter first number: 56
Enter second number: 800