条件语句
1. 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 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('输入错误!')
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("游戏结束,不玩儿啦!")
【例子】布尔表达式返回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: