而/ if循环给我带来麻烦(初学者)

时间:2015-01-12 00:59:55

标签: python if-statement for-loop while-loop

我一直在尝试制作我的第一个“solo”python程序,它是一个计算器,你可以选择你想要它计算的公式,然后输入所需的变量。我的while / for循环出现问题,当我运行程序时,我得到正确的菜单:menu(),然后当我通过输入1选择我的下一个菜单时我正确得到“v_menu”但是如果我输入2,应该给我“m_menu”,而不是像我输入的那样得到v_menu。

我希望我的解释是有道理的,我仍然对这一切都很新。感谢我能得到的任何帮助,在这至少一个小时左右的时间里,我已经不知所措了。

干杯,继承我的代码:      #coding = utf-8

#Menues
def menu():
    print "Choose which topic you want in the list below by typing the corresponding number\n"
    print "\t1) virksomhedsøkonomi\n \t2) matematik\n"
    return raw_input("type the topic you want to pick\n >>")


def v_menu():
    print "Choose which topic you want in the list below by typing the corresponding number"
    print "\t1) afkastningsgrad\n \t2) overskudsgrad\n \t3) aktivernes omsætningshastighed\n \t4)                          Egenkapitalens forrentning\n \t5) return to main menu\n"
    return raw_input("Type the topic you want to pick\n >>")

def m_menu():
    print "Choose which topic you want in the list below by typing the corresponding number"
    print "\t1) omregn Celsius til Fahrenheit\n \t2) omregn Fahrenheit til Celsius\n"
    return raw_input("Type the topic you want to pick\n >>")

    # - Mat -

#Celsius to Fahrenheit
def c_to_f():
    c_temp = float(raw_input("Enter a temperatur in Celsius"))
    #Calculates what the temperatur is in Fahrenheit
    f_temp = c_temp * 9 / 5 + 32
    #Prints the temperatur in Fahrenheit
    print (str(c_temp) + " Celsius is equal to " + str(f_temp) + " Fahrenheit")


#Fahrenheit to Celsius
def f_to_c(): 
    f_temp = float(raw_input("Enter a temperatur in Fahrenheit"))
    #Calculates what the temperatur is in celsius
    c_temp = (f_temp - 32) * (float(100) / 180)
    #Prints the temperatur in celsius
    print (str(f_temp) + " Fahrenheit is equal to " + str(c_temp) + " Celsius")


#Program
loop = 1
choice = 0



while loop == 1:
    choice = menu()

    if choice == "1" or "1)":
        v_menu()

    elif choice == "2" or "2)":
        m_menu()
        if choice == "1":
            c_to_f()
        elif choice == "2":
            f_to_c()

    loop = 0

2 个答案:

答案 0 :(得分:0)

您的问题出在您的if语句中:if choice ==" 1"或" 1)":

你真正需要的是:如果选择==" 1"或选择==" 1)":

之后的所有内容或被评估为另一个表达式。你说"如果选择等于一个或者一个存在。"

" 1)"评估为" true"在这种情况下,所以你总是会碰到那个分支。

答案 1 :(得分:0)

问题出在这里;

if choice == "1" or "1)":
    v_menu()

elif choice == "2" or "2)":

你必须写出像;

if choice == "1" or choice == "1)":
        v_menu()

elif choice == "2" or choice == "2)":

否则,if语句始终为True。如果第一个if语句为True,那么您的elif语句将不起作用。这就是为什么你不能打电话给v_menu()

相关问题