请帮我解决python loop / if语句

时间:2013-03-31 07:00:26

标签: python loops if-statement variable-assignment

* >重复循环,提示用户选择一个选项,然后运行

  

适当的命令并重复直到用户选择退出。   选项为:0退出程序; 1计算流量   特定的价值集合; 2计算雷诺数,和   3绘制预期流量。如果用户选择任何其他选项,   程序必须一直要求他们选择有效值,直到他们   这样做。 *

而我<= 3:

i=input (" Please enter a number between 0-3:")

if i==0:
    print " program will exit."
    break

elif i==1:
     print ( " To calculate flow rate please input these values:" )
     pressure = input (" Please enter pressure drop in pascals: " )
     radius = input  (" Please enter radius in m: " )
     viscosity = input  (" Please enter viscosity of liquid in Pa.s: ")
     Length= input  (" Please enter length in m: " )
     Flowrate = (pressure * pi *(radius**4))/ ( 8 * viscosity * Length)
     print " Therefore, flow rate is " , Flowrate
     print " Program will run again for user to calculate flow rate..."


elif i==2:
    print ( " To calculate reynolds number please input these values:" )
    q=input ("Please enter a value for flow rate in m^3/s")
    radius = input  (" Please enter radius in m: " )
    density=input   (" Please enter density in kg/m^3 : " )
    viscosity = input  (" Please enter viscosity of liquid in Pa.s: ")
    Rno=(2*q*radius*density)/(viscosity*pi*radius*radius)
elif i==3:
    print " not implemented yet."
else:
    print " Program will start again!"                          





    ***new edited post***

3 个答案:

答案 0 :(得分:4)

我能发现的一个错误就在这里:

Rno=(2*q*radius*density)/(viscosity*pi*radius*radius

您的代码缺少右括号。

另一个(逻辑)错误是input()调用应该在循环内部,而不是在它之外。

答案 1 :(得分:1)

我通常会让人们列出像

这样的程序
while(True):
    i = input("<Prompt>")

    if(i==1):
        # Do something

    elif(i==2):
        # Do something else

    #... any additional elifs

    else: 
        break

或者像这样

while(True):
    i = input("<Prompt>")

    if(i==1):
        # Do something

    elif(i==2):
        # Do something else

    #... any additional elifs

    elif(i==10):        # Assuming 10 here is the "exit" option
        break

    else: 
        print("Unknown selection, please try again")

第二个版本要求用户明确选择“退出”选项,而第一个版本只在选择了未知/未定义选项时退出。

答案 2 :(得分:0)

您已经说过,您的程序应该在用户输入0后退出,所以我会更改此内容:

if i==0 :
    print " program will exit."
    i=4  

到此:

if i==0 :
    print " program will exit."
    break  

此外,您无需在第二个0中将i分配给if,因为i已在此块中等于0 ,所以你可以安全地删除这行代码。