目录: 0x00 - Python学习笔记
选择
if
- 只有一次判断的
if
:
if score > 50:
print("You are so cool!")
else:
printf("I don't want to say anything...")
- 多次判断(一般不如此使用):
if score >= 80:
print("You are so good!")
else:
if 80 > score >= 50:
print("You are not bad!")
else:
print("...")
- 多次判断的简洁用法:
if score >= 80:
print("You are the best!")
elif 80 > score >= 50:
print("You are cool!")
elif 50 > score >= 20:
print("haha")
else:
print("a,zhe...")
悬挂else:在 Python 中不存在 悬挂else 的问题,因为他强制编译出简洁可读的代码,要求严格的缩进,所以在 Python 中,else 与那个 if 相对一目了然
断言(assert)
assert 称为“断言”,当他后的条件为假的时候,程序会自动崩溃,并抛出AssertionError异常。
一般用于在程序中设置检查点,可在之后的程序中设置捕获异常的方法
assert 1 > 2
三元操作符
在 Python 中也有一种三元操作符:
如果有以下的程序:
if x < y:
small = x
else:
small = y
它可以直接使用三元操作符完成:
small = x if x < y else y
他的意思是,如果x<y
则将x
赋给small
,否则将y
赋给small
循环
while
while i < 10:
print("i < 10")
i++
for
Python 中的 for 循环比 C 语言的更加强大,他的语法如下:
for 目标 in 表达式:
循环体
- 打印字符串中的每一个字符:
csdnName = '1ta_chi'
for i in csdnName:
print(i, end=' ')
# 输出:
# 1 t a _ c h i
- 打印字符数组中的每一个元素
csdn = ['Python','C','C++','Java']
for word in csdn:
print(word, len(word))
# 打印每一个字符串及其长度
# Python 6
# C 1
# C++ 3
# Java 4
range()
range( [start,] stop [,step = 1] )
它含有两个可选参数和一个必选参数(第三个默认为1)
它的作用是生成一个从start
参数的值开始到stop
参数的值结束的数字序列
step
的意思是 步径 ,就是 间隔
list(range(5)) /# 默认从 0 开始
# 输出
# [0, 1, 2, 3, 4]
range() 最常与 for循环 连用
for i in range(1, 10, 2):
print(i)
# 输出
# 1
# 3
# 5
# 7
# 9
break与continue
这两个关键词的用法与 C 语言相同,这里简单介绍一下
break:直接结束循环
continue:结束其后的语句,再去判断循环条件是否为 True
,判断是否执行下一步