Python for loop - Python zero basics tutorial

catalogue

Zero basic Python learning route recommendation: Python learning directory >> Getting started with Python Basics

stay Python During development, in addition to the previous article while loop One more for loop It is also often used. The use of both is similar. The use of for loop is more flexible than that of while loop. Let's understand the specific differences.

I for loop syntax

for variable in Sequence: 
    Execute statement......

What is a sequence:

  1. The sequence can be a number interval, such as 0 ~ 100;
  2. The sequence can be character string
  3. The sequence can be a list / dictionary / Yuanzu;

Let's start with a simple example:

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:python for loop.py
@Time:2021/3/20 23:00
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""

for a in range(0, 5): # Indicates that the initial value of a is 0 and less than 5, and the value of a starts from 0 and increases successively: 0 1 2 3 4 
    print(a)

print("Exit the program at the end of the cycle")


"""
Output result:

0
1
2
3
4
 Exit the program at the end of the cycle

"""

So is the range function python built-in functions , range(x,y) means an integer between X and y-1, excluding y

range(5,10) Means: 5 6 7 8 9
range(0,10) Indicates: 0 1 2 3 4 5 6 7 8 9

For the above code, we also use the while loop to realize the following:

a = 0
while a < 5:
    print(a)
    a += 1
print("Exit the program at the end of the cycle")

thus it can be seen, while loop It has the same functions as the for loop. The for loop is more flexible than the while loop. Specifically, analyze the parameters in the for loop:

'''
i: Variable name, named a,b,c Fine,indifferent

n: variable i The default value is reset n Start, i = n

m: During the cycle, the default i Value offset step plus 1 until i value>= m,Cycle stop, note: i The maximum value of is equal to m-1 
'''

for i in range(n,m):
    # Code block
    # ....

II for loop practice

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:python for loop.py
@Time:2021/3/20 23:00
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""

# Traverse the string and output each character in the string in turn
for a in "python course - Ape theory python": # a starts with the first letter of the string and ends at the end of the traversal string
    print(a)

print("*"*20) # Tip: 20 consecutive outputs*

# Traverse the numbers between 0 and 100, but not including 100. By default, a starts from 0 and increases successively until the end of 99
for a in range(0,100):
    if a % 2 == 0: # Judge parity. If it is even, skip this cycle directly and continue the next cycle
        continue
    elif a > 5: # If it is odd and the value of a is greater than 5
        a *= 10
    else:   # If it is an odd number and the value of a is less than 5
        a += 20

    if a > 30: # If the value of a is greater than 30, jump out of the loop directly
        break

    print(a)

print("Exit the program at the end of the cycle")


'''
Output result:

p
y
t
h
o
n
 teach
 Cheng

-

ape
 say
p
y
t
h
o
n
********************
21
23
25
 Exit the program at the end of the cycle

'''

Code analysis:

The above code combines the previous learning Conditional expression if / else as well as continue / break use. During the for loop, the default offset of variable a value increases by + 1 in turn. What if you want the for loop to reduce the offset or increase by + 2 or decrease by - 2?

To realize the offset increment + 2 or decrement - 2 in the for loop, you need to add another parameter in the for loop. The syntax is as follows:

'''
i: Variable name, named a,b,c Fine,indifferent

n: variable i The default value is reset n Start, i = n

k: variable k If the value of is not set, the default offset step is 1; set up k Value means that the offset step is equal to k (k (can be integer or floating point number)

m: During the cycle, i The default offset step is incremented by the value of k,If not set k Value, default k = 1, until i >= m,Cycle stop, note: i The maximum value of is equal to m-1
'''

for i in range(n,m,k):

The code is as follows:

# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:python for loop.py
@Time:2021/3/20 23:00
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!

"""

for i in range(0, 10, 2):  # The default i value starts from 0 again, and the offset step is incremented by + 2 and less than 10
    print(i, end=" ")  # The print function will wrap lines by default, forcing "" (space) instead of "" \ n "" (line break)

print("\n") # Line feed
print("**"*20)
for i in range(0, -10, -2):  # The default i value starts from 0, and the offset step size decreases by - 2 and is greater than - 10
    print(i, end=" ")  # The print function will wrap lines by default, forcing "" (space) instead of "" \ n "" (line break)

print("\n")# Line feed
print("**"*20)

str1 = "Ape theory python"
print("len(str1):%d " % len(str1))
for i in range(0,len(str1),2): # The default i value starts from 0 again, and the offset step is incremented by + 2 and less than len(str1)
    print(str1[i])


"""
Output result:

0 2 4 6 8 

****************************************
0 -2 -4 -6 -8 

****************************************
len(str1):8 
ape
p
t
o


"""

III Key summary

  • 1. The use method of continue / break in the for loop is the same as that of while
  • 2. The for loop can directly traverse string / number interval / list and other sequences

IV Guess you like it

  1. Introduction to Python
  2. Python pycham anacanda differences
  3. Python2.x and python 3 x. How to choose?
  4. Python configuration environment
  5. Getting started with Python Hello World
  6. Python code comments
  7. Python Chinese code
  8. Python variables
  9. What is Anaconda? Anconda download installation tutorial
  10. Pychart prompt: this license **** has been cancelled
  11. Pychart set development template / font size / background color

No reprint without permission: Ape programming » Loop for Python

Keywords: Python

Added by smonsivaes on Wed, 09 Feb 2022 03:32:53 +0200