当前位置:网站首页>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
Sequential structure : The code is executed from top to bottom , The statement is executed only once a day .( Default )
print('hello') print('word')
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 ')
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
Print according to the range of grades entered
pass
perhapsfail,
.score = float(input(' Please enter the score :')) if score >= 60: print(' pass ') else: print(' fail, ')
Print according to the entered age range
adult
perhapsA minor
, If the age is not within the normal range (0~150) PrintThis 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 !')
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 ')
Use for Cyclic output 0~100 All in 3 Multiple .
for i in range(0,101,3): print(i)
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)
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)
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)
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)
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
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)
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)
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
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()
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)
边栏推荐
- As a programmer, how can we learn, grow and progress happily? (personal perception has nothing to do with technology)
- 头歌 第3关:使用线程锁(Lock)实现线程同步
- 【AXI】解读AXI协议原子化访问
- How to download the software package of CDH version
- Live800 online customer service system: do business across time and space, starting from each interaction
- golang Make a list of intervals with sequential numbers
- The wisdom of questioning? How to ask questions?
- 关闭MongoDB一些服务需要注意的地方(以及开启的相关命令)
- Kubernetes cluster construction of multiple ECS
- Windows安装Redis及简单使用
猜你喜欢
问题记录与思考
String deformation (string case switching and realization)
Idea auto generator generates constructor get/set methods, etc
Network security project questions of the first Henan vocational skills competition in 2022
Fegin client entry test
[untitled] open an item connection. If it cannot be displayed normally, Ping the IP address
Why is the frame rate calculated by opencv wrong?
Live800 online customer service system: do business across time and space, starting from each interaction
元宇宙标准论坛成立
Several optimization scenarios using like fuzzy retrieval in SQL
随机推荐
剑指 Offer 46. 把数字翻译成字符串(DP)
UE4\UE5 蓝图节点Delay与Retriggerable Delay的使用与区别
[opencv450 samples] create image list yaml
软件测试面试一直挂,面试官总是说逻辑思维混乱,怎么办?
LM小型可编程控制器软件(基于CoDeSys)笔记十七:pto脉冲功能块
ACM. HJ16 购物单 ●●
How to add cartoon characters to the blog park?
Set up your own website (15)
Unity technical manual - life cycle rotation rotationoverlifetime- speed rotation rotationbyspeed- and external forces
Es7/es9 -- new features and regularities
Ue4 Ue5 combine le plug - in de reconnaissance vocale de bureau pour la reconnaissance vocale
Why is BeanUtils not recommended?
元宇宙标准论坛成立
Xampp重启后,MySQL服务就启动不了。
字符串变形(字符串大小写切换和变现)
Technology blog site collection
Jupiter notebook common shortcut keys
干货丨产品的可行性分析要从哪几个方面入手?
golang Make a list of intervals with sequential numbers
pdm的皮毛