根据输入重新运行代码

时间:2015-09-26 23:07:36

标签: python

print("=======================PHONE ONE INPUT=============================")
    global name1
    name1=input("1).      What brand is your phone? ")
    condition=input("2).      What is the condition of your phone (new or used)? ")
    camera=input("3).      Does the phone have a Camera (true or false)? ")
    GPS=input("4).      Does the phone have GPS (true or false)? ")
    WiFi=input("5).      Does the phone have WiFi (true or false)? ")
    global price1
    price1=input("6).      Enter phone price($0-$1000) : ")
    if (price1>"1000" or price1<"0"):
        print("Invalid input, please re-run the simulation")
        def main():
    else:
        computeValue(condition,GPS,WiFi,camera)
        PhoneValue1=PhoneValue

如果用户输入的值大于1000或小于0,我试图让上面的代码从顶部重新运行。我将如何去做?

1 个答案:

答案 0 :(得分:0)

如果您想使用price1int()进行数字比较,则需要使用<>转换为整数 - 而不是将其用作字符串:

price1=int(input("6).      Enter phone price($0-$1000) : "))
if (price1> 1000 or price1 < 0):
    print("Invalid input, please re-run the simulation")
    main()

另外,如上所示,您需要使用main()来运行主要功能。 def main():定义了名为main的函数。

但是,您可能只想重复此输入,而不是在此输入中运行整个函数。您可以使用while循环执行此操作,类似于以下内容。

valid_price = False
while (not valid_price):
    price1 = int(input("6).      Enter phone price($0-$1000) : "))
    if (price1> 1000 or price1 < 0):
        valid_price = True
    else:
        print("Invalid input.")

Python 3 \ Python 2差异

在Python 2中,input将评估类型化表达式并返回评估值,因此键入52 + 3将为您提供整数5,例如

在Python 3中,input与Python 2中的raw_input相同,它将给定的输入解释为字符串,因此5将为您提供"5"和{ {1}}会给你2 + 3。这就是我们需要使用上面的"5"将输入转换为整数的原因。