python training camp D2
1 Conditional statement
1.1 if statement
if expression:
expr_true_suite
if
Statementexpr_true_suite
block of code only when the conditional expressionexpression
result is true if implemented, otherwise we will continue to execute the statement immediately behind the code block.- A single
if
statement ofexpression
the conditional expression by Boolean operatorsand
,or
andnot
to achieve multiple conditional .
if 2 > 1 and not 2 > 3:
print('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.
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
猜一猜小姐姐想的是哪个数字?666
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!
if
Sentences support nesting, which means that one if
sentence is embedded in another if
sentence to form a different level of selection structure.
[Example] Python uses indentation instead of curly braces to mark code block boundaries, so pay special attention to else
the suspension problem.
hi = 6
if hi > 2:
if hi > 7:
print('好棒!好棒!')
else:
print('切~')
# 无输出
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("小了,小了")
print("游戏结束,不玩儿啦!")
猜一猜小姐姐想的是哪个数字?8
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!
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.
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('输入错误!')
请输入成绩:99
A
1.4 assert keyword
assert
We call this keyword " assertion ". When the condition behind this keyword is False, the program automatically crashes and throwsAssertionError
an exception.
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
During unit testing, it can be used to put checkpoints in the program . Only the condition is True can the program work normally.
assert 3 > 7
# AssertionError
2 Loop statement
2.1 while loop
`while`语句最基本的形式包括一个位于顶部的布尔表达式,一个或多个属于`while`代码块的缩进语句。
```python
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.
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("游戏结束,不玩儿啦!")
猜一猜小姐姐想的是哪个数字?8
你太了解小姐姐的心思了!
哼,猜对也没有奖励!
游戏结束,不玩儿啦!
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
, the content of the code block will not be executed else
.
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.
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
Same as while-else loop
2.5 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
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()
Used in conjunction with for loops.
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
.
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!
for i, language in enumerate(languages, 2):
print(i, 'I love', language)
print('Done!')
# 2 I love Python
# 3 I love R
# 4 I love Matlab
# 5 I love C++
# Done!
2.6. Deduction
List comprehension
[ expr for value in collection [if condition] ]
【example】
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)
# [-8, -4, 0, 4, 8]
x = [i ** 2 for i in range(1, 10)]
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
x = [(i, i ** 2) for i in range(6)]
print(x)
# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
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]
a = [(i, j) for i in range(0, 3) for j in range(0, 3)]
print(a)
# [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
x = [[i, j] for i in range(0, 3) for j in range(0, 3)]
print(x)
# [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
x[0][0] = 10
print(x)
# [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)
# [(0, 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)
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}
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}
other
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
【example】
e = (i for i in range(10))
print(e)
# <generator object <genexpr> at 0x0000007A0B8D01B0>
print(next(e)) # 0
print(next(e)) # 1
for each in e:
print(each, end=' ')
# 2 3 4 5 6 7 8 9
s = sum([i for i in range(101)])
print(s) # 5050
s = sum((i for i in range(101)))
print(s) # 5050