如果您有很多elif,您是否需要更改某些内容?

时间:2018-12-20 02:10:39

标签: python-2.7

我正在尝试制作单位转换器,因此我需要进行大量转换。对于列表中的第五个elif,它说这是语法错误。

我尝试将其更改为if,但随后显示未定义我的变量cent_mi。有什么想法吗?

else:
    convert_answer = raw_input("What would you like to convert? (_____ to ______)? ")
    if convert_answer == 'centimeter to feet' or convert_answer == 'cent to feet':
        cent_f = raw_input("How many centimeters? ")
        print str(int(cent_f) / float(30.48)) + " feet."
    elif convert_answer == 'centimeter to inch' or convert_answer == 'cent to inch':
        cent_i = raw_input("How many centimeters? ")
        print str(int(cent_i) / float(2.54)) + " inches."
    elif convert_answer == 'centimeter to yard' or convert_answer == 'cent to yard':
        cent_y = raw_input("How many centimeters? ")
        print  str(int(cent_y) / float(91.44)) + " yards."
    elif convert_answer == 'centimeter to meter' or convert_answer == 'cent to meter':
        cent_m = raw_input("How many centimeters? ")
        print  str(int(cent_m) / 100) + " meters."
    elif convert_answer ==  'cent to kilometer' or convert_answer == 'centimeter to kilometer':
        feet_km = raw_input("How many centimeters? ")
        print str(int(feet_km) / 100000 + " kilometers."
    elif convert_answer == 'cent to mile' or convert_answer == 'centimeter to mile':
    # This is the elif that raises an error.
        cent_mi = raw_input("How many centimeters? ")
        print str(int(cent_mi) / float(160934.4)) + " miles."
    elif convert_answer ==  'feet to cent' or convert_answer == 'feet to centimeter':
        feet_c = raw_input("How many feet? ")
        print str(int(feet_c) * float(30.48)) + " centimeters."

我认为您可以拥有任意多个elif,但是第五个elif会引发语法错误。

1 个答案:

答案 0 :(得分:0)

此行不需要更多的右括号

 print str(int(feet_km) / 100000 + " kilometers."

类似

print str(int(feet_km) / 100000) + " kilometers."