For Python diagram


Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tutorials/56
Article address: http://www.showmeai.tech/article-detail/72
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source

1. Python for loop statement

There are many sequential data structures (such as lists or strings) in Python, which can be traversed by using the for loop.

Syntax:

The syntax format of the for loop is as follows:

for iterating_var in sequence:
   statements(s)

flow chart:

Code instance (code can be found in Online Python 3 environment (running in)

for letter in 'ShowMeAI':     # First instance
   print("Current letter: %s" % letter)
 
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second instance
   print('Current fruit: %s'% fruit)
 
print("complete!")

Output result of the above code:

Current letter: S
 Current letter: h
 Current letter: o
 Current letter: w
 Current letter: M
 Current letter: e
 Current letter: A
 Current letter: I
 Current fruit: banana
 Current fruit: apple
 Current fruit: mango
 complete!

2. Iteration through sequence index

Another way to execute loop traversal is through index. The following example (the code can be found in Online Python 3 environment Running in:

fruits = ['Banana', 'Apple',  'Grape']
for index in range(len(fruits)):
   print('Current fruit : %s' % fruits[index])
 
print("complete!")

Output result of the above code:

Current fruit : Banana
 Current fruit : Apple
 Current fruit : Grape
 complete!

In the above example, we used the built-in functions len() and range(). The function len() returns the length of the list, that is, the number of elements. Returns a number of ranges.

3. Recycle else statements

In python, for... Else means this. There is no difference between the statements in for and ordinary ones. The statements in else will be executed after the loop is normally executed (that is, for is not interrupted by break ing out). The same is true for while... Else.

for num in range(20,30):  # Iterating numbers between 10 and 20
   for i in range(2,num): # Iteration according to factor
      if num%i == 0:      # Determine the first factor
         j=num/i          # Calculate the second factor
         print ('%d be equal to %d * %d' % (num,i,j))
         break            # Jump out of current loop
   else:                  # else part of the loop
      print ('%d Is a prime number' % num)

Output result of the above code:

20 Equal to 2 * 10
21 Equal to 3 * 7
22 Equal to 2 * 11
23 Is a prime number
24 Equal to 2 * 12
25 Equal to 5 * 5
26 Equal to 2 * 13
27 Equal to 3 * 9
28 Equal to 2 * 14
29 Is a prime number

4. Classic case for circular drawing

Let's use the learned for loop to draw different patterns to help you get more familiar with the usage of for loop

(1) Hollow equilateral triangle

The code can be in Online Python 3 environment Run in.

rows = int(input('Enter the number of columns: '))

print("Print a hollow equilateral triangle and remove it here if-else Conditional judgment is solid")
for i in range(0, rows + 1):#Variable i controls the number of rows
    for j in range(0, rows - i):#(1,rows-i)
        print(" ", end='')
        j += 1
    for k in range(0, 2 * i - 1):#(1,2*i)
        if k == 0 or k == 2 * i - 2 or i == rows:
            if i == rows:
                if k % 2 == 0:#Because the first number starts from 0, if even numbers print *, odd numbers print spaces
                    print("*", end='')
                else:
                    print(" ", end='')#Note that the "end = ''" here must not be omitted and can play the role of no line feed
            else:
               print("*", end='')
        else:
            print(" ", end='')
        k += 1
    print("\n")
    i += 1

(2) Diamond

The code can be in Online Python 3 environment Run in.

rows = int(input('Enter the number of columns: '))

print("Print hollow diamond and remove it here if-else Conditional judgment is solid")

rows = int(input('Enter the number of columns: '))

for i in range(rows):#Variable i controls the number of rows
    for j in range(rows - i):#(1,rows-i)
        print(" ", end='')
        j += 1
    for k in range(2 * i - 1):#(1,2*i)
        if k == 0 or k == 2 * i - 2:
            print("*", end='')
        else:
            print(" ", end='')
        k += 1
    print("\n")
    i += 1
    #The lower half of the diamond
for i in range(rows):
    for j in range(i):#(1,rows-i)
        print(" ", end='')
        j += 1
    for k in range(2 * (rows - i) - 1):#(1,2*i)
        if k == 0 or k == 2 * (rows - i) - 2:
            print("*", end='')
        else:
            print(" ", end='')
        k += 1
    print("\n")
    i += 1

5. Video tutorial

Please click to station B to view the version of [bilingual subtitles]

[bilingual subtitles + data download] Python 3 full series of basic tutorials, whole process code Demonstration & explanation! 10 hours of video 42 sections, to ensure that you can master Python! Come on, knock the code with the video~ < quick start series >

Data and code download

The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can scientifically surf the Internet can also directly run and learn through interactive operation with the help of Google Lab!

The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:

Extended references

ShowMeAI related articles recommended

ShowMeAI series tutorial recommendations

Keywords: Python Machine Learning AI Data Mining

Added by alexcmm on Tue, 22 Feb 2022 16:17:48 +0200