Python control flow

1. if statement

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... 	x = 0
... 	print('Negative changed to zero')
... elif x == 0:
... 	print('Zero')
... elif x == 1:
... 	print('Single')
... else:
... 	print('More')
...
More

Else is optional, 'elif' is the abbreviation of else if.

2. for statement

Python's for statement iterates according to the order of children in any sequence (linked list or string).

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... 	print(x, len(x))
...
cat 3
window 6
defenestrate 12

In the iterative process, it is not safe to modify the iterative sequence. If you want to modify the iterative sequence, you can iterate its copy. It is convenient to use the cutting mark:

>>> for x in a[:]: # make a slice copy of the entire list
... 	if len(x) > 6: a.insert(0, x)
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']

Attention

# Strange things happen if you just print a sequence:
>>> print(range(10))
range(0, 10)

In different ways, the object returned by the range() function appears as a list, but in fact it is not. When you iterate over it, it is an object that can return consecutive items like the desired sequence; But to save space, it doesn't really construct lists.

What we call this kind of object [eg: range()] is iterative, that is, it is suitable as a target (parameter) of functions or structures that expect to obtain continuous items from something until the end. The for statement we have seen is such an iterator. The list() function is another (iterator) that creates a list from the iteratable (object):

>>> list(range(5))
[0, 1, 2, 3, 4]

3. break, continue, else statements

A loop can have an else sentence, which is executed when the loop iterates over a complete list (for for) or when the execution condition is false (for while), but it will not be executed when the loop is aborted by break.

>>> for n in range(2, 10): 
... 	for x in range(2, n): 
... 		if n % x == 0: 
... 			print(n, 'equals', x, '*', n//x) 
... 			break 
... 	else: 
... 		# loop fell through without finding a factor 
... 		print(n, 'is a prime number') 
... 
2 is a prime number 
3 is a prime number 
4 equals 2 * 2 
5 is a prime number 
6 equals 2 * 3 
7 is a prime number 
8 equals 2 * 4 
9 equals 3 * 3

The continue statement is borrowed from C, which means that the loop continues to execute the next iteration.

The pass statement does nothing.

Posted by typo on Fri, 20 May 2022 19:44:46 +0300