当前位置:网站首页>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
passperhapsfail,.score = float(input(' Please enter the score :')) if score >= 60: print(' pass ') else: print(' fail, ')Print according to the entered age range
adultperhapsA 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 numbera = 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 ') breakOutput 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)
边栏推荐
- 剑指 Offer 46. 把数字翻译成字符串(DP)
- How to add cartoon characters to the blog park?
- 【AXI】解读AXI协议原子化访问
- Svn icon disappearing solution
- Actual combat: how to quickly change font color in typera (blog sharing - perfect) -2022.6.25 (solved)
- 一位博士在华为的22年
- 1281_FreeRTOS_vTaskDelayUntil实现分析
- 软件测试面试一直挂,面试官总是说逻辑思维混乱,怎么办?
- What is CDN acceleration
- 22 years of a doctor in Huawei
猜你喜欢

UE4\UE5 蓝图节点Delay与Retriggerable Delay的使用与区别
Why is BeanUtils not recommended?

【EOSIO】EOS/WAX签名错误 is_canonical( c ): signature is not canonical 问题

Meta universe standard forum established
[email protected]@COLLATION_ CONNECTION */"/>. SQL database import error: / *! 40101 SET @OLD_ COLLATION_ [email protected]@COLLATION_ CONNECTION */

Circuit module analysis exercise 5 (power supply)

建立自己的网站(15)
![[untitled] open an item connection. If it cannot be displayed normally, Ping the IP address](/img/34/d3c146d5faa2728cb5eb8f3ee00200.png)
[untitled] open an item connection. If it cannot be displayed normally, Ping the IP address

Kubernetes cluster construction of multiple ECS

【无标题】打开一个项目连接,无法正常显示时,ping一下ip
随机推荐
Multithreaded learning 1
Pycharm student's qualification expires, prompting no suitable licenses associated with account solution
UE4_UE5结合offline voice recognition插件做语音识别功能
元宇宙标准论坛成立
The new version of Tencent's "peace elite" is coming: add a new account security protection system, and upgrade the detection of in-game violations
OBS-Studio-27.2.4-Full-Installer-x64.exe 下载
Flex & Bison Start
最近准备翻译外国优质文章
leetcode_ 136_ A number that appears only once
Implementation of importing vscode from PDM
UE4\UE5 蓝图节点Delay与Retriggerable Delay的使用与区别
Determine whether the appointment time has expired
The sum of logarithms in group 52--e of Niuke Xiaobai monthly race (two points)
Unity technical manual - life cycle rotation rotationoverlifetime- speed rotation rotationbyspeed- and external forces
ES6学习-- LET
Why is BeanUtils not recommended?
Multi modal data can also be Mae? Berkeley & Google proposed m3ae to conduct Mae on image and text data! The optimal masking rate can reach 75%, significantly higher than 15% of Bert
The Ping class of unity uses
[2023 proofreading and bidding questions] Part 1: Measurement Technology FPGA post (roughly analytical version)
. SQL database import error: / *! 40101 SET @OLD_ COLLATION_ [email protected]@COLLATION_ CONNECTION */