Contents
1 Basic knowledge
1.1 Concept
Control flow tools in Python change the flow of how code is executed by the Python interpreter.
Since the Python interpreter executes code in a line by line manner, control flow tools help dictate what line(s) of code should run in a Python program. There are different types of control flow tools available to us in Python and we will go through them in detail in this lesson.
2 Usage
2.1 while
examples
①Open cmd.exe and enter python
to enter interactive mode.
②we can write an initial sub-sequence of the Fibonacci series as follows:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
This example introduces several new features.
-
The first line contains a multiple assignment: the variables
a
andb
simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right. -
The
while
loop executes as long as the condition (here:a < 10
) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C:<
(less than),>
(greater than),==
(equal to),<=
(less than or equal to),>=
(greater than or equal to) and!=
(not equal to). -
The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
-
The
print()
function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:
>>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
2.2 More Control Flow Tools
Besides the while statement just introduced, Python uses the usual flow control statements known from other languages, with some twists.
2.2.1 if
Statements
Perhaps the most well-known statement type is the if
statement. For example:
>>> 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
There can be zero or more elif
parts, and the else
part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif …
sequence is a substitute for the switch or case statements found in other languages.
2.2.2 break
and continue
Statements, and else
Clauses on Loops
The break
statement, like in C, breaks out of the innermost enclosing for or while loop.
Loop statements may have an else
clause; it is executed when the loop terminates through exhaustion of the list (with for
) or when the condition becomes false (with while
), but not when the loop is terminated by a break
statement. Generally speaking, the condition of This is exemplified by the following loop, which searches for prime numbers:while
at this time is that the parameters of True
or for
loop are still within the range of being run.
>>> 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
(Yes, this is the correct code. Look closely: the else
clause belongs to the for
loop, not the if
statement.)
When used with a loop, the else
clause has more in common with the else
clause of a try
statement than it does that of if
statements: a try
statement’s else
clause runs when no exception occurs, and a loop’s else
clause runs when no break
occurs.
The continue statement, also borrowed from C, continues with the next iteration of the loop:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
3 Exercise
Q: Find all the narcissistic number within 100.
i = 100
while i < 1000:
if (i // 100)**3 + ((i % 100) // 10)**3 + (i % 10)**3 == i:
print(i)
i += 1
The output is 153, 370, 371, 407.
There is another way to ignore the impact of digits.
a = 100
while a < 20000:
if sum([eval(i)**len(str(a)) for i in list(str(a))]) == a:
print(a)
a += 1
- The narcissistic number with different digits can be obtained by changing the number after
while a <
.
Q: Get any number entered by the user and determine whether it is a prime number?
from math import sqrt
while True:
a = input('Please enter a number:')
if a == '':
break
elif a.isdigit() and eval(a) > 1:
b = int(a)
i = 1
count = 0
while i <= sqrt(b):
if b%i == 0:
count += 1
i += 1
if count == 1:
print(a, 'is a prime number.')
else:
print(a, 'is a composite number')
else:
print('Please re-enter!')
Q: Fist guessing game:
- Process: The player enters it manually and the computer automatically generates it randomly.
- Result: ①The player wins; ②the computer wins; ③the two sides draw.
import random
while True:
a = input('Please enter a number(1 for "stone", 2 for "cloth", 3 for "scissors"): ')
b = random.randint(1, 3)
c1 = (('1', '2'), ('2', '3'), ('3', '1'))
if a=='':
break
elif a.isdigit() and eval(a) in (1, 2, 3):
if (a, str(b)) in c1:
print('Computer win!')
elif a == str(b):
print('The two sides draw!')
else:
print('Player win!')
else:
print('Incorrect input, please re-enter.')