a = 10 b = 20 if a <= b: … smaller = a … else: … smaller = b … smaller 10
# Rewrite the above judgment as a conditional expression ( It's also called the ternary operator )
s = a if a <= b else b s 10 ```
Expand if sentence : Multi branch statement , If a certain condition is satisfied, the corresponding statement block will be executed , Other conditions are no longer judged . Multiple branches execute only one branch .
Random number module
>>> import random
# random.choice Randomly select an item from a given list
>>> random.choice('abcdef')
'a'
>>> random.choice('abcdef')
'c'
>>> random.choice(['aaa', 'bb', 'cccc', 'ddd'])
'bb'
>>> random.choice(['aaa', 'bb', 'cccc', 'ddd'])
'ddd'
>>> random.choice(['aaa', 'bb', 'cccc', 'ddd'])
'ddd'
python The middle cycle is divided into while Circulation and for loop , When the number of cycles is unknown , Use while loop , The number of cycles is known , Use for loop .
while The loop condition :
Code groups in the circulatory body
When the loop condition is true , Execute the code group in the body of the loop . The condition is true and if The judgment is the same .
Cyclic else sentence : When the loop is break,else Statement does not execute , Otherwise execution
Used to generate integers .
>>> range(10) # Generate range object
range(0, 10)
>>> list(range(10)) # Convert to list , For viewing only range Numbers that can be generated
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for i in range(10):
... print(i)
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(1, 11, 2))
[1, 3, 5, 7, 9]
>>> list(range(10, 0, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
A convenient and fast way to generate a list
>>> [10]
[10]
>>> [10 + 2] # The result of the expression evaluation is put in the list
[12]
>>> [10 + 2 for i in range(5)] # Loop determines how many times the expression is evaluated
[12, 12, 12, 12, 12]
>>> [10 + i for i in range(1, 11)] # The expression can be a loop variable
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> [10 + i for i in range(1, 11) if i % 2 == 1] # If the judgment condition is true, the calculation result will be retained
[11, 13, 15, 17, 19]
# Equivalent to the following code :
>>> nums = []
>>> for i in range(1, 11):
... if i % 2 == 1:
... nums.append(10 + i)
...
>>> nums
[11, 13, 15, 17, 19]
Generated by list parsing 192.168.1.0/24 All of the segments IP Address :
>>> ['192.168.1.%s' % i for i in range(1, 255)]