Skip to content

Commit dc20417

Browse files
committed
python学习资料
1 parent 465c529 commit dc20417

17 files changed

+7197
-0
lines changed

Python Language/01. 变量、运算符与数据类型.md

Lines changed: 562 additions & 0 deletions
Large diffs are not rendered by default.

Python Language/02. 条件语句.md

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# 条件语句
2+
3+
## 1. if 语句
4+
5+
```python
6+
if expression:
7+
expr_true_suite
8+
```
9+
- if 语句的 `expr_true_suite` 代码块只有当条件表达式 `expression` 结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。
10+
- 单个 if 语句中的 `expression` 条件表达式可以通过布尔操作符 `and``or``not` 实现多重条件判断。
11+
12+
```python
13+
if 2 > 1 and not 2 > 3:
14+
print('Correct Judgement!')
15+
16+
# Correct Judgement!
17+
```
18+
19+
20+
21+
## 2. if - else 语句
22+
23+
24+
```python
25+
if expression:
26+
expr_true_suite
27+
else
28+
expr_false_suite
29+
```
30+
- Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。
31+
32+
【例子】
33+
```python
34+
temp = input("猜一猜小姐姐想的是哪个数字?")
35+
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
36+
if guess == 666:
37+
print("你太了解小姐姐的心思了!")
38+
print("哼,猜对也没有奖励!")
39+
else:
40+
print("猜错了,小姐姐现在心里想的是666!")
41+
print("游戏结束,不玩儿啦!")
42+
```
43+
44+
45+
46+
47+
`if`语句支持嵌套,即在一个`if`语句中嵌入另一个`if`语句,从而构成不同层次的选择结构。Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意`else`的悬挂问题。
48+
49+
【例子】
50+
```python
51+
hi = 6
52+
if hi > 2:
53+
if hi > 7:
54+
print('好棒!好棒!')
55+
else:
56+
print('切~')
57+
```
58+
59+
60+
【例子】
61+
```python
62+
temp = input("不妨猜一下小哥哥现在心里想的是那个数字:")
63+
guess = int(temp)
64+
if guess > 8:
65+
print("大了,大了")
66+
else:
67+
if guess == 8:
68+
print("你这么懂小哥哥的心思吗?")
69+
print("哼,猜对也没有奖励!")
70+
else:
71+
print("小了,小了")
72+
print("游戏结束,不玩儿啦!")
73+
```
74+
75+
76+
77+
78+
79+
80+
## 3. if - elif - else 语句
81+
82+
```python
83+
if expression1:
84+
expr1_true_suite
85+
elif expression2:
86+
expr2_true_suite
87+
.
88+
.
89+
elif expressionN:
90+
exprN_true_suite
91+
else:
92+
expr_false_suite
93+
```
94+
95+
- elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
96+
97+
【例子】
98+
99+
```python
100+
temp = input('请输入成绩:')
101+
source = int(temp)
102+
if 100 >= source >= 90:
103+
print('A')
104+
elif 90 > source >= 80:
105+
print('B')
106+
elif 80 > source >= 60:
107+
print('C')
108+
elif 60 > source >= 0:
109+
print('D')
110+
else:
111+
print('输入错误!')
112+
```
113+
114+
## 4. assert 关键词
115+
116+
- `assert`这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出`AssertionError`的异常。
117+
118+
【例子】
119+
120+
```python
121+
my_list = ['lsgogroup']
122+
my_list.pop(0)
123+
assert len(my_list) > 0
124+
125+
# AssertionError
126+
```
127+
128+
- 在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
129+
130+
【例子】
131+
```python
132+
assert 3 > 7
133+
134+
# AssertionError
135+
```
136+
137+
---
138+
**练习题**
139+

0 commit comments

Comments
 (0)