SoFunction
Updated on 2024-11-15

Python's loop structure

while loop structure

Format.

while displayed formula:
  statement block (computing)

Execution process: when the program executes to the while statement, it first judges the truth or falsity of the expression. If the value of the expression is true, then execute the indented statement block, and then return to the expression to continue the judgment; if the value of the expression is false, then skip the indented statement block execution.

Description:

  • Expressions: also called loop conditions
  • Statement blocks: also called loop bodies
  • Dead loop: the loop condition is always valid
  • break: break out of the loop
  • continue: end this loop, go to the next loop
  • else: the corresponding statement block, which will be executed when the loop exits normally, but not when it exits abnormally (break).

for-in loop structure

Description:

It is also a looping structure, often used to facilitate iterable objects such as strings, lists, tuples, dictionaries, etc.

Format:

for x in y:
  fastidious
# Implementation process:xone-time delegateyAn element of the species,The loop ends when the traversal ends.

nested loops

for i in range(1, 11):
  # print('*' * i)
  # Memory loops control how many per line
  for j in range(i):
    print('*', end=' ')
  print()

Selection Sorting Using Loop Nesting

lt = [8, 3, 6, 9, 5, 2, 4, 1, 7]
n = len(lt)
# Outgoing loops control how many rounds are sorted
for i in range(n-1):
  # Memory loop to control comparison of selected elements with others
  for j in range(i+1,n):
    if lt[i] > lt[j]:
      # Generic way of exchanging elements
      # temp = lt[i]
      # lt[i] = lt[j]
      # lt[j] = temp
      # python-specific way
      lt[i], lt[j] = lt[j], lt[i]
print(lt)

Bubbling order using loop nesting

lt = [8, 3, 6, 9, 5, 2, 4, 1, 7]
n = len(lt)
# Outgoing loops control how many rounds are sorted
for i in range(n-1):
  # Memory loop to control comparison of two neighboring elements
  for j in range(n-1-i):
    if lt[i] > lt[i+1]:
      # Generic way of exchanging elements
      # temp = lt[j]
      # lt[j] = lt[j+1]
      # lt[j+1] = temp
      # python-specific way
      lt[i], lt[i+1] = lt[i+1], lt[i]
print(lt)

summarize

Above is the entire content of this article, I hope the content of this article for your study or work has a certain reference learning value, thank you for your support. If you want to know more about the content please check the following related links