当前位置:网站首页>Day4 branch and loop

Day4 branch and loop

2022-06-26 05:47:00 m0_ sixty-seven million thirty-six thousand three hundred and f

day4- Branches and loops

Summary of learning

1. Process control

​ 1) Sequential structure : The code is executed from top to bottom , Each statement is executed only once ( Default )

​ 2) Branching structure : Choose to execute or not execute part of the code according to the conditions ( Use if function )

​ 3) Loop structure : Let the code execute repeatedly (for、while)

2、 Branching structure

Single branch : Perform an operation when a condition is met , If the conditions are not met, it will not be implemented ( If … Just …)
such as : Your father told you :“ If you take an exam 100 You'll be rewarded with a car for every minute ”
Double branch : Perform an operation when a condition is met , If the conditions are not met, perform another operation ( If … Just … Otherwise, …)
such as : Your father told you :“ If you take an exam 100 You'll be rewarded with a car for every minute , Or I'll kill you ”

Multiple branches : Perform different operations according to different conditions

1) if Single branch structure : If … Just …

grammar :

if  Conditional statements :
     Code segment 

explain :
if - keyword ; Fixed writing
Conditional statements - It can be any expression with a result , Include : Specific data 、 Cloud experiment expression ( Assignment operation exception )、 Variables that have been assigned 、 Function call expression, etc
: - Fixed writing ( Colon in English )
Code segment - Structurally, it is and if One or more statements that hold an indent ( At least one ); logically , It is the code that will be executed when the condition is established

2)if Two branch structure - If … Just … otherwise …

grammar :

if  Conditional statements :
     Code segment 1( Code to execute when conditions are met )
else:
     Code segment 2( The condition to be executed when the condition is not met )
#  Judge the parity of an integer 
num = int(input(' Please enter an integer :'))
if num % 2 == 0:
    print(' even numbers ')
else:
    print(' Odd number ')

3)if Multi branch structure - If … Just … If … Just … If … Just … otherwise …

grammar :

if  Conditions 1:
     Code segment 1
elif  Conditions 2:
     Code segment 2
elif  Conditions 3:
     Code 3
...
else:
     Code segment N

 Other code 
 Print the corresponding scholarship amount according to the corresponding score 
# 90 More than  - 2000 element 
# (85,90]-1000 element 
# (75,85]-500 element 
# (60,75]- 200 element 

score = int(input(' Please enter the score :'))
if score > 90:
    print('2000 element ')
elif 85 < score <= 90:
    print('1000 element ')
elif 75 < score <= 85:
    print('500 element ')
elif 60 < score <= 75:
    print('200 element ')
else:
    print(' It's time for you to try ')

3、 Loop structure

1)for loop

grammar :

for  Variable  in  Sequence :
     The loop body 

explain :
for - keyword ; Fixed writing
Variable - Valid variable name ( Can be defined , It can also be undefined )
in - keyword ; Fixed writing
Sequence - Data of container data type , Include : character string 、 list 、 Dictionaries 、 aggregate 、 Tuples 、 iterator 、 generator 、range etc.
: - Fixed writing
The loop body - and for One or more statements that hold an indent ; The loop body is the code to be executed repeatedly

Execution process :
Let the variable go out of the sequence , One by one , Until it's done , Take one and execute a loop
for The number of cycles is related to the number of elements in the sequence

for h in 'hello':
    print(' loop ')

4、range function - Create a sequence of equal differences ( Integers )

1)range(N) - produce [0,N) Equal difference sequence of , The difference is 1
2)range(M, N) - produce [M, N) Equal difference sequence of , The difference is 1
3)range(M,N,step) - produce [M, N) Equal difference sequence of , The difference is step

for h in range(5):
    print('23')

for h in range(5, 7):
    print('23')

for h in range(3, 9, 2):
    print('3')

# ; practice : Print 1000 An even number within 
for h in range(0, 1000, 2):
    print(h)

5、for Two basic application scenarios of the loop

1、 The accumulation of

practice 1: seek 1+2+3+…+100 And

First step : Define the saved results , The initial value of a variable is usually 0( Sum up ) perhaps 1( Find the product )

result = 0

The second step : Use a loop to get cumulative data step by step

for x in range(1, 101):

The third step : In the loop body, merge each data obtained into the variable corresponding to the result

result += x

print(result)

practice 2: seek 10 The factorial :123*…*10

night = 1
for n in range(1, 11):
night *= n
print(night)

practice 3: seek 100 To 200 All can be 3 The sum of even numbers divided by integers

result = 0
for h in range(100, 201):
if h % 3 == 0 and h % 2 == 0:
result += h
print(result)

It can be optimized

Optimize 1

result = 0
for h in range(100, 201, 2):
if h % 3 == 0:
result += h
print(result)

Optimize 2

result = 0
for h in range(102, 201, 6):
result += h
print(result)

2、 Number of Statistics

practice 1: Statistics 1000 Number of odd numbers within

First step : Define the last number of variables saved ,

result = 0

The second step : Use circular statements to count objects

for x in range(1000):

The third step : In case of data matching the conditions, add 1

​ if x % 2 == 1:
​ result += 1
print(result)

practice 2: Statistics 1000 With internal energy 3 Divisible but not by 7 The number of integers

result = 0
for x in range(1000):
if (x % 3 == 0) and (x % 7 != 0):
result += 1
print(result)

Practice your homework

Basic questions

1、 Print according to the range of grades entered ` pass `  perhaps ` fail, `
grade = float(input(' Please enter the grade :'))
if grade < 60:
    print(' fail, ')
else:
    print(' pass ')
2、 Print according to the entered age range ` adult ` perhaps ` A minor `, If the age is not within the normal range (0~150) Print ` This is not a person !`
age = int(input(' Please enter age :'))
if 0 < age < 18:
    print(' A minor ')
elif 18 <= age < 150:
    print(' adult ')
else:
    print(' This is not a person ')
3、 Enter two integers a and b, if a-b The result is an odd number , The result is output , Otherwise, the prompt message will be output `a-b The result is not an odd number `
a = int(input(' Please enter a:'))
b = int(input(' Please enter b:'))
x = a - b
if x % 2 != 0:
    print(x)
else:
    print('a-b The result is not an odd number ')
4. Use for Cyclic output  0~100 All in 3 Multiple .
for x in range(3, 100):
    if x % 3 == 0:
        print(x)
5、 Use for Cyclic output 100~200 The inner single digit or ten digit can be 3 Divisible number .
for x in range(100, 201):
    if (x % 10) % 3 == 0 or (x // 10 % 10) % 3 == 0:
        print(x)
6、 Use for Cycle statistics 100~200 The median ten is 5 The number of 
for x in range(100, 200):
    if x // 10 % 10 == 5:
        print(x)
 7、 Use for Loop printing 50~150 All can be 3 Divisible but not by 5 Divisible number 
for x in range(51,148, 3):
    if x % 5 != 0:
        print(x)
8、 Use for Cycle calculation 50~150 All can be 3 Divisible but not by 5 The sum of divisible numbers 
num = 0
for x in range(51, 148, 3):
    if x % 5 != 0:
        num += x
print(num)
9、 Statistics 100 The inner single digits are 2 And can be 3 The number of integers .
num = 0
for x in range(100):
    if x % 10 == 2 and x % 3 == 0:
        num += 1
print(num)

Advanced

# 1、 Enter any positive integer , Ask him how many digits ?
#  Be careful :  You can't use strings here , Only loop 
number =2345
r = 0
for x in range(100000):
    if number > 1:
        r += 1
        number /= 10
    else:
        break
print(r)
# 2、 Print out all the daffodils , The so-called narcissus number refers to a three digit number , Its figures ⽴ The sum of the squares is equal to the number itself .
# 例 Such as :153 yes ⼀ individual ⽔ Fairy flower number , because   `1³ + 5³ + 3³ `  be equal to  153.
for abc in range(100, 1000):
    a = abc // 100
    b = abc // 10 % 10
    c = abc % 10
    if a ** 3 + b ** 3 + c ** 3 == abc:
        print(abc)
# 3、 Judge whether the specified number is a prime number ( Prime numbers are prime numbers , In addition to 1 A number other than itself that cannot be divided by other numbers )
number = int(input(""))
abc = ' Prime number '
for x in range(2, number):
    if number % x == 0:
        abc = ' Not a quality '
print(abc)
# 4、 Output 9*9 formula .  Program analysis : Branch and column considerations , common 9 That's ok 9 Column ,i The control line ,j Control the column .
for i in range(1, 10):
    for j in range(1, i+1):
        print(i, '*', j, '=', i * j, end='  ')
    print('')
5、 This is the classic " A hundred horses and a hundred burdens " problem , There are a hundred horses , Carry a hundred loads , Big horse, big horse 3 Dan , On the back of a horse 2 Dan , Two ponies carry 1 Dan , How big is it , in , How many ponies each ?
# ( You can directly use the exhaustive method )
for x in range(1, 34):
    for y in range(1, 51):
        for z in range(100):
            if x + y + z == 100 and x * 3 + y * 2 + z / 2 == 100:
                print(x, y, z)
原网站

版权声明
本文为[m0_ sixty-seven million thirty-six thousand three hundred and f]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180505254155.html