Fundamentals of Python 03 – branch and loop structure

Time:2020-1-11

 This article is included inPython from introduction to Mastery Series

1. Branch structure

1.1 Application scenario

So far, we’ve writtenPythonCode is executed in a sequence of statements. This code structure is usually calledSequential structure。 However, only sequence structure can’t solve all the problems. For example, when we design a game, the first pass condition of the game is that the player gets1000After finishing the game, we will decide whether to enter the second level or tell the players according to the scores they get“Game Over”There will be two branches, and only one of them will be executed. There are many similar scenes, we call this structureBranch structureorSelection structure

 

1.2 ifUse of statements

stayPythonTo construct a branch structure, you can use theifelifandelseKeyword. Keywords are words with special meanings, such asifandelseIt’s a keyword specifically used to construct a branch structure. Obviously you can’t use it as a variable name (in fact, it can’t be used as another identifier).

01-Single branch

The following example shows how to construct a branch structure.

“””

User authentication

 

Version: 0.1

Author: along

“””

username = input(enter one user name: ‘)

password = input(Please input a password: ‘)

 

if username == ‘along’ and password == ‘12345’:

    print(Verifying and passing)

else:

    print(Validation failed) 

The only thing that needs to be said is andC/C++JavaDifferent languages,PythonInstead of using curly braces to construct code blocks, you use indentation to set the code hierarchy ififIf the condition holds, multiple statements need to be executed, as long as multiple statements have the sameindentIn other words, if continuous code keeps the same indentation, they belong to the same code block, which is equivalent to a whole execution.

 

02-Multiple branches

Of course, if you want to construct more branches, you can useif…elif…else…Structure, such as the following piecewise function evaluation.

“””

Piecewise function evaluation

 

        3x – 5  (x > 1)

f(x) =  x + 2   (-1 <= x <= 1)

        5x + 3  (x 

 

Version: 0.1

Author: along

“””

x = float(input(Please enter a number: ‘))

if x > 1 :

    y = 3 * x – 5

elif x >= –1 and x <= 1 :

    y = x + 2

else:

    y = 5 * x + 3

print(‘f(%.2f) = %.2f % (x , y))

 

03-Nested branch

Of course, according to the needs of actual development, the branch structure can be nested. For example, after determining whether to pass the customs, you need to give a grade to your performance according to the number of treasures or props you get (such as lighting two or three stars). Then we need toifA new branch structure is constructed in the inner part ofelifandelseWe can also construct new branches in, which we call nested branch structure, that is to say, the code above can also be written as follows.

“””

Piecewise function evaluation

        3x – 5  (x > 1)

f(x) =  x + 2   (-1 <= x <= 1)

        5x + 3  (x 

 

Version: 0.1

Author: along

“””

x = float(input(‘x = ‘))

if x > 1:

    y = 3 * x – 5

else:

    if x >= –1:

        y = x + 2

    else:

        y = 5 * x + 3

print(‘f(%.2f) = %.2f % (x, y))

Explain: You can feel for yourself which is better. As we mentioned beforePythonThere is a saying in Zen“Flat is better than nested.”, the reason for advocating codeDelayeringBecause the nesting level of nested structure will seriously affect the readability of the code, so you should not use nesting when you can use flat structure.

 

1.3 Practice

Practice1: inch in English units are interchanged with centimeter in metric units.

Reference answer:

“””

English units inches and metric units centimeters interchanged

 

Version: 0.1

Author: along

“””

value = float(input(Please enter the length: ‘))

unit = input(Please enter unit: ‘)

if unit == ‘in’ or unit == inch:

    print(%finch = %fcentimeter % (value, value * 2.54))

elif unit == ‘cm’ or unit == centimeter:

    print(%fcentimeter = %finch % (value, value / 2.54))

else:

    print(Please enter a valid unit)

 

Practice2: 100% to grade.

Requirement: if the score entered is90Score above (including90Output)A80branch-90(excluding)90Output)B70branch-80(excluding)80Output)C60branch-70(excluding)70Output)D60Sub outputE

Reference answer:

“””

Conversion of 100% to grade

 

Version: 0.1

Author: along

“””

score = float(input(Please enter your score: ‘))

if score >= 90:

    grade = ‘A’

elif score >= 80:

    grade = ‘B’

elif score >= 70:

    grade = ‘C’

elif score >= 60:

    grade = ‘D’

else:

    grade = ‘E’

print(The corresponding level is:’, grade)

 

Practice3: enter the length of three sides. If you can form a triangle, calculate the perimeter and area.

Reference answer:

“””

Determine whether the input side length can form a triangle, and if it can, calculate the perimeter and area of the triangle

 

Version: 0.1

Author: along

“””

a = float(input(‘a = ‘))

b = float(input(‘b = ‘))

c = float(input(‘c = ‘))

if a + b > c and a + c > b and b + c > a:

    print(Perimeter%f % (a + b + c))

    p = (a + b + c) / 2

    area = (p * (p – a) * (p – b) * (p – c)) ** 0.5

    print(The measure of area%f % (area))

else:

    print(Can’t form a triangle)

Explain: The formula used above to calculate the area of a triangle by its side length is calledHelen formula

Pay attention to review the knowledge of equilateral triangles and right triangles in the students’ time. The blogger forgot at that time. (covering face)~

 

2. Cyclic structure

2.1 Application scenario

If we need to execute some or some instructions repeatedly in the program, such as using the program to control the robot to play football, if the robot holds the ball and has not yet entered the shooting range, then we should always give the command to let the robot run towards the goal. Of course, you may have noticed that there are not only actions that need to be repeated in the description just now, but also the branch structure mentioned in the previous chapter. For another simple example, we need to implement a1Print once on screen in seconds“hello, world”And continue to print the program for an hour, we can’t directlyprint(‘hello, world’)This code says3600Time, if you really want to do this, then the work of programming is too boring. Therefore, we also need to understand the circular structure. With the circular structure, we can easily control something or something to repeat, repeat and repeat to execute.

stayPythonThere are two ways to construct cyclic structure infor-in LoopsOne iswhile Loop

 

2.2 for-inloop

If you knowNumber of loop executionsOr toIterate over a container(later on), then we recommend usingfor-inCycle.

 

01-case1

For example, calculate in the following code1~100The result of summation($\displaystyle \sum \limits_{n=1}^{100}n$)。

“””

useforLoop implementation1~100Summation

 

Version: 0.1

Author: along

“””

sum = 0

for a in range(101):

    sum += a

print(sum) 

It should be noted thatrange(101)Can be used to construct a0reach100In this way, a sequence of integers can be constructed and used in the loop, for example:

  • Range (101) can produce a sequence of integers from 0 to 100.
  • Range (1, 100) can produce a sequence of integers from 1 to 99.
  • Range (1, 100, 2) can generate an odd number sequence from 1 to 99, where 2 is the step size, that is, the increment of the number sequence.

for b in range(10):

    print(b)

for b in range(1,10):

    print(b)

for b in range(1,10,2):

    print(b)

 

02-case2

Knowing this, we can use the following code to implement1~100Sum even numbers between.

“””

useforLoop implementation1~100Even sum between

 

Version: 0.1

Author: along

“””

sum = 0

for i in range(2,101,2):

    sum += i

print(sum)

 

03-for_inandifCombination

You can also do the same by using a branch structure in a loop, as shown below.

“””

useforLoop implementation1~100Even sum between

 

Version: 0.1

Author: along

“””

 

sum = 0

for i in range(1101):

    if i % 2 == 0:

        sum += i

print(sum)

 

2.3 whileloop

If you want to constructDo not know the specific number of cyclesWe recommend usingwhileCycle.whileThe ability to produce or convert out ofboolValue to control the loop,The value of the expression isTrueLoop continues with the value of the expressionFalseLoop end

01-Infinite cycle

Let’s go through aGuess the numberA computer game1~100Between the random numbers, people input their own guess number, the computer gives the corresponding prompt information, until people guess the number of the computer) to see how to usewhileCycle.

“””

Figure guessing game

A computer1~100The random number between is guessed by people

The computer gives a bigger prompt according to the number people guess/Smaller one/Guess right.

 

Version: 0.1

Author: along

“””

import random

 

answer = random.randint(1,100)

counter = 0

# print(answer)

 

while True:

    counter += 1

    number = int(input(Please enter a number: ‘))

    if number > answer:

        print(Smaller one)

    elif number 

        print(A little bigger)

    else:

        print(Congratulations, that’s right)

        break

print(You guessed it all%dsecond % counter)

if counter >= 7:

    print(Your IQ balance is obviously insufficient)

Used in the above codeBreak keywordTo terminate the cycle ahead of time, note thatbreakIt can only terminate the cycle it is in, which needs to be noted in the use of nested loop structures (discussed below). exceptbreakIn addition, there is another keywordcontinue, it can be used toGive up the subsequent code of this cycle and let it go to the next round

 

02-Nested loop

Like branch structure, loop structure can be nested, that is to say, loop structure can be constructed in loop. The following example shows how to output a multiplication table through nested loops.

“””

Output multiplication table(Table 90)

 

Version: 0.1

Author: along

“””

 

for i in range(110):

    for j in range(1, i + 1):

        print(%d*%d=%d % (j, i, i * j), end=\t)

    print()

 

2.4 Practice

Practice1: enter a positive integer to determine whether it is a prime.

Hint: prime number refers to the number that can only be1Greater than1Integer.

Reference answer:

“””

Enter a positive integer to determine if it is a prime

 

Version: 0.1

Author: along

“””

from math import sqrt

 

num = int(input(Please enter a positive integer: ‘))

end = int(sqrt(num))

is_prime = True

for x in range(2, end + 1):

    if num % x == 0:

        is_prime = False

        break

if is_prime and num != 1:

    print(%dPrime number % num)

else:

    print(%dNot primes % num)

 

Practice2: enter two positive integers and calculate their maximum common divisor and minimum common multiple.

Reference answer:

“””

Enter two positive integers to calculate their maximum common divisor and minimum common multiple

 

Version: 0.1

Author: along

“””

x = int(input(‘x = ‘))

y = int(input(‘y = ‘))

Ifxgreater thanyOn exchangexandyValue

if x > y:

    Through the following operationyAssign the value tox, takexAssign the value toy

    x, y = y, x

Start a decreasing cycle from the number of the two

for factor in range(x, 0, –1):

    if x % factor == 0 and y % factor == 0:

        print(%dand%dThe greatest common divisor of%d % (x, y, factor))

        print(%dand%dThe minimum common multiple of is%d % (x, y, x * y // factor))

        break

 

Practice3: print the triangle pattern as shown below.

Note: firstLeftRight angle,rightRight angle, last isosceles triangle

*
   **
  ***
 ****
*****
*
   **
  ***
 ****
*****
*
   ***
  *****
 *******
*********

Reference answer:

“””

Print triangle pattern

 

Version: 0.1

Author: along

“””

row = int(input(Please enter the number of lines: ‘))

for i in range(row):

    for _ in range(i + 1):

        print(‘*’end=)

    print()

 

 

for i in range(row):

    for j in range(row):

        if j 1:

            print(‘ ‘end=)

        else:

            print(‘*’end=)

    print()

 

for i in range(row):

    for _ in range(row – i – 1):

        print(‘ ‘end=)

    for _ in range(2 * i + 1):

        print(‘*’end=)

    print()

 

If you are interested in branch and loop structures in Linux, choose transfer.