if-else阶梯被终止

时间:2014-03-23 14:25:06

标签: python python-2.7

我尝试制作和Celcius到Faharanite转换器,反之亦然。 我制作了额外的if-else梯形图,以确保用户不会卡住以及当用户输入错误时。 但我尝试在第一个语句终止后编译它。

ch = raw_input("""What you want to convert :
1) Celcius to Faharanite.
2) Faharanite to Celcius.\n""")
if (type(ch)==int):
    if (ch==1):
        cel=raw_input("Enter to temperature in Celeius : ")
        if (type(cel)!='float'):
            cel = 1.8*(cel+32)
            print "The Conversion is :" + cel
        else :
            print "YOu should enter values in numeric form"
    elif (ch==2):
        fara=raw_input("Enter to temperature in Faharanite : ")
        if (type(fara)==float):
            print "The Conversion is :" + 1.8*(fara-32)
        else :
            print "YOu should enter values in numeric form"
    else :
        print "Wrong choice"

2 个答案:

答案 0 :(得分:1)

因为第一个if语句永远不会成立。 raw_input的结果始终是一个字符串。

答案 1 :(得分:0)

devnull的评论表明,只要用户输入为数字,添加ch = int(ch)就会起作用。
为了更强大的处理,我会做类似的事情:

is_valid = False
while not is_valid:
    ch = raw_input("""What you want to convert :
    1) Celsius to Fahrenheit.
    2) Fahrenheit to Celsius.\n""")
    try:
        ch = int(ch)  # Throws exception if ch cannot be converted to int
        if ch in [1, 2]:  # ch is an int; is it one we want?
            is_valid = True  # Don't need to repeat the while-loop
    except:  # Could not convert ch to int
        print "Invalid response."
# The rest of your program...

将继续提示用户,直到他们输入有效选项 请注意,您必须使用类似的try / except结构来解析温度转换为浮点数(使用float()方法)。