当前位置:网站首页>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)
边栏推荐
- Comp2913 database
- 小程序-视图与逻辑
- Some points to pay attention to when closing mongodb services (as well as related commands when opening)
- Why is BeanUtils not recommended?
- 【opencv450 samples】创建图像列表yaml
- The Ping class of unity uses
- CDN加速是什么
- Glory launched the points mall to support the exchange of various glory products
- Oracle - getting started
- 【EOSIO】EOS/WAX签名错误 is_canonical( c ): signature is not canonical 问题
猜你喜欢
2. What is the geometric meaning of a vector multiplying its transpose?

作为一个程序员我们如何快乐的学习成长进步呢?(个人感悟和技术无关)

Live800在线客服系统:跨越时空做生意,从每次互动开始

LM小型可编程控制器软件(基于CoDeSys)笔记十七:pto脉冲功能块
![[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

How to use JMeter for interface testing

干货丨产品的可行性分析要从哪几个方面入手?
![[eosio] eos/wax signature error is_ Canonical (c): signature is not canonical](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[eosio] eos/wax signature error is_ Canonical (c): signature is not canonical

Use and difference between ue4\ue5 blueprint node delay and retroggable delay

RepOptimizer: 其实是RepVGG2
随机推荐
How to use JMeter for interface testing
【无标题】打开一个项目连接,无法正常显示时,ping一下ip
【opencv450-samples】读取图像路径列表并保持比例显示
Determine whether the appointment time has expired
Meta universe standard forum established
Baidu: in 2022, the top ten hot spots will rise and the profession will be released. There is no suspense about the first place!
22 years of a doctor in Huawei
zabbix_ Server configuration file details
Sword finger offer 46 Translate numbers to strings (DP)
The Ping class of unity uses
Pit resolution encountered using East OCR (compile LAMS)
Huawei cloud SRE deterministic operation and maintenance special issue (the first issue)
Leetcode(605)——种花问题
MySQL数据库常用函数和查询
Flex & Bison 开始
How to add cartoon characters to the blog park?
Fastjson反序列化随机性失败
Paper notes: multi tag learning MSWl
LM小型可编程控制器软件(基于CoDeSys)笔记十七:pto脉冲功能块
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