简体   繁体   English

if-else阶梯被终止

[英]the if-else ladder gets terminated

I tried of making and Celcius to Faharanite converter and visa-versa. 我尝试将Celcius制作成Faharanite转换器,反之亦然。 I made extra if-else ladder to ensure that the user doesn't get stuck and when the user enters something wrong. 我制作了额外的if-else阶梯,以确保用户不会在输入错误时卡住。 But i tried compiling this after the first statement gets terminated. 但是我尝试在第一个语句终止后进行编译。

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"

Because the first if statement is never true. 因为第一个if语句永远不会为真。 The result of raw_input is always a string. raw_input的结果始终是一个字符串。

devnull's comment suggesting adding ch = int(ch) will work as long as the user input is a number. devnull的注释建议,只要用户输入为数字,就可以添加ch = int(ch)
For more robust handling, I would do something like: 为了获得更可靠的处理,我将执行以下操作:

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...

which will continue to to prompt the user until they enter a valid choice. 这将继续提示用户,直到他们输入有效的选择为止。
Note that you'll have to use a similar try/except construct to parse the temperature-to-convert into a float (with the float() method). 请注意,您必须使用类似的try / except构造来解析要转换为float的温度(使用float()方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM