Python Foundation - Branch, Circulation

- Restore content to start

Catalog

1. Branch structure

1.1 Preliminary Introduction

Up to now, all the Python codes we write are executed sequentially, but sometimes logical judgments are needed in the code, such as user input username and password, correct input will verify the validation, otherwise the validation will fail. At this time, there will be two branches, and only one branch of the two branches will go on. Of course, there are many similar scenarios, which we call "branching structure" or "selection structure". Compile a set of Python materials and PDF, Python learning materials can be added to the learning group if necessary: 631441315, anyway, idle is also idle, it is better to learn something!~~

Grammatical Format:

    if xxx1:
        Matter 1
    elif xxx2:
        Matter 2
    elif xxx3:
        Matter 3
    else:
        Matter 4

  

1.2 Use Cases

1. User authentication

# -*- coding:utf-8 -*-
"""
//User authentication
version: 0.1
author: coke
"""
username = input("Please enter a user name:")
password = input("Please input a password:")
if username == 'admin' and password == '123456':
    print("Authentication Successful")
else:
    print("Authentication failure")

Output result

 

2. Valuation of piecewise function

"""
//Evaluation of piecewise function
       3x - 5 (x > 1)
f(x) = x + 2 (-1 < x < 1)
       5x + 3 (x <= -1)
version: 0.1
Author: coke
"""
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))

Output result

 

1.3 practice

1. Guessing game

# -*- coding:utf-8 -*-
"""
//Finger guessing game
version: 0.1
author: coke
"""
import random
num = int(input("Scissors (0) Stone (1) Cloth (2):"))
computer = random.randint(0,2)
print("Computer punches:%d"%computer)

if (num == 0 and computer == 2) or (num == 1 and computer == 0) or (num == 2 and computer == 1):
    print("Haha, you won")
elif  num == computer:
    print("A draw. Do you want another one?")
else:
    print("Wash your hands, it's sunrise in the final battle.")

 

2. Grade Conversion of Achievements

"""
//Percentage grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade grade
90 More than    --> A
80 branch~89 branch    --> B
70 branch~79 branch    --> C
60 branch~69 branch    --> D
60 Below    --> E

Version: 0.1
Author: coke
"""

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)

 

2. Cyclic structure

1.1 Preliminary Introduction

If we are going to execute a series of repetitive instructions in the program, such as I want to calculate the sum of 1 - 100 or I want to output 99 Hello worlds, do we have to write one by one? If so, then the programming work is too unreasonable. So, we need to understand the loop structure, if we learn to follow it. The ring structure allows repetitive execution of certain operational instructions.

There are two ways to construct a loop structure in Python: for-in loop and while loop.

for - in cycle

If we can know the number of cycles or iterations to containers (which will be covered later), we would recommend for-in cycles.

for temporary variables in lists or strings, etc.
        Code executed when the loop satisfies the condition

 

while cycle

If you want to construct a loop structure that does not know the exact number of cycles, we recommend using the while loop. The while loop controls the loop by an expression that generates or converts bool values. The value of the expression is True and the value of the expression is False.

while condition:
        When conditions are met, do 1
        When conditions are met, do 2
        When conditions are met, do 3
        (omitted)...

 

break: End the current loop

continue: Used to end this cycle, followed by the next one

Note: break/continue can only be used in loops, but can not be used alone.

 

1.2 Use Cases

1. Calculate the sum of even numbers between 1 and 100 with for cycle

"""
//Summation of 1-100 with for loop
version: 1.0
Author: coke
"""
#-*- coding=utf-8 -*-
sum = 0
for x in range(1,101):
    if x % 2 == 0:
        sum += x
print(sum)

Output result

It should be noted that the range type in the above code can be used to produce a constant sequence of values, and this sequence is usually used in loops, for example:

  • range(101) can produce an integer sequence of 0 to 100.
  • range(1, 100) can produce an integer sequence of 1 to 99.
  • range(1, 100, 2) can produce an odd sequence of 1 to 99, of which 2 is the step size, that is, the increment of the numerical sequence.

 

2. Do not judge and calculate the sum of even numbers between 1-100

"""
//Summation of 1-100 with for loop
version: 1.0
Author: coke
"""
#-*- coding=utf-8 -*-
sum = 0
for x in range(2,101,2):
    sum += x
print(sum)

 

3. Number guessing games

"""
//Number guessing game
//The computer produces a random number between 1 and 100, which is guessed by people.
//The computer gives the hints a little bigger/a little smaller/right according to the guessed numbers.
version: 0.1
admin: coke
"""
import random
answer = random.randint(1,100)
counter = 0
while True:
    counter += 1
    result = int(input("Please enter a number.:"))
    if answer > result:
        print("A little bigger")
    elif answer < result:
        print("Smaller one")
    else:
        print("Guess right.")
        break
if counter > 7:
    print("Insufficient IQ Balance")

 

4. Use of continue and break

"""
continue Use
version: 0.1
author: coke
"""
name = "cokehaha"
for x in name:
    print("----")
    if x == "k":
        continue
    if x == "a":
        break
    print(x)

 

1.3 practice

1. Input two positive integers to calculate the maximum common divisor and the minimum common divisor.

"""
//Input two positive integers to calculate maximum common number and minimum common multiple
version: 0.1
author: coke
"""

x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print('%d and%d The maximum common divisor is%d' % (x, y, factor))
        print('%d and%d The minimum common multiple is%d' % (x, y, x * y // factor))
        break

 

2. Printing triangle pattern

"""
//Print various triangle patterns

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

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

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

version: 0.1
author: coke
"""

row = int(input('Please enter the number of rows: '))
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 < row - i - 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()

- Restore the end of the content.

Keywords: Python Programming

Added by peytonrm on Sat, 21 Sep 2019 16:45:31 +0300