系列文章目录
第一章: 运算符,变量, 数据类型
第二章: 位运算,print函数的使用介绍
第三章 :条件语句与循环语句
第四章:Python 异常处理
第五章:列表,元祖
第三章 条件语句与循环语句
本系列文章参考自: 天池龙珠计划- python训练营
文章目录
前言
程序设计的三大经典结构:顺序,选择,循环
本文介绍其中两大结构在python语言中的使用
只是看是学不会的,多动手跟着敲才会逐渐上手;
遇到问题,独立思考,分析问题,才能获得最大的收货。
条件语句
1. if 语句
# if语句基本结构:
if expression:
expr_true_suite
- if 语句的
expr_true_suite
代码块只有当条件表达式expression
结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。 - 单个 if 语句中的
expression
条件表达式可以通过布尔操作符and
,or
和not
实现多重条件判断。
【例子】
if 2 > 1 and not 2 > 3:
print('Correct Judgement!')
# Correct Judgement!
2. if - else 语句
# if-else语句基本结构
if expression:
expr_true_suite
else:
expr_false_suite
- Python 提供与 if 搭配使用的 else,如果 if 语句的条件表达式结果布尔值为假,那么程序将执行 else 语句后的代码。
【例子】
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
if
语句支持嵌套,即在一个if
语句中嵌入另一个if
语句,从而构成不同层次的选择结构。
【例子】Python 使用缩进而不是大括号来标记代码块边界,因此要特别注意else
的悬挂问题。
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("游戏结束,不玩儿啦!")
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,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。
【例子】
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
4. assert 关键词
assert
这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError
的异常。
【例子】
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
assert 3 > 7
# AssertionError
循环语句
1. while 循环
while
语句最基本的形式包括一个位于顶部的布尔表达式,一个或多个属于while
代码块的缩进语句。
while 布尔表达式:
代码块
while
循环的代码块会一直循环执行,直到布尔表达式的值为布尔假。
如果布尔表达式不带有<、>、==、!=、in、not in
等运算符,仅仅给出数值之类的条件,也是可以的。当while
后写入一个非零整数时,视为真值,执行循环体;写入0
时,视为假值,不执行循环体。也可以写入str、list
或任何序列,长度非零则视为真值,执行循环体;否则视为假值,不执行循环体。
【例子】
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
# 你太了解小姐姐的心思了!
# 哼,猜对也没有奖励!
# 游戏结束,不玩儿啦!
【例子】布尔表达式返回0,循环终止。
string = 'abcd'
while string:
print(string)
string = string[1:]
# abcd
# bcd
# cd
# d
2. while - else 循环
while 布尔表达式:
代码块
else:
代码块
当while
循环正常执行完的情况下,执行else
输出,如果while
循环中执行了跳出循环的语句,比如 break
,将不执行else
代码块的内容。
【例子】
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
【例子】
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
3. for 循环
for
循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str、list、tuple
等,也可以遍历任何可迭代对象,如dict
。
for 迭代变量 in 可迭代对象:
代码块
每次循环,迭代变量被设置为可迭代对象的当前元素,提供给代码块使用。
【例子】
for i in 'ILoveLSGO':
print(i, end=' ') # 不换行输出
# I L o v e L S G O
【例子】
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
print(each)
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
for i in range(len(member)):
print(member[i])
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
【例子】
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
【例子】
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key in dic.keys():
print(key, end=' ')
# a b c d
【例子】
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for value in dic.values():
print(value, end=' ')
# 1 2 3 4
4. for - else 循环
for 迭代变量 in 可迭代对象:
代码块
else:
代码块
当for
循环正常执行完的情况下,执行else
输出,如果for
循环中执行了跳出循环的语句,比如 break
,将不执行else
代码块的内容,与while - else
语句一样。
【例子】
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 是一个质数
5. range() 函数
range([start,] stop[, step=1])
- 这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。
step=1
表示第三个参数的默认值是1。range
这个BIF的作用是生成一个从start
参数的值开始到stop
参数的值结束的数字序列,该序列包含start
的值但不包含stop
的值。
【例子】
for i in range(2, 9): # 不包含9
print(i)
# 2
# 3
# 4
# 5
# 6
# 7
# 8
【例子】
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
6. enumerate()函数
enumerate(sequence, [start=0])
- sequence:一个序列、迭代器或其他支持迭代对象。
- start:下标起始位置。
- 返回 enumerate(枚举) 对象
【例子】
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()
与 for 循环的结合使用。
for i, a in enumerate(A)
do something with a
用 enumerate(A)
不仅返回了 A
中的元素,还顺便给该元素一个索引值 (默认从 0 开始)。此外,用 enumerate(A, j)
还可以确定索引起始值为 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!
7. break 语句
break
语句可以跳出当前所在层的循环。
【例子】
import random
secret = random.randint(1, 10) #[1,10]之间的随机数
while True:
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > secret:
print("大了,大了")
else:
if guess == secret:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
break
else:
print("小了,小了")
print("游戏结束,不玩儿啦!")
8. continue 语句
continue
终止本轮循环并开始下一轮循环。
【例子】
for i in range(10):
if i % 2 != 0:
print(i)
continue
i += 2
print(i)
# 2
# 1
# 4
# 3
# 6
# 5
# 8
# 7
# 10
# 9
9. pass 语句
pass
语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而 pass
语句就是用来解决这些问题的。
【例子】
# 定义一个什么都不做的函数,直接这么写会报语法错误
def a_func():
# SyntaxError: unexpected EOF while parsing
# 只要增加pass就可以啦
def a_func():
pass
pass
是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。尽管pass
语句不做任何操作,但如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个pass
语句,让代码可以正常运行。
10. 推导式
10.1 - 列表推导式
# 结构如下
[ expr for value in collection [if condition] ]
【例子】
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)]
【例子】
# 获得100以内奇数组成的数组
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]
【例子】
# 双重for循环
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]]
【例子】
# 双重for循环+条件判断
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)]
10.2 - 元组推导式
# 基本结构,相当于列表推导式的中括号改为圆括号
( expr for value in collection [if condition] )
【例子】
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
10.3 - 集合推导式
# 基本结构,相当于列表推导式的中括号改为花括号
{ expr for value in collection [if condition] }
【例子】
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}
10.4 - 其它
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.
翻译:
next(迭代器[, 默认值])
返回迭代器中的下一个元素。如果设置了默认值,那么当迭代器穷尽时返回该默认值;否则,抛出停止迭代(StopIteration)的异常。
【例子】
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
总结
以上就是今天要讲的内容,本文介绍了条件语句,循环语句的简单使用和推导式的使用,在代码中使用推导式可以大大简化代码,希望能对你有所收货。