Public account: You and the cabin by: Peter Editor: Peter

Hello, I’m Peter

Year round, cycle round: it’s all about cycle in the end

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

The for statement is a programming language statement for iterables that allows code to be executed repeatedly. Take a look at this introduction 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. (What is a for loop?)

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

  • What is it: in computing, a control-flow statement for a particular iterator that can be executed repeatedly
  • How to form: a header (which is an iterable) + the body of each object

iterable

What is an iterable

An Iteratable Object is an Object that can return one of its members ata time, such as strings, lists, tuples, collections, dictionaries, etc., all of which are iterable objects that can be retrieved using a for loop.

To put it simply, any object that you can loop over is an iterable.

How to judge

How do I determine if a Python object is iterable? The isinstance() function is usually used to determine whether an object is iterable

from collections import可迭代Copy the code

Summary: Of Python’s common data objects, only numbers are non-iterable; strings, tuples, lists, dictionaries, and so on are all iterable

String for loop

Iterate over each element in the printed string once

for i in "python": 
    print(i)    
Copy the code
p
y
t
h
o
n
Copy the code

Here’s another example:

for i in "abcdefg":
    print(i)
Copy the code
a
b
c
d
e
f
g
Copy the code

List for loop

Whether it’s a single-layer list or a multi-layer nested list, we can iterate over and print it out:

# Single layer list

a = ["Xiao Ming"."Little red"."Zhang"."Wang"]

for i in a:
    print(i)  Print each element in the list
Copy the code
Xiao Ming, Xiao Hong, Xiao Zhang, Xiao WangCopy the code
# nested list

b = ["Xiao Ming"."Little red"."Zhang"."Wang"[19.20.18.23]]

for i in b:
    print(i)
Copy the code
Xiao Ming, Xiao Hong, Xiao Zhang, Xiao Wang [19, 20, 18, 23]Copy the code

The last element in the above example is printed as a whole. What if you want to print it separately?

def qiantao(x) :   Define a function
    for each in x:  Iterate over every element in each original list
        if isinstance(each, list) :Isintance = isintance
            qiantao(each)  # if it is a list, the recursive executive function qiantao()
        else:
            print(each)  If it is not a list, print it directly
            
b = ["Xiao Ming"."Little red"."Zhang"."Wang"[19.20.18.23]]

Call the function, passing in listing B
qiantao(b)  
Copy the code
Xiao Ming, Xiao Hong, Xiao Zhang, Xiao Wang 19, 20, 18, 23Copy the code

For loops for tuples

The loop and list of tuples are similar:

t = ("Xiao Ming"."Little red"."Wang")

for i in t:
    print(i)
Copy the code
Xiao Ming, Xiao Hong, Xiao WangCopy the code

Dictionary for loop

Using keys(), values(), items(), we can walk through the dictionary’s keys, values, and key-value pairs, respectively. The default value for traversing a dictionary is the key of the dictionary.

d = {"name":"Peter"."age":20."sex":"male"."address":"china"}
Copy the code

keys

Iterate over the keys of the dictionary;

for i in d.keys():  Walk through the keys of the dictionary
    print(i)
Copy the code
name
age
sex
address
Copy the code
for i in d:  The default is to iterate over key values
    print(i)
Copy the code
name
age
sex
address
Copy the code

values

Iterating through the dictionary values:

for i in d.values():  Walk through the dictionary values
    print(i)
Copy the code
Peter
20
male
china
Copy the code

items()

Iterate over the dictionary’s keys and values at the same time

for i in d.items():  Walk through the dictionary values
    print(i)
Copy the code
('name', 'Peter')
('age', 20)
('sex', 'male')
('address', 'china')
Copy the code

Retrieve the keys and values of the dictionary separately:

for k,v in d.items():
    print(k + "- >" + str(v))
Copy the code
name--->Peter
age--->20
sex--->male
address--->china
Copy the code

For loop for range function

The range function is a Python built-in function that generates a series of consecutive integers, mostly used in for loops.

range(start,stop,step)
Copy the code
  • Start: contains start. The default value is 0
  • Stop: does not contain stop and must be written
  • The step size can be positive or negative. The default value is 1, not 0

1. Basic cases

range(10)  The iterable is generated
Copy the code
range(0, 10) 
Copy the code

The default is 0

range(0.10)
Copy the code
range(0, 10)
Copy the code

Specify a start of 1

range(1.10)
Copy the code
range(1, 10)
Copy the code

Here’s how to expand the results into a list:

list(range(10))  # not including 10 (tail)
Copy the code
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

Specify step size 2:

list(range(0.10.2))  # does not contain 10, the step size is 2
Copy the code
[0, 2, 4, 6, 8]
Copy the code

Conclusion: The range function contains the head and not the tail

for i in range(10) :print(i)
Copy the code
0
1
2
3
4
5
6
7
8
9
Copy the code

2, Find the number within 100 that is divisible by 5:

for i in range(101) :# does not contain 101, 0-100
    if i % 5= =0:  # % denotes remainder: remainder 0 denotes divisor
        print(i,end="、")
Copy the code
0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100,Copy the code

3. Gaussian summation

Find the sum of all the numbers from 1 to 100

sum = 0

for i in range(1.101) :sum = sum + i  # For each loop, sum is this number
    
sum
Copy the code
5050
Copy the code

Find the sum of odd numbers up to 100:

sum = 0

1, 3, 5, 7...
for i in range(1.101.2) :sum = sum + i
    
sum
Copy the code
2500
Copy the code

Find the sum of even numbers up to 100:

sum = 0

2,4,6,8...
for i in range(2.101.2) :sum = sum + i
    
sum
Copy the code
2550
Copy the code

Multiple for statements

We can also use the for statement again:

for i in ["python"."java"."html"] :for j in i:
        print(i.upper(),j)    # upper() : Uppercase letters
Copy the code
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
Copy the code
for i in [4.5.6] :for j in [1.2.3] :print(i*j)  # multiply any two numbers
Copy the code
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
Copy the code

The derived type

(1) Above we mentioned numbers divisible by 5: use the for loop and if to solve this problem

five = []  Define an empty list

for i in range(101) :# does not contain 101, 0-100
    if i % 5= =0:  # % denotes remainder: remainder 0 denotes divisor
        five.append(i)  # Add to the list
        
five
Copy the code
[0,
 5,
 10,
 15,
 20,
 25,
 30,
 35,
 40,
 45,
 50,
 55,
 60,
 65,
 70,
 75,
 80,
 85,
 90,
 95,
 100]
Copy the code

(2) How to use list derivation?

[x for x in range(101) if x % 5= =0]
Copy the code
[0,
 5,
 10,
 15,
 20,
 25,
 30,
 35,
 40,
 45,
 50,
 55,
 60,
 65,
 70,
 75,
 80,
 85,
 90,
 95,
 100]
Copy the code

for-else

Maybe you’ve heard if-else, but have you heard for-else? This is also a bit of a mystery in Python

for i in range(5) :print(i)
else:
    print("The end")
Copy the code
0, 1, 2, 3, 4 EndCopy the code

In other words: the for statement will still execute the else statement

for i in[] :print(i)
    
else:
    print("The end")
Copy the code
The end of theCopy the code

In the following example, when the remainder of I divided by 3 is 2, the loopback terminates the entire for loop and the else does not execute

for i in range(10) :print(i)
    if i % 3= =2:
        break
else:
    print("The end")
Copy the code
0
1
2
Copy the code

Implementing a triangular array

for i in range(1.11) :for k in range(1,i):
        print(k, end="")
    print("\n")
Copy the code

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 9Copy the code

If we wanted to do the reverse, how would we do it?

for i in range(10.0, -1) :for k in range(1,i):
        print(k, end="")
    print("\n")
Copy the code
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 6 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 1 2 3 1 2 3 1 2 2 3 4 1 2 3 1 2 3 1 2 3 1 2 1 1 2 3 4Copy the code

99 times table

Here is an example to illustrate how to implement the 99 times table, how to play the 99 times table refer to the previous article

for i in range(1.10) :for j in range(1,i+1) :# In order to make sure that there's 4 times 4, which is the same number multiplied by the same number, we need to make I appear, and use I +1
        print('{}x{}={}'.format(j, i, i*j), end="")  The end of # end is marked with a space
    print("\n")
Copy the code