SoFunction
Updated on 2024-10-30

Details of for loops in Python

The for statement actually solves the problem of looping. There are for loops in many high-level languages.

The for statement is actually a statement for iterable objects in a programming language, and its main purpose is to allow code to be executed repeatedly.Look at a quote from Wikipedia:

In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly。(corresponds English -ity, -ism, -ization:introducesforWhat's the loop??)

A for-loop has two parts: a header specifying the iteration, and a body which is executed once per iteration. (forWhat makes a loop?)

What it is:In computational science, it is a control flow statement for special iterative objects that can be executed repeatedly
How it's constituted:A header (which is an iterable object) + Execution of each object

1. Iterable objects

1.1 What is an iterable object?

Iterable objects (Iteratable Object) is able to return one of the members of the object at a time, such as we commonly used strings, lists, tuples, sets, dictionaries and so on belong to the iterative object, to get to these objects we can use the for loop to carry out the operation.

Simply put, any object that you can loop through is an iterable object.

1.2 How to judge

How to tell if aPythonIs an object iterable? Usually the isinstance() function is used to determine whether an object is iterable or not

from collections import Iterable



Summary: InPythonOf the common data objects, only numbers are not iterable; strings, tuples, lists, dictionaries, etc. are iterable

2. String for loop

Iterate through the print string one at a time for each element of the string

for i in "python": 
    print(i)    


Output:

p
y
t
h
o
n

Looking at another example:

for i in "abcdefg":
    print(i)


Output:

a
b
c
d
e
f
g

3、List of for loop

Whether it's a single-level list or a multi-level nested list, we can traverse and print it out:

# Single level list

a = ["Little Ming.","Little Red.","Little Zhang.","Little King."]

for i in a:
    print(i)  # Print each element of the list

Xiaoming (1904-1971), Soviet trained Chinese * leader, a martyr of the Cultural Revolution
little red
Zhang Xiaozhang (1908-1992), Mao *'s second wife
youngest of all

# Nested lists

b = ["Little Ming.","Little Red.","Little Zhang.","Little King.",[19,20,18,23]]

for i in b:
    print(i)

Xiaoming (1904-1971), Soviet trained Chinese * leader, a martyr of the Cultural Revolution
little red
Zhang Xiaozhang (1908-1992), Mao *'s second wife
youngest of all

[19, 20, 18, 23]

In the above example the last element is printed as a whole, what if you also want to print it separately?

def qiantao(x):   # Define a function
    for each in x:  # Iterate over each element of each original list
        if isinstance(each, list):  # Determine if each element is a list: isintance
            qiantao(each)  # In case of a list, recursively execute the function qiantao()
        else:
            print(each)  # If it's not a list, print the element directly
            
b = ["Little Ming.","Little Red.","Little Zhang.","Little King.",[19,20,18,23]]

# Call function, pass in list b
qiantao(b)  

Xiaoming (1904-1971), Soviet trained Chinese * leader, a martyr of the Cultural Revolution
little red
Zhang Xiaozhang (1908-1992), Mao *'s second wife
youngest of all
19
20
18
23

4. tuple for loop

The loops and lists for the tuple tuple are analogous:

t = ("Little Ming.","Little Red.","Little King.")

for i in t:
    print(i)

Xiaoming (1904-1971), Soviet trained Chinese * leader, a martyr of the Cultural Revolution
little red
youngest of all

5. Dictionary for loop

We usekeys()values()items() We can traverse the keys, values, and key-value pairs of a dictionary, respectively. Note that traversing a dictionary defaults to traversing the keys of the dictionary, theFirst define a dictionary:

d = {"name":"Peter","age":20,"sex":"male","address":"china"}

5.1keys()

Iterates over the keys of the dictionary;

for i in ():  # Iterate over the keys of the dictionary
    print(i)


name
age
sex
address

for i in d:  # The default is to iterate through the key's values
    print(i)


name
age
sex
address

5.2 values()

Iterates over the values of the dictionary:

for i in ():  # Iterate over dictionary values
    print(i)


Peter
20
male
china

5.3 items()

Iterate over the keys and values of the dictionary at the same time

for i in ():  # Iterate over dictionary values
    print(i)


('name', 'Peter')
('age', 20)
('sex', 'male')
('address', 'china')

Take out the keys and values of the dictionary, respectively:

for k,v in ():
    print(k + "--->" + str(v))


name--->Peter
age--->20
sex--->male
address--->china

6, range function of the for loop

rangeThe function isPython Built-in function to generate a series of consecutive integers, mostly used in for loops.

  • range(start,stop,step)
  • start: include start, default is 0, no write default is 0
  • stop: does not contain stop and must be written
  • pacemakerstepCan be positive or negative, default is 1, can't be 0

6.1 Base Case

range(10)  # Generate iterable objects


range(0, 10)

The default start is 0

range(0,10)


range(0, 10)

Specify the beginning as 1

range(1,10)


range(1, 10)

Here is the result expanded into a list:

list(range(10))  # 10 (tail) not included


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Specify a step size of 2:

list(range(0,10,2))  # Without the 10, the step is 2


[0, 2, 4, 6, 8]

Summary:rangeFunctions are headers without tails

for i in range(10):
    print(i)


0
1
2
3
4
5
6
7
8
9

6.2 Find numbers up to 100 that are divisible by 5

for i in range(101):  # Excluding 101, 0-100
    if i % 5 == 0:  # % denotes remainder: a remainder of 0 denotes an integer division
        print(i,end="、")


0、5、10、15、20、25、30、35、40、45、50、55、60、65、70、75、80、85、90、95、100、

6.3 Gaussian Summation

Find the sum of all numbers from 1 to 100.

sum = 0

for i in range(1,101):
    sum = sum + i  # Every time we loop, sum is this number #
    
sum

5050

Find the sum of odd numbers up to 100:

sum = 0

# Steps of 2, starting at 1: 1, 3, 5, 7...
for i in range(1,101,2):  
    sum = sum + i
    
sum

2500

Find the sum of even numbers up to 100:

sum = 0

# Steps of 2, starting at 2: 2,4,6,8...
for i in range(2,101,2):  
    sum = sum + i
    
sum

2550

7. Multiple for statements

The for statement can be reused in a for statement:

for i in ["python","java","html"]:
    for j in i:
        print((),j)    # upper(): make letters uppercase


PYTHON p
PYTHON y
PYTHON t
PYTHON h
PYTHON o
PYTHON n
JAVA j
JAVA a
JAVA v
JAVA a
HTML h
HTML t
HTML m
HTML l

for i in [4,5,6]:
    for j in [1,2,3]:
        print(i*j)  # Realize the multiplication of any two numbers


4  # 4*1
8  # 4*2
12 # 4*3
5  # 5*1
10 # 5*2
15 # 5*3
6  # 6*1
12 # 6*2
18 # 6*3

8. List of derivatives

(1) Above we mentioned numbers divisible by 5: use for loops and ifs to solve the problem

five = []  # Define the empty list

for i in range(101):  # Excluding 101, 0-100
    if i % 5 == 0:  # % denotes remainder: a remainder of 0 denotes an integer division
        (i)  # Add to list
        
five

[0,
 5,
 10,
 15,
 20,
 25,
 30,
 35,
 40,
 45,
 50,
 55,
 60,
 65,
 70,
 75,
 80,
 85,
 90,
 95,
 100]

(2) How can this be accomplished using list derivatives?

[x for x in range(101) if x % 5 == 0]


[0,
 5,
 10,
 15,
 20,
 25,
 30,
 35,
 40,
 45,
 50,
 55,
 60,
 65,
 70,
 75,
 80,
 85,
 90,
 95,
 100]

9、for-else

Maybe you've heard of it.if-elseBut I've heard that.for-elseStatements? That's kind ofPythonA cold spot of knowledge in the

for i in range(5):
    print(i)
else:
    print("The end.")


0
1
2
3
4
close

That is to say:forThe statement ends and still executes theelsesuch statements

for i in []:
    print(i)
    
else:
    print("The end.")


close

The following example jumps back when the remainder of i divided by 3 is 2 and terminates the wholeforloop, followed by theelseIt won't work.

for i in range(10):
    print(i)
    if i % 3 == 2:
        break
else:
    print("The end.")


0
1
2

10. Realization of triangular arrays

for i in range(1,11):
    for k in range(1,i):
        print(k, end=" ")
    print("\n")


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9

If we want to reverse it, how do we accomplish that?

for i in range(10,0,-1):
    for k in range(1,i):
        print(k, end=" ")
    print("\n")


1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

11. 99 multiplication table

Here's an example of how to implement the 99 multiplication table

for i in range(1,10):
    for j in range(1,i+1):  # In order to ensure that there is a 4*4, i.e. an equation of multiplying the same numbers, it is necessary to make i appear, using i+1
        print('{}x{}={}'.format(j, i, i*j), end=" ")  # end with a space for the end symbol
    print("\n")


This article on the Python for loop details of the article is introduced to this, more related Python for loop content please search my previous posts or continue to browse the following related articles I hope that you will support me more in the future!