DataWhale7月学习——Python入门
Task2: 条件循环结构
本节将学习Python的条件语句和循环结构。文章给出了一些重点知识的.py程序便于读者深入理解。本文的程序编写基于Python3.0+,安装环境使用的是PyCharm。
if条件语句
本小节我们将从以下几个基本的if语句学习条件结构
- if语句的表达形式
- if-esle语句
- if-elif-esle语句
- assert关键词
if语句的表达形式
和C语言中的定义一样,Python中的if语句由一个可用于判断的条件表达式和执行句构成。条件表达式跟在if后面,以冒号结束换行,当其值为真正时,才执行下面的执行句,否则不执行。条件表达式可以通过布尔操作符,如: and、or和not实现多重条件判断
if 2 > 1 and not 2 > 3:
print('Correct Judgement!')
# Correct Judgement!
if-else语句
if-else结构实现了针对不同结构对应执行相应的语句,当if后面的条件表达式为真时,执行下面的执行句,否则执行else下面的执行句
temp = input("猜⼀猜⼩姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
print("你太了解⼩姐姐的⼼思了!")
print("哼,猜对也没有奖励!")
else:
print("猜错了,⼩姐姐现在⼼⾥想的是666!")
print("游戏结束,不玩⼉啦!")
另外,if语句支持嵌套结构,即在一个if句中嵌入另一个if句构成更为复杂的选择结构。值得注意的是Python中是通过缩进区分代码的边界,因此在使用if-else语句时候注意根据缩进方式判断if-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("游戏结束,不玩⼉啦!")
if-elif-else语句
elif语句即为else-if,与第一个if属于并列关系(所以代码不可缩进),用来检查多个表达式是否为真,并在真时执行特定代码块的代码
结构为:
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
一些成绩判断的问题通常用到这种结构,如:
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时,程序自动崩溃并抛出Assertion Error的异常。在进行单元测试时,可以用来在程序中置入检查点,只有条件为真时才让程序正常工作
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
循环语句
本小节中我们将学习几个重要的循环体结构:while循环、for循环,并了解一些函数的使用规则,如: range()函数、enumerate()函数,以及用于跳出循环题的break语句、continue语句、pass语句,我们同样给出了一些例子方便大家理解
while循环
while循环结构简单来讲由一个布尔表达式和循环的代码块构成,while循环的代码块会一直进行下去直到布尔表达式地值为假。这里的布尔表达式可以是带有<、>、==、!=、in、not in的运算符,也可以是一个整数(while视0为假,非零整数为真);当布尔表达式是一个str、list或任何序列,若其长度非零则视为真值,否则实为假
string = 'abcd'
while string:
print(string)
string = string[1:]
# abcd
# bcd
# cd
# d
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("游戏结束,不玩⼉啦!")
while-else 循环
while-else的结构形式虽然和if-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
for 循环
for循环是用来在可迭代对象中循环迭代变量,且在每次迭代时执行迭代代码块的循环体。for循环可以遍历任何有序序列,如str、list、tuple,也可以遍历任何可迭代对象,如dict
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
for-else 循环体
for-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参数的值开始,以step为间隔,到stop参数的值结束的数字序列(包含start不包含stop的值),形式是range(start,stop,step),当step不写明的时候,通常默认为step=1
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
enumerate函数
enumerate函数的用法是:enumerate(sequence,start),当start省略时,默认start=0(从第一个位置开始,Python中默认第一个位置从0开始)。值得注意的是,enumerate(A)不仅返回了A中的元素,还顺便给了该元素的一个索引值。次外,利用enumerate(A,j)还可以确定索引起始值为j
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循环使用,如下例:
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!
'''
break函数和continue函数
break用于跳出当前循环体;cotinue用于结束本轮循环重新开始下轮循环
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("游戏结束,不玩⼉啦!")
for i in range(10): # 主义这里是 i=0,1,2,...,9
if i % 2 != 0:
print(i)
continue
i += 2
print(i)
# 2
# 1
# 4
# 3
# 6
# 5
# 8
# 7
# 10
# 9
pass语句
pass是空语句,只起到占位的作用,起作用是保持程序结构的完整,如果暂时不知道该放什么代码块,可以先放置一个pass语句让代码可以正常语句
def a_func():
# SyntaxError: unexpected EOF while parsing
def a_func():
pass
练习题
1.编写一个python程序来查找那些可以被7除以5的整数数字,介于1500-2700之间:
T= 1500
for i in range(1500, 2700):
if i % 7 == 0 and i % 5 ==0:
print(i)
T+=1
2.龟兔赛跑预测问题
v1,v2,t,s,l = map(int,input().split())
if v1<=100 and v2<=100 and t<=300 and s<=10 and l<=10000 and l%v1==0 and l%v2==0:
s1,s2,i = 0,0,0
while s1<l and s2<l:
s1,s2,i=v1+s1,v2+s2,i+1
if s1==l or s2==l:
break
elif s1-s2>=t:
s2,i=s2+v2*s,i+s
if s1>s2:print('R')
if s1==s2:print('D')
if s1<s2:print('T')
print(i)
原文链接:https://blog.csdn.net/weixin_45829462/article/details/103882743