访问列表的元素
# 访问列表的元素
"""
访问元素的方法:
"""
animals=['bear','tiger','penguin','zebra']
"""
animals列表有四个动物['bear','tiger','penguin','zebra']
用1获取第一个元素,按照数字的顺序排列事物称为序数(ordinal number)
以0为开头抓取任何一个元素是索引(index),称为基数(cardinal number)
当需要抓取第N只动物时,需要将序数-1转换成基数。将前者-1,那么第3只动物的索引就是2:penguin
序数等于有序,从1开始;
基数是随机抽取,从0开始
"""
bear=animals[0]
print(bear,0)
tiger=animals[1]
print(tiger,1)
penguin=animals[2]
print(penguin,2)
zebra=animals[3]
print(zebra,3)
——————————————————
bear 0
tiger 1
penguin 2
zebra 3
进程已结束,退出代码0
________________
animals=['bear','python3.6','peacock','kangaroo','whale','platypus']
bear=animals[0]
print(bear,0)
animals[0 +1]=animals[1]
print(animals[1],1)
peacock=animals[2]
print(peacock,2)
kangaroo=animals[3]
print(kangaroo,3)
whale=animals[4]
print(whale,4)
platypus=animals[5]
print('platypus',5)
__________________
bear 0
python3.6 1
peacock 2
kangaroo 3
whale 4
platypus 5
进程已结束,退出代码0
习题35 分支和函数
代码如下:
from sys import exit
def gold_room():
print(f"This room is full of gold. How much do you take?")
choice = input(">")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man,learn to type a number.")
if how_much <50:
print("Nice ,you're not greedy,you win!")
exit(0)
else:
dead('You greedy bastard!')
def bear_room():
print("There is a bear here.")
print("The bear has a bunch oh honey.")
print("The fat bear is in front of another door.")
print("How are you going to move the bear?")
bear_moved=False
while True:
choice = input('>')
if choice == "take honey":
dead("The bear looks at you then slaps your face off.")
elif choice =="taunt bear" and not bear_moved:
print("The bear has moved from the door.")
print("You can go through it now.")
bear_moved =True
elif choice =="taunt bear"and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif choice =="open door"and bear_moved:
gold_room()
else:
print("I got no idea what that means.")
def cthulhu_room():
print("Here you see the great evil Cthulhu.")
print("He,it,whatever stars at you and you go insane.")
print("Do you flee for your life or eat your head?")
choice=input(">")
if "flee"in choice:
start()
elif "head" in choice:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why):
print(why,"Good job!")
exit(0)
def start():
print("You're in the dark room.")
print("There is a door to your right and left.")
print("Which one do you take?")
choice = input('>')
if choice =="left":
bear_room()
elif choice=="right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
结果输出:
You're in the dark room.
There is a door to your right and left.
Which one do you take?
>right
Here you see the great evil Cthulhu.
He,it,whatever stars at you and you go insane.
Do you flee for your life or eat your head?
>flee
You're in the dark room.
There is a door to your right and left.
Which one do you take?
>left
There is a bear here.
The bear has a bunch oh honey.
The fat bear is in front of another door.
How are you going to move the bear?
>fat bear
I got no idea what that means.
>taunt bear
The bear has moved from the door.
You can go through it now.
>open door
This room is full of gold. How much do you take?
>1
Nice ,you're not greedy,you win!
进程已结束,退出代码0
while True
可以创建一个无限循环
exit(0)的功能?
exit(0)是终止程序,数字用于表示程序是否遇到错误而终止。
exit(1)表示发生了某种错误,exit(0)表示正常退出,这与布尔逻辑0==False相反
input()和input(‘>’)
input的参数是将会打印出来的字符串,用于提醒用户输入
习题36
if语句的规则
- 每一条if语句必须包含一个else
- 如果else得不到执行,那就没有任何意义,那就要在else语句后面使用die函数,让它打印出错消息并且die给你看
- if语句嵌套不要超过两层,最好尽量保持一层
- 将if语句当作段落,其中每个if、elif、else组合就跟段落的句子组合一样。这种组合的最前面和最后面留一个空行以区分。
- 复杂的布尔测试需要在函数里将运算事先放到一个变量里,并且定义变量。
循环的规则
- while循环常用于不会停止的循环, 其他类型的循环都用for循环,尤其是循环对象数量固定或者有限的情况下。
调试技巧
- 利用print()打印代码的关键点
- 代码要一部分一部分的运行,检查错误
习题37
and 逻辑与(示例:True and False == False)
as import someone as a 假如someone是某个模块,这里将a指向模块someone,相当于给someone赋名;with-as语句的一部分(示例:with X as Y:pass)
assert 断言(确保)某东西为真 (例子:assert 1 == 2,它是不对的,所以会首先返回 AssertionError错误,assert False,"Error!")
break 立即停止循环(示例:while True:break)
class 定义类(示例:class person(object))
continue 停止当前循环的后续步骤,再做一次循环(示例:while True:continue)
def 定义函数(示例:def X:pass)
del 从字典中删除(示例:del X[Y])
elif else if条件(示例:if: X;elif: Y;else:J)
else else条件(示例:if: X;elif: Y;else:J)
except 如果发生异常,运行此处代码(示例:except ValueError,e:print(e))
exec 将字符串作为python脚本运行(示例:exec"print('Hello')")
finally 不管是否发生异常,都运行此处代码(示例:finally:pass)
for 针对物件集合执行循环(示例:for X in Y:pass)
from 从模块导入特定部分(示例:from X import Y)
global 定义全局变量(示例:global X)
in for循环的一部分,也可以X是否再Y中的条件判断(示例:for X in Y:pass,以及1 in [1]==True)
is 类似于==,判断是否一样(示例:1 is 1 == True)
lambda 匿名函数(示例:s=lambda y:y**y;s(3))
not 逻辑非(示例:not True == False)
or 逻辑或(示例:True or False == True)
pass 代表空缺码(示例:def empty():pass)是为了保持程序结构的完整性。(假如你自定义了一个函数,里面没有任何语句,这样python就会报错,而如果你使用了pass语句,这样就可以规避这一错误)
raise 出错后主动抛出异常(示例:raiseValueErro("No"))
return 返回值并退出函数(示例:def X(): return Y)
try 尝试执行代码,出错后转到except(示例:try:pass)
while while循环(示例:while X:pass)
with 将表达式作为一个变量,执行代码块(示例:with X as Y:pass)
yield 暂停函数,返回到调用函数的代码中(示例:def X(): yield Y;X().next)
#数据类型
True 布尔值“真”,True or False == True
False 布尔值“假”,True or False == False
None 没有值,x = None
bytes 字符串储存,可能是文本、PNG图片和文件等,X=b'Hello'
strings 存储文本信息,X='hello'
numbers 存储整数,i=100
Floats 存储十进制,i=10.389
lists 存储列表,j=[1,2,3,4]
dicts 存储键-值映射,e={'x':1,'y':2}
#字符转义序列
\\ 反斜杠
\b 退格符
\a 响铃
\r 回车
\v 垂直制表符
\t 横向制表符
\n 换行符
%e 浮点数:以指数形式输出
%g 浮点数:更具实际情况输出
%f 浮点数:输出浮点数
%c 字符格式
%% 百分号自身
#运算符
+ 加号
- 减号
* 乘号
** 幂,2**4=16
/ 除号
// 除后向下取整,2//4=0
% 字符串翻译,或求余数,2%4=2
< 小于
> 大于
<= 小于等于,4<=4 == True
>= 大于等于,4>=4 == True
== 等于,4 == 5 == False
!= 不等于,4!= 5 == True
() 括号,len('hi')== 2
[] 方括号,[1,3,4]
{} 花括号,{'X':5,'Y':10}
@ 修饰器符,@classmethod
+= 加后赋值,
-= 减后赋值
*= 乘后赋值
/= 除后赋值
//= 除后舍余并赋值
%= 求余后赋值
**= 求幂后赋值
习题38
代码如下:
'''
append函数是向列表追加
代码出现了mystuff.append('hello'),python开始查找有无创建mystuff变量,或者检查mystuff是不是一个函数参数,或者是一个全局变量
python找到mystuff,就轮到句点(.)运算符,查看mystuff内部的变量,由于mystuff是一个列表,python知道变量支持的函数
处理append,python将append和mystuff支持的函数进行一一对比,如果确实有append函数,python就会使用append函数
python看到(),就会意识到,这是一个函数,通过额外参数mystuff,再调用append函数
'''
ten_things="Apple Orange Crows Telehpone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ['Day','Night','Song','Frisbee','Corn','Banana','Girl','Boy']
while len(stuff)!=10:
next_one=more_stuff.pop()
print("Adding:",next_one)
stuff.append(next_one)
print(f"There are len{stuff} item now.")
print("There we go:",stuff)
print("stuff[1]")
print("stuff[-1]")#whoa!fancy
print("stuff.pop()")
print(''.join(stuff))#what cool!
print('#'.join(stuff[3:5]))#super stellar!
结果输出:
C:\Users\50520\anaconda3\python.exe D:/1A-Bella---project/2022_11练习/习题38.py
Wait there are not 10 things in that list. Let's fix that.
Adding: Boy
There are len['Apple', 'Orange', 'Crows', 'Telehpone', 'Light', 'Sugar', 'Boy'] item now.
Adding: Girl
There are len['Apple', 'Orange', 'Crows', 'Telehpone', 'Light', 'Sugar', 'Boy', 'Girl'] item now.
Adding: Banana
There are len['Apple', 'Orange', 'Crows', 'Telehpone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana'] item now.
Adding: Corn
There are len['Apple', 'Orange', 'Crows', 'Telehpone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn'] item now.
There we go: ['Apple', 'Orange', 'Crows', 'Telehpone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
stuff[1]
stuff[-1]
stuff.pop()
AppleOrangeCrowsTelehponeLightSugarBoyGirlBananaCorn
Telehpone#Light
进程已结束,退出代码0
'''
列表是常用的数据结构(组织数据的正式方法),就是有序的列表,用于存储、访问元素
比如,你有一堆纸牌,每张都有一个值,这些纸牌拍成一摞,这是一个从上到下的列表
你可以从上到下去牌,也可以从中间随机取牌
如果你需要抽特定牌,也要一张张检查,直到抽到特定牌
-有序的列表:纸牌从头到尾都是有序排列的
-要存储的东西:纸牌
-随机访问:任意抽取纸牌
-线性:从第一张纸牌开始,依次寻找某张牌
-通过索引:第19张牌需要数到19,找到第19张牌,Python可以通过索引位置找到19对应的牌
什么时候使用列表?
只要能匹配到列表数据结构的有用功能,你就能使用列表
-如果你需要维持次序(列表内容排列顺序,而不是按照某个规则排序),列表不会自动为你按照某规则排序
-如果你急需一个数字随机访问内容,需要从0开始访问
-如果你需要线性(从头到尾)访问内容,可以用for循环
'''
'''
''.join起拼接作用
stuff[3:5]
列表索引从3开始到4结束,与range(3,5)一样
'''