- 结构语句
- for range 循环
- 条件语句(If…else)
- While循环
- 循环的进阶应用
- 课后作业(3必做)
1、结构语句 1.sequence 2.condition(if) 3.loop友情提示:将下文中代码拷贝到JupyterNotebook中直接执行即可,部分代码需要连续执行。
1.1 Sequence
Sequence是Python的一种内置类型(built-in type),内置类型就是构建在Python Interpreter里面的类型,三种基本的Sequence Type是list(数组),tuple(定值表,或称为元组),range(范围)。可以看作是Python Interpreter定义了这样三个class。
1.2 for range 循环range() 函数可创建一个整数列表,一般用在 for 循环中。
range函数语法:1.range(stop): 0到stop 不包括stop
2.range(start,stop): start到stop 包括start不包括stop
3.range(start,stop,step): start到stop step(步长)
for i in range(5):则循环0-4
for i in range(5):
print(i)
0
1
2
3
4
for i in range(3,10):则循环3-9
for i in range(3,10):
print(i)
3
4
5
6
7
8
9
for i in range(1,10,3):则循环1-9,步长为3(间隔2个数)
for i in range(1,10,3):
print(i)
1
4
7
对数组长度进行循环,根据元素index遍历数组
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
for i in range(len(weekdays)):
print(weekdays[i])
Monday
Tuesday
Wednesday
Thursday
Friday
直接对数组进行循环,遍历数组
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
for day in weekdays:
print(day)
Monday
Tuesday
Wednesday
Thursday
Friday
1.2.1 for range循环填充数组
i for i in range(10) if i % 2 ==1 表示0-9循环,且满足除以2余数是1,即单数
[i for i in range(10) if i % 2 ==1]
[1, 3, 5, 7, 9]
挑战:用循环填充数组,实现公式: ( 3 − 1 ) 2 , ( 6 − 1 ) 2 , ( 9 − 1 ) 2 , ( 12 − 1 ) 2 , ( 15 − 1 ) 2 , . . . (3-1)^2,(6-1)^2,(9-1)^2,(12-1)^2,(15-1)^2,... (3−1)2,(6−1)2,(9−1)2,(12−1)2,(15−1)2,...
[i*i for i in range(1,40) if i % 3 == 2]
[4, 25, 64, 121, 196, 289, 400, 529, 676, 841, 1024, 1225, 1444]
1.2.2 for enumerate枚举
enumerate是Python的一个内置函数。它可以让我们在某物上循环,并有一个自动计数器。enumerate还接受一个可选参数,这使它更加有用。可选参数允许我们告诉enumerate从何处开始索引。
进阶提示:
enumerate 只允许返回两个循环变量值,一个是计数器值,一个是循环项目本来的值。
for key,day in enumerate(weekdays):
print(key," ",day)
0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
enumerate(month,3):表示计数器从3开始
month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
for c,value in enumerate(month,3):
print(c,value)
3 Jan
4 Feb
5 Mar
6 Apr
7 May
8 Jun
9 Jul
10 Aug
11 Sep
12 Oct
13 Nov
14 Dec
enumerate 只允许返回两个循环变量值,一个是计数器值,一个是循环项目本来的值。
所以循环项目有两个值(key,value)则需要用()括起来
dict = {"Monday":"星期一","Tuesday":"星期二","Wednesday":"星期三","Thursday":"星期四","Friday":"星期五"}
for index,(key,value) in enumerate (dict.items()):
print("index = {},key = {},value = {}".format(index,key,value))
index = 0,key = Monday,value = 星期一
index = 1,key = Tuesday,value = 星期二
index = 2,key = Wednesday,value = 星期三
index = 3,key = Thursday,value = 星期四
index = 4,key = Friday,value = 星期五
1.2.3 Separate numbers拆分
将一个列表分为两个列表,一个列表中的所有数字都低于目标值,另一个列表中的所有数字都大于或等于目标值
random.sample(range(0,10),8)的意思是从0-9中随机取8个值形成数组
import random
list0 = random.sample(range(0,10),8)
target = 4
print("list0={}\nlist1={}\nlist2={}".format(list0,[i for i in list0 if i < target],
[i for i in list0 if i >= target]))
list0=[4, 8, 3, 5, 6, 1, 2, 9]
list1=[3, 1, 2]
list2=[4, 8, 5, 6, 9]
1.2.3 for循环嵌套
rows = range(1,4)
cols = range(1,3)
cell =list()
for row in rows:
for col in cols:
cell.append((row,col))
cell
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]
1.3 条件语句Condition(If…else)
语法:
if (condition) {
当条件为 true 时执行的代码
}
else{
当条件不为 true 时执行的代码
}
当时间小于 20时,生成问候 “Good day”,否则生成问候 “Good evening”。
time = 17
if (time<20):
print("Good day")
else:
print("Good evening")
Good day
下雨指数possibility_to_rain
当x > 0.8,带伞
当0.3 < x < = 0.8,根据情况带伞
当x< =0.3,享受阳光
possibility_to_rain = 0.7
if possibility_to_rain > 0.8:
print("take u umbrella")
elif possibility_to_rain > 0.3:
print("take u umbrella just in case")
else:
print("enjoy the sunshine")
if 嵌套 if
nationality =input("请输入您的国籍(中国:外国) >>/n")
nation=input("请输入您的民族(汉族:少数民族) >>/n")
if nationality == "中国": # == 做判断返回True or False
if nation == "汉族":
print("您是汉族人")
else:
print("您是少数民族")
else:
print("您不是中国人")
请输入您的国籍(中国:外国) >>/n中国
请输入您的民族(汉族:少数民族) >>/n少数民族
您是少数民族
1.3.1 使用If…else条件语句时,需要注意使用Python缩进,缩进为4个空格或者1个Tab键
if
if
if
else
else
else
x = int(input("please enter an integer:"))
if x < 0:
x = 0
print("x is lower than zero")
elif x == 0:
print("x is zero")
else:
print("x is bigger than zero")
please enter an integer:6
x is bigger than zero
1.4 While循环
while 语法:
while condition:
statements_1
else:
statements_2
我们要输出10条“you are my sunshine ”可以表达如下:
count = 0
while count< 10:
print("you are my sunshine "),
count = count + 1
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
you are my sunshine
break用在while循环中用于跳出当前循环
counter =1
while True:
print("计数器 = %d"%counter)
ch = input("Do you want to continue? \n[y:n]:")
if ch =='y':
counter += 1
else:
break
计数器 = 1
Do you want to continue?
[y:n]:y
计数器 = 2
Do you want to continue?
[y:n]:y
计数器 = 3
Do you want to continue?
[y:n]:n
2、循环的进阶应用
2.1 List 数组应用
你也可以在数组中使用循环填充。
标准用法:
rows = range(1,3)
cols = range(1,4)
cells = []
for row in rows:
for col in cols:
cells.append((row,col))
cells
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
循环填充用法:
rows = range(1,3)
cols = range(1,4)
cells = [(row,col) for row in rows for col in cols]
cells
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
2.2 dict字典应用
类似于数组应用,您可以使用字典应用来生成新的字典。基本形式是:
{key_expression:value_expression for expression in iterable}\
例如:使用dict字典快速统计字符串中每个字符出现的次数:
set(dna)是将字符串转化为去重后的tuple,dna.count(a)是统计每个字符串出现的次数
dna = "ABABCCDCDAB"
dna_count = {a:dna.count(a) for a in set(dna)}
dna_count
{'C': 3, 'A': 3, 'B': 3, 'D': 2}
3、课后作业
1、做一个简单的猜数字游戏(0-30内), 随机生成一个数字,给5次机会猜中,猜大猜小均有提示,5次机会后,游戏宣布结束。
您的代码:
2、统计"I have a dream that one day this nation will rise up and live out the true meaning of its creed: We hold these truths to be self-evident, that all men are created equal." 每个英文字符出现的次数
您的代码:
3、打印9*9乘法表
您的代码:
4、02.Python零基础速成班-第3讲-Python基础(中),list数组、tuple元组、dict字典、set集合 课后作业及答案
1、已知两个升序列表A、B:A=[1,3,4,6,7] B=[1,2,3,4,5,6] 请判断列表A是否是列表B的子集,如果是则返回 True ,否则返回 False 。
a = [1,3,4,6,7]
b = [1,2,3,4,5,6]
a1=set(a)
b1=set(b)
if len(a1 - b1) > 0: #也可以用issubset()方法
print (False)
else:
print (True)
False
2、创建一个[“Monday”,“Tuesday”,“Wednesday”,“Thursday”,“Friday”]数组,用两种方法分别增加Saturday和Sunday并输出,再用三种方法分别删除Mon,Tue,Wed并输出,询问Monday是否还在数组中?
week = ["Monday","Tuesday","Wednesday","Thursday","Friday"]
week.append("Saturday")
week.insert(6,"Sunday")
print(week)
week.pop(0)
del week[0]
week.remove("Wednesday")
print(week)
"Monday" in week
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
['Thursday', 'Friday', 'Saturday', 'Sunday']
False
3、创建一个数组a=[11,2.71,True,3.1415,100,0.75,False],使其降序排列并输出。b数组浅拷贝a;c、d、e组数通过三种方式深拷贝a,修改a数组第一个数字"100"为"1000",然后分别输出数组abcde。
a =[11,2.71,True,3.1415,100,0.75,False]
a.sort(reverse=True)
print(a)
b = a
c = a.copy()
d = a[:]
e = list(a)
a[0]="1000"
print("a=",a,"\nb=",b,"\nc=",c,"\nd=",d,"\ne=",e)
[100, 11, 3.1415, 2.71, True, 0.75, False]
a= ['1000', 11, 3.1415, 2.71, True, 0.75, False]
b= ['1000', 11, 3.1415, 2.71, True, 0.75, False]
c= [100, 11, 3.1415, 2.71, True, 0.75, False]
d= [100, 11, 3.1415, 2.71, True, 0.75, False]
e= [100, 11, 3.1415, 2.71, True, 0.75, False]
4、使用数组方式快速排序字符串"ac2b4d13",返回仍然是String类型。
str ='ac2b4d13'
"".join(sorted(str))
'1234abcd'
5、创建一个获取真实获取登录Token的dictionary(命名为token{})
{
“client_id”:“A1”,
“client_secret”:“a1b2c3d”,
“username”:“ROOT”,
“password”:“1c63129ae9db9c60c3e8aa94d3e00495”
}
token = {
"client_id":"A1",
"client_secret":"a1b2c3d",
"username":"ROOT",
"password":"123456"
}
print("{}\n{}\n{}".format(token.keys(),token.values(),token.items()))
token["grant_type"] = "usepasswd"
print(token)
del token["password"]
print(token)
print(list(token.values()))
dict_keys(['client_id', 'client_secret', 'username', 'password'])
dict_values(['A1', 'a1b2c3d', 'ROOT', '123456'])
dict_items([('client_id', 'A1'), ('client_secret', 'a1b2c3d'), ('username', 'ROOT'), ('password', '123456')])
{'client_id': 'A1', 'client_secret': 'a1b2c3d', 'username': 'ROOT', 'password': '123456', 'grant_type': 'usepasswd'}
{'client_id': 'A1', 'client_secret': 'a1b2c3d', 'username': 'ROOT', 'grant_type': 'usepasswd'}
['A1', 'a1b2c3d', 'ROOT', 'usepasswd']
6、创建一个seta ={1,“x”,True,“y”,5,3},新增2、4、z三个元素,删除True元素后输出,创建一个setb={1, 3, 4, 5, ‘x’, ‘w’, ‘z’},分别求seta setb两个集合的交集、并集、差集(seta-setb)、补集。#
seta = {1,"x",True,"y",5,3}
seta.update((2,4,"z"))
seta.discard(True)
print("seta=%s"%seta)
setb={1, 3, 4, 5, 'x', 'w', 'z'}
print("setb=%s"%setb)
print("交集={}\n并集={}\n差集={}\n补集={}\n".format(seta&setb,seta|setb,seta-setb,seta^setb,))
seta={2, 3, 4, 5, 'z', 'y', 'x'}
setb={'x', 1, 'z', 3, 4, 5, 'w'}
交集={'z', 3, 4, 5, 'x'}
并集={1, 2, 3, 4, 5, 'z', 'w', 'y', 'x'}
差集={2, 'y'}
补集={1, 2, 'w', 'y'}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)