条件语句和循环语句
python学习第二课
条件语句
- if 语句
if 2 > 1 and not 2 > 3: # if后为条件,可借布尔操作符 and,or和not 实现多重条件判断
print('Correct Judgement!') # 语句体,语句数目至少得为1个,可以使用pass语句
-
if - else 语句
二选一执行
例1
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")
例2 - if 语句嵌套:缩进
可通过逻辑运算符简化嵌套
hi = 1 #3-7无返回值
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("游戏结束,不玩儿啦!")
- if - elif - else 语句
超过两个可能的情况,链式条件;
elif 是“else if”的缩写。同样地,第一个为真的分支会被执行。
elif 语句的数目没有限制,如果有 else 从句必须是在最后。
例子
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('输入错误!')
- assert 关键词
assert“断言”,当后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
my_list = ['lsgogroup']
my_list.pop(0) # pop() 函数用于移除列表中的一个元素
assert len(my_list) > 0
循环语句
- while 循环
while循环的代码块会一直循环执行,直到布尔表达式的值为False。
布尔表达式可不带有<、>、==、!=、in、not in等运算符,仅仅给出数值之类的条件。
当while后写入一个非零整数时,视为真值,执行循环体;写入0时,视为假值,不执行循环体。也可以写入str、list或任何序列,长度非零则视为真值,执行循环体;否则视为假值,不执行循环体。
例1
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("游戏结束,不玩儿啦!")
string = 'abcd' # while str
while string:
print(string)
string = string[1:]
- while - else 循环*
当while循环正常执行完的情况下,执行else输出
如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。
例1
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
例2
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
- for 循环
for循环是迭代循环,在Python中相当于一个通用的序列迭代器,可以遍历任何有序序列,如str、list、tuple等,也可以遍历任何可迭代对象,如dict。
例1
for i in 'ILoveLSGO':
print(i, end=' ') # 不换行输出
# I L o v e L S G O
例2
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
print(each)
for i in range(len(member)): # 结果一致
print(member[i])
例3
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
- for - 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 是一个质数
- range() 函数
range([start,] stop[, step=1])
这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。
step=1 表示第三个参数的默认值是1。
range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。
例1
for i in range(2, 9): # 不包含9
print(i)
# 2
# 3
# 4
# 5
# 6
# 7
# 8
例2
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
- enumerate() 函数
enumerate(sequence, [start=0])
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
sequence – 一个序列、迭代器或其他支持迭代对象。
start – 下标起始位置。
返回 enumerate(枚举) 对象
例1
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')]
例2 for循环和enumerate
i = 0
seq = ['one', 'two', 'three']
for element in seq:
print (i, seq[i])
i +=1
# 0 one
# 1 two
# 2 three
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!
- break语句
跳出当前所在层的循环
例1
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("游戏结束,不玩儿啦!")
- continue语句
continue终止本轮循环并开始下一轮循环。
例1
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
- pass 语句
pass是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。
如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个pass语句,让代码可以正常运行。 - 推导式
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)]
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)]
- 10.2 元组推导式
( expr for value in collection [if condition] )
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)
- 10.3 字典推导式
{ key_expr: value_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.4 集合推导式
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.5 其他
d = 'i for i in "I Love Lsgogroup"'
print(d)
# i for i in "I Love Lsgogroup"
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
- 综合
passwdList = ['123', '345', '890']
valid = False
count = 3
while count > 0:
password = input('enter password:')
for item in passwdList:
if password == item:
valid = True
break
if not valid:
print('invalid input')
count -= 1
continue
else:
break
练习
练习1 编写一个Python程序来查找那些既可以被7整除又可以被5整除的数字,介于1500和2700之间。
x = [i for i in range(1500,2700) if (i % 7) == 0 and (i % 5) == 0]
print(x)
[1505, 1540, 1575, 1610, 1645, 1680, 1715, 1750, 1785, 1820, 1855, 1890, 1925, 1960, 1995, 2030, 2065, 2100, 2135, 2170, 2205, 2240, 2275, 2310, 2345, 2380, 2415, 2450, 2485, 2520, 2555, 2590, 2625, 2660, 2695]
练习2 龟兔赛跑游戏 - 待补(不会)
学习资料
https://github.com/datawhalechina/team-learning-program/blob/master/Python-Language/03.%20条件语句.md
https://codingpy.com/books/thinkpython2/05-conditionals-and-recursion.html
https://www.runoob.com/python/att-list-pop.html
https://www.runoob.com/python/python-func-enumerate.html