A memorandum around Python's control syntax. We will make additions and corrections as needed.
operator | Explanation |
---|---|
A == B | A and B are equal |
A != B | A and B are not equal |
A < B | A is smaller than B |
A > B | A is greater than B |
A <= B | A is less than or equal to B |
A >= B | A is B or higher |
A in [LIST] | [LIST]There is A in |
A not in [LIST] | [LIST]There is no A in |
A is None | A is None |
A is not None | A is not None |
Condition A and condition B | Satisfy both condition A and condition B |
Condition A or Condition B | Satisfy either condition A or condition B |
if
num = 5
if num == 0:
print('The number is 0')
elif num < 0:
print('Number is less than 0')
else:
print('Number is greater than 0')
while
limit = input('Enter:') #Accept input
count = 0
while True:
if count >= limit:
break #If count is 10 or more, exit the loop
if count == 5:
count += 1
continue #If count is 5, go to the next loop
print(count)
count += 1
else: #Execute when the loop ends without breaking
print('Done')
for
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
if i == 5: #If i is 5, go to the next loop
continue:
if i == 8: #If i is 8, exit the loop
break:
print(i)
#Execute when the loop ends without breaking
else:
print('Done')
#When you want to process a specified number of times but do not need to retrieve the value_To use
for _ in range(10):
print('hello')
#Process until it exceeds 10 by skipping 2 to 3
for i in range(2, 10, 3):
print('hello')
#If you also want to get the index
for i, animal in enumerate(['dog', 'cat', 'bird']):
print(i, animal)
#When you want to expand and get multiple lists at the same time
animals = ['dog', 'cat', 'bird']
foods = ['meat', 'fish', 'bean']
for animal, food in zip(animals, foods):
print(animal, food)
#Dictionary loop processing
data = {'x': 10, 'y': 20}
for k, v in d.items():
print(k, ':', v)
Recommended Posts