This is the 11th day of my participation in Gwen Challenge


The introduction

There are two types of loops in Python syntax

  • whilecycle
  • forcycle

The use of the keywords continue and break in loops is described.


The basic structure of a program

In program development, there are three basic structures:

  • Sequential – Execute code sequentially, from top to bottom
  • Branch/select – Decide which branch of code to execute based on criteria
  • Loop – Let specific code be executed repeatedly


whileCyclic basic use

  • The purpose of a loop is to execute the specified code repeatedly
  • whileThe most common application scenario for loops isLet the code executeIn accordance with theSpecified number repeatperform


whileBasic statement syntax


whileJudgment condition: loop body statementCopy the code


Note: The while statement and the indentation part are a complete block of code


While loop flowchart

Graph TD start -->cond --True-->op -->cond --False-->stop


While loop case

Print Hello Python five times

In [22]: 
In [23]: i = 1	# define a repeat count

In [24] :while i <= 5:
    ...:     print('Hello Python')
    ...:
    ...:     # handle counter I. : i = i +1. : Hello Python Hello Python Hello Python Hello Python Hello PythonCopy the code


Print the little star

demand

  • Output five lines in a row on the console*, the number of asterisks on each line increases successively
*
**
***
****
*****
Copy the code
  • Using strings*print
#! /usr/bin/python3
# -*- coding:utf-8 -*-

# define a counter variable that starts with the number 1
row = 1

while row <= 5:

    print("*" * row)

    row += 1

Copy the code


Counting methods in Python

There are two common counting methods, which can be called respectively:

  • Natural counting method(from1Start) — more in line with human habits
  • Procedure counting(from0Start) — almost all programming languages choose from0Start counting

When we programmers write programs, we try to get into the habit of counting loops starting at zero unless a requirement specifically requires it


whileA nested loop

While nesting is: while has a while inside of it


The basic grammar

whileconditions1: outer circulatory body...whileconditions2: inner circulatory body... Outer circulatory body...Copy the code


Suppose Python does not provide string * operations to concatenate strings

demand

  • Output five lines in a row on the console*, the number of asterisks on each line increases successively
*
**
***
****
*****
Copy the code


Development steps

  • 1) Simple output of 5 lines of content
  • 2) Analyze the inside of each line*How should it be handled?
    • Each row displays the same number of stars as the current row
    • Nest a small loop that deals specifically with each rowcolumnStar display
#! /usr/bin/python3
# -*- coding:utf-8 -*-

row = 1

while row <= 5:

    # Assuming python does not provide string * operations
    # Inside the loop, add another loop to print stars for each row
    col = 1

    while col <= row:
        print("*", end="")

        col += 1

    Add a new line after each line of asterisk output
    print()

    row += 1
Copy the code


print()The function to strengthen

  • By default,printAfter the function outputs the content, it automatically adds a newline to the end of the content
  • If you don’t want to add a line break to the end, you can use theprintThe output content of the function is added later, end=""
  • Among them""In between you can specifyprintAfter the function outputs the content, proceed with what you want to display
  • The syntax is as follows:
No line breaks after output to the console
print("*", end="")

print("*", end="")	# Add two Spaces to the end, no line breaks

print("*", end="\t")	# Add a TAB bit to the end, no line breaks

# Simple line feeds
print(a)Copy the code

End =”” in print() means that there will be no line breaks after the output to the console is finished


Infinite loop

Because the programmer forgot to modify the judgment condition of the loop inside the loop, the loop continued to execute, and the program could not be terminated!

# always print hello
i = 0
while i <= 10:
    print('hello')
    
    # i = i + 1
Copy the code

You can force out of the loop by pressing Ctrl + C in the console.


forCyclic basic use

The for loop in Python iterates over any Iterable, such as a list, string, etc.

Iterables are covered in the Python Advanced Section. If you want to learn more about them, you can start by looking at Python iterators


Basic syntax for the for statement


forvariableinIterable: the body of a loopCopy the code


For loop flowchart

Graph TD start -->cond{is there any element left? } cond - True - > op [repeat code] -- > cond cond - False - > stop [over]


For instance

Iterate over the list of programming languages

In [1]: languages = ['C'.'Python'.'Java'.'C++'.'Php']

In [2] :for lang inlanguages: ... :print(lang) ... : C Python Java C++ Php In [3] :Copy the code


Traversal string

In [3]: message = 'Life is short, I use Python'

In [4] :for msg inmessage: ... :print(msg) ... I use P y t h o n In [5] :Copy the code


traverserange()A sequence of numbers generated

range()grammar

range(start, stop[, step])
Copy the code


Parameter Description:

  • start: Counting starts from start. The default value is 0. For example,range(3)Is equivalent torange(0, 3)
  • stop: count to stop end, butDo not includestop. For example,range(0, 5)[0, 1, 2, 3, 4]No. 5
  • step: step length,The default is1. For example,range(0, 3)Is equivalent torange(0, 3, 1)


IPython test

In [10] :# specify only start
    
In [11] :list(range(6))
Out[11] : [0.1.2.3.4.5]

In [12] :# start/stop

In [13] :list(range(3.10))
Out[13] : [3.4.5.6.7.8.9]

In [14] :# start, stop, and step are specified

In [15] :list(range(0.10.2))
Out[15] : [0.2.4.6.8]
Copy the code

So you use a list to show the internal elements.


forTo iterate overrange()

In [16] :# for loop over range()

In [17] :for i in range(6) :... :print(i) ... :0
1
2
3
4
5

In [18] :for i in range(3.9) :... :print(i) ... :3
4
5
6
7
8

In [19] :for i in range(0.10.2) :... :print(i) ... :0
2
4
6
8

In [20] :Copy the code


The for loop is nested

For nesting is: for has a for inside it


The basic grammar

forvariableinIterable: outer loop body...forvariableinIterable: inner loop body... Outer circulatory body...Copy the code


Case study: Find 1! + 2! + 3! + 4! + 5! The sum of the factorial accumulations between, [1, 5].

  • 2 factorial 2 factorial That’s 1 times 2

  • 3 factorial 3 factorial 1 times 2 times 3

  • .


The program design is as follows

#! /usr/bin/python3
# -*- coding:utf-8 -*-

total = 0

for i in range(1.6) :# Compute the factorial of I
    temp = 1
    for j in range(1, i+1):
        temp = temp * j
    
    So let's add up each factorial
    total = total + temp
    
print(total)	# result is 153
Copy the code


Break and continue

Break and continue are keywords specifically used in loops to break loops.

  • breakTo exit the loop without further code execution
  • continue, terminates the loop, does not execute the subsequent code, and conducts the loop condition judgment again

Break and continue are valid only for the current loop


break

  • In the cycleIf theIf one of the conditions is satisfied.Don’tHope againLoop continues, you can usebreakExit the loop
i = 0

while i < 10:

    # break When a condition is met, the loop is broken and no subsequent iterations of the code are executed
    # i == 3
    if i == 3:
        break

    print(i)

    i += 1

print("over")
Copy the code


Break is valid only for the current loop


continue

  • In the cycleIf theIf one of the conditions is satisfied.Don’thopeExecute loop code, but do not want to exit the loop, you can usecontinue
  • There are only certain conditions in the loop that do not need to be executed, and all other conditions need to be executed
i = 0

while i < 10:

    # when I == 7, you don't want to execute code that needs to be executed repeatedly
    if i == 7:
        The counter should also be modified before using continue
        Otherwise there will be an infinite loop
        i += 1

        continue

    # repeatable code
    print(i)

    i += 1

Copy the code
  • Note: usecontinueWhen,The conditional handling section of the code needs special attention, not careful will appearInfinite loop

Continue is valid only for the current loop


Else syntax for Python loops

The Python loop statement for, while may have an else branch that is fired when a for loop completes normally or when a while loop completes normally (the loop condition is False), but if the loop is abnormally terminated by a break statement, The else branch does not execute.


while … else …

whileCirculation conditions: circulation body...else: The loop ends normallyCopy the code


for … else …

forvariableinIterable: the body of a loopelse: The loop ends normallyCopy the code


IPython test

# for loop
In [1] :for i in range(5) :... :print(i) ... :else:
   ...:     print('For loop completes properly')
   ...:     print(i) ... :0
1
2
3
4
forNormal end of cycle4


# the while loop
In [2]: num = 1. :... :while num <= 5:
   ...:     print(num) ... : num = num +1. :else:
   ...:     print('While loop ends normally')
   ...:     print(num) ... :1
2
3
4
5
whileNormal end of cycle6


# break interrupt
In [3] :for i in range(10) :... :print(i) ... :if i == 5:
   ...:         break. :else:
   ...:     print('For loop completes properly')
   ...:     print(i) ... :0
1
2
3
4
5
Copy the code


Application scenarios

Take the example of finding primes in the official Python documentation – print primes up to 10

for n in range(2.10) :for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, The '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

Copy the code


The running results are as follows:

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Copy the code


Circular actual combat small case

[0, 100]The sum of all the even numbers between

# 0. Used to count final results
result = 0

# 1. Counters
i = 0

# 2. Start the loop
while i <= 100:

    # Determine even numbers
    if i % 2= =0:
        result += i  # add
        
    i += 1

print(result)	# result = 2550

Copy the code


Print isosceles triangles

demand

  • Print n-layer isosceles triangles

  • Print using a string *

  • The number of * in each layer increases in order of 1, 3, 5, 7, 9, and forms an isosceles triangle


For example, the isosceles triangle of layer 5 is shown as follows:

    *
   ***
  *****
 *******
*********
Copy the code


The program design is as follows

#! /usr/bin/python3
# -*- coding: utf-8 -*-

while True:
    level = input('Please enter the number of layers to print the isosceles triangle (enter Q to exit):')

    if level == 'q':
        break

    # to int
    level = int(level)

    row = 1     # hierarchy counter

    while row <= level:

        Count the number of Spaces per layer
        space_count = level - row
        print(' ' * space_count, end=' ')    Print Spaces without newlines

        # Count the number of layers *
        char_count = row * 2 - 1
        print(The '*' * char_count)             Print the * for each layer and wrap it

        The level count increases by 1
        row = row + 1
Copy the code


The running results are as follows:

Please enter the number of layers to print isosceles triangles (enter Q to exit):3**** ***** Please enter the number of layers to print the isosceles triangle (enter Q to exit):5* * * * * * * * * * * * * * * * * * * * * * * * * please enter to print an isosceles triangle layer (exit) input q:7* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * please enter to print an isosceles triangle layer (exit) input q: q Process finishedwith exit code 0
Copy the code


Print the 99 times table

for i in range(1.10) :for j in range(1, i + 1) :# print(f'{j} * {i} = {j * i}', end='\t')
        print('%d * %d = %d' % (j, i, j * i), end='\t')  Each line is separated by a TAB character
    print(a)Copy the code


This uses the formatted output of the string, where

  • f'{j} * {i} = {j * i}'Before the stringf, it isTemplate string, can be used directly within a string{xxx}To reference a variable or perform a corresponding operation.
  • '%d * %d = %d' % (j, i, j*i)', is a formatted string,%dIndicates a format integer number%The following data will be filled in%dThe placeholder.

This is only a preliminary introduction, which will be covered in more detail in a subsequent string tutorial.


The running results are as follows:


The tail language

✍ Code writes the world and makes life more interesting. ❤ ️

✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️

✍ code word is not easy, but also hope you heroes support. ❤ ️