1 Conditional statement
1.1 if statement
if expression:
expr_true_suite
- if the statement
expr_true_suite
block of code only if the conditional expressionexpression
is true if implemented, otherwise we will continue to execute the statement immediately behind the code block. - Single statement if
expression
the conditional expression by Boolean operatorsand
,or
andnot
to achieve multiple conditional.
【example】
if 2 > 1 and not 2 > 3:
print('Correct Judgement!')
# Correct Judgement!
1.2 if-else statement
if expression:
expr_true_suite
else
expr_false_suite
- Python provides the else used with if, if the result of the conditional expression of the if statement is false, the program will execute the code after the else statement.
【example】
temp = input("猜一猜小仙女想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小仙女的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小仙女现在心里想的是666!")
print("游戏结束,不玩儿啦!")
if
Sentences support nesting, which means that one if
sentence is embedded in another if
sentence to form a different level of selection structure. Python uses indentation instead of curly braces to mark code block boundaries, so pay special attention to else
the hanging problem.
【example】
hi = 6
if hi > 2:
if hi > 7:
print('好棒!好棒!')
else:
print('切~')
1.3 if-elif-else statement
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
- The elif statement is the else if, used to check whether multiple expressions are true, and execute the code in a specific code block when it is true.
【example】
temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
print('A')
elif 90 > source >= 80:
print('B')
elif 80 > source >= 60:
print('C')
elif 60 > source >= 0:
print('D')
else:
print('输入错误!')
1.4 assert keyword
assert
Used to judge an expression and triggerAssertionError
an exception when the expression condition is false .
Assertions can directly return an error when the conditions are not met and the program runs without waiting for the program to crash after running. For example, our code can only run under the Linux system. You can first determine whether the current system meets the conditions.
【example】
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
- During unit testing, it can be used to place checkpoints in the program. Only the condition is True can the program work normally.
【example】
assert 3 > 7
# AssertionError
2 Loop statement
2.1 while loop
while
The most basic form of a statement includes a Boolean expression at the top, and one or more while
indented statements that belong to the code block.
while 布尔表达式:
代码块
while
The looped code block will continue to loop until the value of the Boolean expression is Boolean false.
If the Boolean expression does not have an <、>、==、!=、in、not in
equal operator, it is also possible to give only conditions such as values. When while
a non-zero integer is written later, it is regarded as a true value and the loop body is executed; 0
when written , it is regarded as a false value and the loop body is not executed. You can also write str、list
or any sequence. A non-zero length is regarded as a true value and the loop body is executed; otherwise, it is regarded as a false value and the loop body is not executed.
【example】
count = 0
while count < 3:
temp = input("不妨猜一下小哥哥现在心里想的是那个数字:")
guess = int(temp)
if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你是小哥哥心里的蛔虫吗?")
print("哼,猜对也没有奖励!")
count = 3
else:
print("小了,小了")
count = count + 1
print("游戏结束,不玩儿啦!")
[Example] The Boolean expression returns 0 and the loop terminates.
string = 'abcd'
while string:
print(string)
string = string[1:]
# abcd
# bcd
# cd
# d
2.2 while-else loop
while 布尔表达式:
代码块
else:
代码块
When the while
loop is executed normally, the else
output while
is executed . If the statement that jumps out of the loop is executed in the loop, for example break
, else
the content of the code block will not be executed .
【example】
count = 0
while count < 5:
print("%d is less than 5" % count)
count = count + 1
else:
print("%d is not less than 5" % count)
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
# 5 is not less than 5
【example】
count = 0
while count < 5:
print("%d is less than 5" % count)
count = 6
break
else:
print("%d is not less than 5" % count)
# 0 is less than 5
2.3 for loop
for
A loop is an iterative loop, which is equivalent to a general sequence iterator in Python, which can traverse any ordered sequence, such str、list、tuple
as, etc., and can also traverse any iterable object, such as dict
.
for 迭代变量 in 可迭代对象:
代码块
In each loop, the iteration variable is set to the current element of the iterable object and provided to the code block.
【example】
for i in 'ILoveMAOMAO':
print(i, end=' ') # 不换行输出
# I L o v e M A O M A O
【example】
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for i in range(len(member)):
print(member[i])
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
【example】
dic = {
'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in dic.items():
print(key, value, sep=':', end=' ')
# a:1 b:2 c:3 d:4
2.4 for-else loop
for 迭代变量 in 可迭代对象:
代码块
else:
代码块
When the for
loop is executed normally, the else
output for
is executed . If the statement that jumps out of the loop is executed in the loop, for example break
, else
the content of the code block will not be executed , while - else
just like the statement.
【example】
for num in range(10, 20): # 迭代 10 到 20 之间的数字
for i in range(2, num): # 根据因子迭代
if num % i == 0: # 确定第一个因子
j = num / i # 计算第二个因子
print('%d 等于 %d * %d' % (num, i, j))
break # 跳出当前循环
else: # 循环的 else 部分
print(num, '是一个质数')
# 10 等于 2 * 5
# 11 是一个质数
# 12 等于 2 * 6
# 13 是一个质数
# 14 等于 2 * 7
# 15 等于 3 * 5
# 16 等于 2 * 8
# 17 是一个质数
# 18 等于 2 * 9
# 19 是一个质数
break
The statement can jump out of the loop of the current layer.
continue
Terminate this cycle and start the next cycle.
pass
It is an empty statement, does not do any operation, only serves as a placeholder, and its role is to maintain the integrity of the program structure.
3 Iterator
3.1 range() function
range([start,] stop[, step=1])
- This BIF (Built-in functions) has three parameters, two of which are enclosed in square brackets indicate that these two parameters are optional.
step=1
Indicates that the default value of the third parameter is 1.range
The function of this BIF is to generate a sequence of numbersstart
starting with the value of thestop
parameter and ending with the value of the parameter. The sequence containsstart
values but does not containstop
values.
【example】
for i in range(2, 5): # 不包含9
print(i)
# 2
# 3
# 4
3.2 enumerate() function
enumerate(sequence, [start=0])
- sequence-A sequence, iterator, or other object that supports iteration.
- start-the starting position of the subscript.
- Return enumerate (enumeration) object
[example]
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1)) # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
enumerate()
Combined use with for loop
for i, a in enumerate(A)
do something with a
With enumerate(A)
only returns A
the element, the element is also a point to an index value (from zero by default). In addition, with enumerate(A, j)
can also determine the starting value of the index j
.
【example】
languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
print('I love', language)
print('Done!')
'''
I love Python
I love R
I love Matlab
I love C++
Done!
'''
4 Derivative
4.1 List comprehension
[ expr for value in collection [if condition] ]
【example】
x = [i ** 2 for i in range(1, 10)]
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
【example】
x = [(i, i ** 2) for i in range(6)]
print(x)
# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
【example】
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)
# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]
4.2 Tuple comprehension
( expr for value in collection [if condition] )
【example】
a = (x for x in range(10))
print(a)
# <generator object <genexpr> at 0x0000025BE511CC48>
print(tuple(a))
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
4.3 Dictionary comprehension
{
key_expr: value_expr for value in collection [if condition] }
【example】
b = {
i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
4.4 Set comprehension
{ expr for value in collection [if condition] }
【example】
c = {
i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}
Practice questions :
1. Write a Python program to find numbers that are divisible by 7 and 5, between 1500 and 2700.
# your code here
[i for i in range(1500,2700,1) if i%7 == 0 and i%5 == 0]
2. The tortoise and the tortoise game
Title description:
Say there are all kinds of rabbits and tortoises in this world, but research has found that all rabbits and tortoises have a common characteristic-they like to race. As a result, tortoise and hare races are constantly taking place in all corners of the world. Xiaohua is very interested in this, so he decides to study the races between different hares and tortoises. He found that although rabbits run faster than tortoises, they have a well-known problem-proud and lazy. So in a game with tortoises, once the rabbits find themselves ahead of t meters or more after any second, they will stop. Rest for s seconds. For different rabbits, the values of t and s are different, but all tortoises are the same-they never stop when they reach the end.
However, some games are quite long and the whole viewing process will take a lot of time. Xiaohua found that as long as the data of the rabbit and the tortoise are recorded after each game starts-the rabbit's speed v1 (which means that the rabbit can run v1 meters per second), the tortoise's The speed v2, and the corresponding t and s values of the rabbit, and the length of the track l-can predict the outcome of the race. But Xiaohua is lazy and doesn’t want to use manual calculations to infer the results of the game, so he found you-a talented student from the Department of Computer Science of Tsinghua University-for help. Please write a program. For the input data v1 of a game, v2, t, s, l, predict the outcome of the game.
Input:
There is only one line of input, including five positive integers v1, v2, t, s, l separated by spaces, where (v1, v2<=100;t<=300;s<=10;l<=10000 and It is the common multiple of v1, v2)
Output: The
output contains two lines, the first line outputs the result of the game-a capital letter "T" or "R" or "D", respectively, indicating that the tortoise wins, the rabbit wins, or both arrive at the same time end.
The second line outputs a positive integer, indicating the time (in seconds) it takes for the winner (or both sides) to reach the end point.
Sample input:
10 5 5 2 20
Sample output
D
4
# your code here
class Turtle_rabbit:
def run(self,inputs):
v1,v2,t,s,l = inputs
result = []
dist1,dist2 = 0, 0
i = 0
while dist1 < l and dist2 < l:
dist1 += v1
dist2 += v2
i +=1
if(dist1 == l or dist2 == l):
break
if(dist1 - dist2 >= t):
dist1 -= s*v1
if dist1 > dist2:
result.append("R")
elif dist1 < dist2:
result.append("T")
else:
result.append("D")
result.append(i)
return result
if __name__ == "__main__":
inputs = (10,5,5,2,20)
result = Turtle_rabbit()
for i,data in enumerate(result.run(inputs)):
print(data)
References :
- https://www.runoob.com/python3/python3-tutorial.html
- https://www.bilibili.com/video/av4050443
- https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ
DataWhale
Datawhale is an open source organization focusing on data science and AI. It brings together excellent learners from many universities and well-known companies in many fields, and brings together a group of team members with open source spirit and exploratory spirit. With the vision of "for the learner, grow with learners", Datawhale encourages true self-expression, openness and tolerance, mutual trust and mutual assistance, the courage to try and make mistakes, and the courage to take responsibility. At the same time, Datawhale uses the concept of open source to explore open source content, open source learning and open source solutions, empower talent training, help talent growth, and establish a connection between people and people, people and knowledge, people and enterprises, and people and the future.