一、条件语句
1.1 if语句
if expression:
expr_true_suite
单个if语句中的expression条件表达式可以通过布尔操作符and,or和not实现多条件判断
【例 1】
if 2 > 1 and not 2 > 3:
print('Correct Judgement!') # Correct Judgement!
1.2 if-else语句
if expression:
expr_true_suite
else:
expr_false_suite
- 不同于其他语言,python中if和else各需要一个’:'
- if-else语句支持嵌套,即一个if中可以嵌套if-else,else中也可以嵌套一个if-else;
- if-else严格用缩进区分
【例 2】
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
注意:input接收外界输入,里面的文字信息是作为输入框提示用的,input接收到的数据temp均为str类型,int(temp)作为强制类型转换,将str类型的数值转换成int类型。
【例 3】
#例子3
hi = 6
if hi > 2:
if hi > 7:
print('好棒!好棒!')
else:
print('切~')
【例 4】
temp = input("不妨猜一下小哥哥现在心里想的是那个数字:")
guess = int(temp)
if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你这么懂小哥哥的心思吗?")
print("哼,猜对也没有奖励!")
else:
print("小了,小了")
print("游戏结束,不玩儿啦!")
1.3 if-elif-else语句:
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
【例 5】
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关键字
assert关键字,当后边的条件为False时,程序会抛出AssertionError异常;
在进行单元测试时,可以在程序中插入检查点,只有当条件为True的时候才通过。
【例 6】
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0 # AssertionError
二、循环语句
2.1 while循环
while 布尔表达式:
代码块
布尔表达式有以下几种情况:
- 带有
<、>、==、!=、in、not in
等逻辑运算符,为真,执行循环体; - 带有数值,
非零整数
,为真,执行循环体,写入0
时,视为假值,退出; - 写入
str、list
或任何序列,长度非零则视为真值,执行循环体;否则视为假值,退出。
【例 7】
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】
string = 'abcd'
while string:
print(string)
string = string[1:]
# abcd
# bcd
# cd
# d
2.2 while-else循环
while 布尔表达式:
代码块
else:
代码块
如果while
循环中执行了跳出循环的语句,比如 break
,将不执行else
代码块的内容。
【例 9】
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循环
for 迭代变量 in 可迭代对象:
代码块
for循环是迭代循环,在python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str,list,tuple,
等,也可以遍历任何可迭代对象,如dict
。
【例 10】
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
print(each)
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
for i in range(len(member)):
print(member[i])
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
【例 11】
dic = {'a':1,'b':2,'c':3,'d':4}
for key,value in dic.items():
print(key,value,sep=':',end=' ')
print('\n')
for key in dic.keys():
print(key,end=' ')
print('\n')
for value in dic.values():
print(value,end=' ')
# a:1 b:2 c:3 d:4
# a b c d
# 1 2 3 4
2.4 for-else循环
for 迭代变量 in 可迭代对象:
代码块
else:
代码块
当for
循环正常执行完的情况下,执行else
输出,如果for
循环中执行了跳出循环的语句,比如 break
,将不执行else
代码块的内容,与while - else
语句一样。
【例 12】
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 是一个质数
2.5 range()函数
range([start,] stop, [step=1])
-
step=1
表示第三个参数的间隔默认值是1; -
range
这个BIF的作用是生成一个从start
参数的值开始到stop
参数的值结束的数字序列,该序列包含start
的值但不包含stop
的值。
【例 13】
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
2.6 enumerate()函数
enumerate(sequence, [start=0])
将给定列表指定从start开始的索引,可与for一起使用
【例 13】
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.7 pass语句
pass
语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass
语句就是用来解决这些问题的。