MOOC: \ program control structure (fourth week) 21.7.25

MOOC – Python language programming (15th)

Control structure of procedure (fourth week) 21.7.25


Example 5: body mass index BMI

# Reference code

height, weight = eval(input())
bmi = weight / pow(height, 2)
print("BMI The value is:{:.2f}".format(bmi))
who, nat = "", ""
if bmi < 18.5:
    who, nat = "Thin ", "Thin "
elif 18.5 <= bmi < 24:
    who, nat = "normal", "normal"
elif 24 <= bmi < 25:
    who, nat = "normal", "Overweight"
elif 25 <= bmi < 28:
    who, nat = "Overweight", "Overweight"
elif 28 <= bmi < 30:
    who, nat = "Overweight", "Obesity"
    who, nat = "Obesity", "Obesity"
print("BMI The index is:international'{0}',domestic'{1}'".format(who, nat))

Example 6: Calculation of PI

# Reference code

from random import random, seed

DARTS = eval(input())
hits = 0.0
for i in range(DARTS):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)

Addition, subtraction and addition of integers

# The addition, subtraction, and addition of integers py
Among them, all numbers are integers, increasing from 1, odd numbers are positive and even numbers are negative

s = 0
for i in range(0,967):
    if i%2 ==1:
        s +=i
        s -=i

Three daffodils

"Narcissistic number "It refers to a three digit integer whose sum of the 3rd power of each digit is equal to the number itself.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬
For example: ABC It's a"3 Number of bit daffodils",Then: A The third power of+B The third power of+C The third power of = ABC
 Please output all 3-bit daffodils in descending order. Please use"comma"Separate output results.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

for i in range(100,1000):
    a = i//100 # hundreds
    b = i//10% 10 # tens
    c = i%10    # Bit
    if i == a**3+b**3+c**3:

Three opportunities for users to log in

Give users three opportunities to enter user name and password. The requirements are as follows:
1)If you enter the first line, enter the user name as'Kate',The password entered in the second line is'666666',output'Login succeeded
2)When the user name or password is incorrect for a total of 3 times, output "the user name or password is incorrect for 3 times"!Exit the program.

count = 3
while count:
    name = input()
    code = input()
    if name == 'Kate' and code == '666666':
        print('Login succeeded!')
        count -= 1
if count == 0:
    print("3 The user name or password is incorrect! Exit the program.")

Single choice questions

1. Which option does not meet the syntax requirements in the blank space of the above program?

for var in _____:





Correct answer C

For... In... The in must be followed by an iteration type (composite type), {1; 2; 3; 4; 5} is not a valid data type for Python.

2. Which option is the output of the above program?

for i in range(0,2):

A,1 2


C,0 1 2

D,0 1

Correct answer D

range(0, 2) outputs two values: 0 and 1.

3. Which option gives the output times of the above program? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

k = 10000
while k>1:





Correct answer C

4. The \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\the \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\8235;‬‭‬‬‬‬‬‬‬‬‬‬‬‬‬‮‬‬‬ which options are the three basic structures of the program? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

A. Sequential structure, jump structure, loop structure

B. Process structure, object structure, function structure

C. Process structure, loop structure, branch structure

D. Sequential structure, cyclic structure, branch structure

Correct answer D

No object structure, jump structure, process structure, etc.

5. Which option describes the loop structure incorrectly? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

A. Loop is a running mode in which the program repeatedly executes backward according to the result of condition judgment

B. Both conditional loop and ergodic loop structures are basic loop structures

C. Loop is a basic control structure of program

D. The loop cannot exit and has no effect

Correct answer D

The dead loop can be used to test performance. The formal dead loop can be exited with break, for example:

x = 10
while True:
    x = x - 1
    if x == 1:

Dead circulation has its function.

6. For the Python statement P= -P, which option is described correctly? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

A. P equals its negative number

B. Assign P to its negative number


D. Absolute value of P

Correct answer B

In Python, = = is the assignment symbol, and = = is the equality symbol for judging equality.

7. Which option is used to determine whether the current Python statement is in the branch structure? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

A. Braces

B. Colon

C. Indent

D. Quotation marks

Correct answer C

Indents represent hierarchical relationships.

8. Which option is the result of the execution of the following code? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

for s in "PYTHON":
   if s=='T':





Correct answer A

continue ends the current cycle, but does not jump out of the current cycle.

9. Which option is the function used to generate random decimals in the random library? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬





Correct answer B

Random(), getrandbits(), and random() all generate random integers, and random() generates random decimals between 0 and 1.

10. With regard to try except, which option description is wrong? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

A. It expresses the characteristics of a branch structure

B. NameError is an exception type

C. If exception handling is used, the program will not make any more errors

D. It is used to catch and handle program exceptions

Correct answer C

With exception handling, the program may run without error, but it may logically fail. Program error is a big concept, which not only refers to code operation error, but also represents functional logic error.

Programming problem

Four rose trees

The four digit rose number is a four digit self idempotent number. Self idempotent refers to a n Number of digits, the number of digits on each of its bits n The sum of powers equals itself.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬
For example, when n When it is 3, there is 1^3 + 5^3 + 3^3 = 153,153 That is n A self idempotent when it is 3. A 3-digit self idempotent is called daffodil number.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬
Please output all 4-digit four digit rose numbers, one line for each number in descending order.

s = ""
for i in range(1000, 10000):
    t = str(i)
    if pow(eval(t[0]),4) + pow(eval(t[1]),4) + pow(eval(t[2]),4) + pow(eval(t[3]),4) == i :

Sum of prime numbers within 100

 Find the sum of all primes within 100 and output.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬
A prime number is an integer that is greater than 1 and can only be divided by 1 and itself.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬
Tip: you can judge whether each number within 100 is a prime number one by one, and then sum it.
s = 0
for i in range(2,100):
    flag = 0                # Flag flag whether it is a prime number. 0 is prime, 1 is not
    for j in range(2,i//2+1):
        if i%j ==0:
            flag = 1
    if not flag :

Study notes

1. Branch structure of program

1.1 single branch structure (if)

1.2 if else

----Compact form: < expression 1 > If < condition > else < expression 2 >

1.3 if elif else

1.4 condition judgment

Operators: <, < =, > =, >, = ==

Reserved words: and, or, not

1.5 program exception handling


	<Statement block 1>
except <Exception type>:
  <Statement block 2>
	<Statement block 1>
  <Statement block 2>
  <Statement block 3>	# Execute when no exception occurs
  <Statement block 4>	# It will be implemented

2. Example 5: body mass index BMI

BMI:Depiction of body mass
--The standard commonly used in the world to measure human obesity and health
--definition: BMI=weight(kg)/height²(㎡)

# Idea 1: calculate and give the international and domestic BIM classification respectively

# Train of thought 2: mixed calculation and international and domestic BMI classification

#   # blend
height,weight = eval(input("Please enter your height(rice)And weight(kg .)[Comma separated]:"))
bmi = weight / pow(height,2)
print("BMI The value is:{:.2f}".format(bmi))
who,nat = '',''
if bmi < 18.5:
    who,nat = 'Thin ','Thin '
elif 18.5 <= bmi < 24:
    who,nat ='normal','normal'
elif 24 <= bmi < 25:
    who,nat ='normal','Overweight'
elif 25 <= bmi < 28:
    who, nat = 'Overweight','Overweight'
elif 28 <= bmi <30:
    who, nat = 'Overweight','Obesity'
    who,nat = "Obesity","Obesity"
print("BMI Indicators: International{0},domestic{1}".format(who,nat))

3. Loop structure of program

3.1 traversal cycle

for <Cyclic variable> in <Ergodic structure> : 
	<Statement block>

	Counting cycle:		for i in range(M,N,K):
	String traversal loop:	for c in s:
	List traversal loop:	for item in ls:
	File loop variable:	for line in fi:		# Traverse each line

3.2 infinite cycle

while <condition> :
  <Statement block>
# ctrl+c exit infinite loop

3.3 cyclic control reserved word

break: jump out and end the current whole loop, and execute the statement after the loop

Continue: end the current cycle and continue to execute the subsequent cycles

3.4 cycle expansion

for <Cyclic variable> in <Ergodic structure>:
  <Statement block 1>
  <Statement block 2>
# -----------------------------------
while <condition>:
  <Statement block 1>
  <Statement block 2>
# When the loop is not exited by the break statement, the else statement block is executed
# Similar to the else usage of exception handling

4. Module 3: random library

4.1 overview of random library

The random library is a Pyhton standard library that uses random numbers

Pseudo random number: a (pseudo) random sequence element generated by Mason rotation algorithm

- basic random number functions: seed(), random()
- extended random number functions: randint(), getrandbits(), uniform(), randrange(), choice(), shuffle()

4.2 basic random function

seed(a=None)Initializes the given random number seed. The default is the current system time
random()Generate a random decimal between [0.0,1.0]

4.3 extended random function

randint(a,b)Generate an integer between [a,b]
randrange(m,n[,k])Generate a random integer between [m,n) in steps of k
getrandbiits(k)Generate a random integer longer than k
uniform(a,b)Generate a random decimal between [a,b]
choice(seq)Randomly select an element from the sequence seq
shuffle(seq)Randomly arrange the elements in the sequence seq and return the disrupted sequence

5. Example 6: Calculation of PI

#    # PI formula method

pi = 0
N = 100
for k in range(N):
    pi += 1/pow(16,k)*(
print("The pI value is:{}".format(pi))


#    # Monte Carlo method

from random import random
from time import perf_counter

DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1,DARTS+1):
    x,y = random(), random()
    dist = pow(x**2+y**2,0.5)
    if dist <= 1.0:
        hits = hits +1
pi = 4 * (hits/DARTS)
print("The pI value is{}:".format(pi))
print("The running time is:{:.5f}s".format(perf_counter( )-start))

Python language programming_ Beijing University of Technology_ China University MOOC (MOOC)

Keywords: Python

Added by Misery_Kitty on Sat, 15 Jan 2022 00:43:36 +0200