Control structure of procedure (fourth week) 21.7.25

Exercises

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"
else:
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())
seed(123)
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)
print("{:.6f}".format(pi))

'''
1-2+3-4...966‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬
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
else:
s -=i
print(s)

Three daffodils

'''
Description:
"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.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬
'''

s=''
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:
s=s+str(i)+','
print(s[:-1])

'''
describe:
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':
break
else:
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 _____:
print(var)

A,(1,2,3)

B,range(0,10)

C,{1;2;3;4;5}

D,"Hello"

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):
print(i)

A,1 2

B,1

C,0 1 2

D,0 1

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

k = 10000
while k>1:
print(k)
k=k/2

A,1000

B,15

C,14

D,13

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

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

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:
break

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

C,P=0

D. Absolute value of P

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

Indents represent hierarchical relationships.

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

for s in "PYTHON":
if s=='T':
continue
print(s,end="")

A,PYHON

B,TT

C,PY

D,PYTHON

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? ‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬

A,randint()

B,random()

C,randrange()

D,getrandbits()

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

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

'''
describe‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬:
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),4) + pow(eval(t),4) + pow(eval(t),4) + pow(eval(t),4) == i :
print(i)

Sum of prime numbers within 100

'''
describe
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
break
if not flag :
s+=i
print(s)

Study notes

1. Branch structure of program

1.2 if else

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

1.4 condition judgment

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

Reserved words: and, or, not

1.5 program exception handling

try—except—else—finally

#1
try:
<Statement block 1>
except <Exception type>:
<Statement block 2>
#-------------------------------------------------------
#2
try:
<Statement block 1>
except:
<Statement block 2>
else:
<Statement block 3>	# Execute when no exception occurs
finally:
<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

# CalBMIv3.py   # blend
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'
else:
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>

'''
Application:
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>
else:
<Statement block 2>

# -----------------------------------
while <condition>:
<Statement block 1>
else:
<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

functiondescribe
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

functiondescribe
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

# CalPiv1.py    # PI formula method

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

#------------------------------------------------------

# CalPiv2.py    # 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))

Source:
Python language programming_ Beijing University of Technology_ China University MOOC (MOOC) https://www.icourse163.org/course/BIT-268001

Keywords: Python

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