if and elif in python

When I first entered python and wrote a temperature conversion program, I found problems with the use of if and elif

tem = input()
if tem[-1] in ['F','f']:
    F = float(tem[0:-1])
    C = (F-32)/1.8
    print("%.2fC" %C)
if tem[-1] in ['c','C']:
    C = float(tem[0:-1])
    F = C*1.8 + 32
    print("%.2fF" %F)
else:
    print("输入格式错误")

input: 32F
output: 0.00C input format error
When the first if is executed, continue to traverse the second if does not meet the conditions, execute else.

input: 25C
output: 77.00F
The first if does not meet the conditions, continue to judge the second if meets the requirements, and the else is no longer executed.

if: No matter whether the condition you want to judge has been traversed, it will continue to traverse down;
elif: When the corresponding conditional statement is traversed, all subsequent elifs and elses will not be executed.

Guess you like

Origin blog.csdn.net/autolsj/article/details/88779241