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(