Loop structure for

Posted by backyard on Tue, 24 Dec 2019 15:59:12 +0100

Course:
High energy: statement structure starts with keywords and ends with colons!     

1: Statement structure

for <variable> in <sequence>:
    <statements>
Else: else is optional
    <statements>

2: Basic rules

(1) use indentation to divide statement blocks. Statements with the same number of indentation form a statement block together.
(2) sequence can be any sequence item, such as a list or a string.

3: Condition is true

Not 0, True, 'None', string is not empty

4: range function
    range(start, end, scan)
Start count start position
End count end position
scan interval per jump
It is often used when traversing a list of numbers

5: Loop nesting

6: continue and break

code:

 1 # -----------------------------------------------------------------------------------------------------#
 2 # for A simple example of a loop
 3 # -----------------------------------------------------------------------------------------------------#
 4 # Method 1
 5 for letter in 'Python':  # First instance
 6     print('Current letter :', letter)
 7 
 8 fruits = ['banana', 'apple', 'mango']
 9 for fruit in fruits:
10     print('Current fruit :', fruit)
11 
12 # Method two
13 fruits = ['banana', 'apple', 'mango']
14 for index in range(len(fruits)):
15     print('Current fruit', fruits[index])
16 
17 
18 # -----------------------------------------------------------------------------------------------------#
19 # for loop-----Judge whether a number is prime
20 # -----------------------------------------------------------------------------------------------------#
21 
22 for num in range(10, 20, 2):  # Iterations between 10 and 20
23     for i in range(2, num):  # Iterate by factor
24         if num % i == 0:  # Determine the first factor
25             j = num / i  # Calculate the second factor
26             print('%d Be equal to %d * %d' % (num, i, j))  # Pay attention here print format
27             break  # Jump out of current loop
28     else:  # Cyclic else Part
29         print(num, 'It's a prime number')
30 
31 # -----------------------------------------------------------------------------------------------------#
32 # continue and break Quotation
33 # -----------------------------------------------------------------------------------------------------#
34 
35 for letter in 'Python':  # First instance
36     if letter == 'h':
37         pass  # Is an empty statement, in order to maintain the integrity of the program structure
38         print("This is a Pass block")
39     #       continue
40     print('Current letter :', letter)

 










Topics: Python