I. Grammar
1.1 if (single branch structure)
''' <Code Block 1> If <condition>: <Code Block 2> # Execute Code Block 2 and then Execute Code Block 3 when the condition is True, otherwise execute Code Block 3 directly without Executing Code Block 2. Code Block 3 > # Run Code Block 3 directly when conditions do not hold '''
light = 'green' if light == 'red': print('wait for') print('adopt')
1.2 if... else (double branching structure)
''' <Code Block 1> if <condition>: <Code Block 2> # Execute Block 2 and then Block 3 when the condition is True else: <Code Block 4> # When conditions do not hold, run block 4, and then block 3 <Code Block 3> # When the condition does not hold, first run code block 4, then run code block 3. '''
light = 'yellow' if light == 'red': print('etc.') else: print('adopt') print('Aha ha')
1.3, if... elif... else (multi-branch structure)
''' <Code Block 1> if <Conditions 1>: <Code Block 2> # When condition 1 is True, code block 2 is executed and code block 3 is executed. elif <Conditions 2>: <Code Block 5> # When condition 1 does not hold, condition 2 holds, code block 5 is executed, and then code block 3 is executed. ... elif <condition n>: <code block n> else: <Code Block 4> # When none of the conditions for if and elif are valid, code block 4 is executed, and then code block 3 is executed. <Code Block 3> '''
light = 'white' if light == 'red': print("wait for") elif light == 'green': print("adopt") elif light == 'yellow': print("Be careful") else: print("No signal!") print("Make you laugh!")
2. Multiple if judgments and if...elif...else
2.1 Multiple if Judgments
# For age guessing applications, multiple IFS take more time
age = 18 inp_age = int(input('age:')) # 17 if age > inp_age: # a # a is done as soon as it's established. It's not related to b, c. print('Guess big.') if age < inp_age: # b # b is done as soon as it's established. It's not related to a and c. print('Guess it's small') if age == inp_age: # c # c does it when it's set up. It's not related to a and b. print('Guess right.')
2.2 if...elif...else
Only one operation, less time-consuming
age = 18 inp_age = int(input('age:')) # 17 if age >= inp_age: # a if age > inp_age: # b if 'e': print('Guess it's small') # a, b, e, I'll do it. else: print('Guess right.') # a is founded c is founded before I do it. else: # a I'll do it if it doesn't work. print('Guess big.')