Examples of for compound statements in Python

  • 2021-01-19 22:17:41
  • OfStack

I usually use the nesting of loops when using double for loops in Python, but there is another trick in Python -- for compound statements.

Simple write a small program, used for delay cycle nesting functions are as follows:


#!/usr/bin/python

defFunc1(ten_num,one_num):

 for i in range(ten_num):

  for j in range(one_num):

   print(10 * i + j)

The results of Func1(2,5) are as follows:


0

1

2

3

4

10

11

12

13

14

The above is a list of the results of the combined operation of 1 number. Next use for compound statement to achieve similar function, add the extension code as follows:


#!/usr/bin/python


defFunc1(ten_num,one_num):

 for i in range(ten_num):

  for j in range(one_num):

   print(10 * i + j)


defFunc2(ten_num,one_num):

 print([(10 * i + j)

  for i in range(ten_num)

   for j in range(one_num)])


#Func1(2,5)

Func2(2,5)

The execution result of the program is as follows:


[0, 1, 2, 3, 4,10, 11, 12, 13, 14]

The generated numeric combination results are stored and printed in the form of a list. Procedures to achieve similar functions, but from the above code and results, for compound statement or has its own characteristics.

The details are as follows:

1. From the point of code, the form code of compound statement is more concise;

2. From the perspective of reading, compound sentences are closer to English grammar in terms of expression.

3, in the realization of the results of the matrix, the compound statement has more advantages.


Related articles: