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

Day4 branch and loop summary and operation

2022-06-25 23:26:00 tw886

Today's summary

One 、 Process control

  1. Sequential structure : The code is executed from top to bottom , The statement is executed only once a day .( Default )

    print('hello')
    print('word')
    
  2. Branching structure : Choose to execute or not execute part of the code according to the conditions ( Use if)

    age = 10
    if age >= 18:
        print(' adult ')
    else:
        print(' A minor ')
    
  3. Loop structure : Let the code execute repeatedly (for、while)

for i in range(5):
    print(i)

Two 、if Branching structure

1、if Single branch structure - If … Just …

Problem solved : Perform an operation when conditions are met , When the addition is not satisfied, it will not be executed

grammar :

if Conditional statements :

​ Code segment ( Code that executes only when conditions are met )

if - keyword ; Fixed writing

Conditional statements - You can any expression that has a result , Include : Specific data 、 Operation expression ( Assignment operation exception )、 Assigned

Variable 、 Function call expression, etc
  • Fixed writing

Code segment - Structurally, it is and if One or more statements that hold an indent ( At least one ); logically , Code snippets are conditional

Code that will be executed when

age = 20
if age >= 18:
    print(' adult ')

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

grammar :

if Conditional statements :

​ Code segment 1( Code that needs to be executed to meet the conditions )

else:

​ Code segment 2( Code to be executed when conditions are not met )

Code segment 3( Whether the conditions are met or not )

# Print if the specified year is a leap year ' Leap year '
year = 2001
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    print(' Leap year ')
else:
    print(' Non leap year ')

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 segment 3

else:

​ Code segment N

Be careful :elif It could be any number ,else There can be or not

score = 83
if  score >= 90:
    print(' good ')
elif score >= 80:
    print(' good ')
elif score >= 70:
    print(' secondary ')
elif score >= 60:
    print(' pass ')
else:
    print(' fail, ')

3、 ... and 、for loop

1、for loop

1) grammar :

for Variable in Sequence :

​ The loop body ( Code that needs to be executed repeatedly )

2) 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 class data type , Container data types 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 that needs to be executed repeatedly

3) Execution process

Let the variable go out of the sequence , One by one , Until it's done ; Take a value and execute the loop body once

for The number of cycles is related to the number of elements in the sequence

2、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 [0,N) Equal difference sequence of , The difference is step

3、 Application scenarios

1) Cumulative sum

First step : Define variables to save results , The initial value of a variable is usually zero ( Sum up ) perhaps 1( Find the product )

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

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

# seek 1+2+3+...+100 And 
result = 0
for i in range(1,101):
    result += i
print(result)

2) Number of Statistics

First step : Define the last number of variables saved , The default built-in variables are 0

The second step : Use the loop to get the statistical object

The third step : When you encounter a number of data that meet the statistical conditions, add 1

# Statistics 1-1000 The number of odd numbers in 
count = 0
for i in range(1000):
    if i % 2 == 1:
        count += 1
print(count)

Homework

Basic questions

  1. Print according to the range of grades entered pass perhaps fail, .

    score = float(input(' Please enter the score :'))
    if score >= 60:
        print(' pass ')
    else:
        print(' fail, ')
    
  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 age <= 18:
        print(' A minor ')
    elif 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 Value :'))
    b = int(input(' Please enter b Value :'))
    if (a - b) % 2 == 1:
        print(a - b)
    else:
        print('a-b The result is not an odd number ')
    
  4. Use for Cyclic output 0~100 All in 3 Multiple .

    for i in range(0,101,3):
        print(i)
    
  5. Use for Cyclic output 100~200 The inner single digit or ten digit can be 3 Divisible number .

    for i in range(100,201):
        if (i % 10 % 3) == 0 or (i // 10 % 10 % 3) == 0:
            print(i)
    
  6. Use for Cycle statistics 100~200 The median ten is 5 The number of

    count = 0
    for i in range(100,201):
        if i // 10 % 10 == 5:
            count += 1
    print(count)
    
  7. Use for Loop printing 50~150 All can be 3 Divisible but not by 5 Divisible number

    for i in range(50,151):
        if i % 3 == 0 and i % 5 != 0:
            print(i)
    
  8. Use for Cycle calculation 50~150 All can be 3 Divisible but not by 5 The sum of divisible numbers

    sum = 0
    for i in range(50,151):
        if i % 3 == 0 and i % 5 != 0:
            sum += i
    print(sum)
    
  9. Statistics 100 The inner single digits are 2 And can be 3 The number of integers .

    count = 0
    for i in range(3,100,3):
        if i % 10 == 2:
            count += 1
    print(count)
    

Advanced questions

  1. Enter any positive integer , Ask him how many digits ?

    Be careful : You can't use strings here , Only loop

    count = 0
    num = input(' Please enter an integer :')
    for i in num:
        if i != '':
            count += 1
    print(count)
    
  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 num in range(100,1000):
        if ((num // 100)**3 + (num // 10 % 10)**3 + (num % 10)**3) == num:
            print(num)
    
  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 )

    num = int(input(' Please enter a number :'))
    for i in range(2, num):
        if num % i == 0:
            print(' Not primes ')
            break
        else:
            print(' Prime number ')
            break
    
  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(j,'x',i,'=',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 )

big_horse = 0
medium_horse = 0
small_horse = 0
for big_horse in range(34):
    for medium_horse in range(51):
        for small_horse in range(200):
            if big_horse * 3 + medium_horse * 2 + small_horse * 0.5 == 100 and big_horse + medium_horse + small_horse == 100 :
              print(big_horse,medium_horse,small_horse)
原网站

版权声明
本文为[tw886]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180603308666.html