访问列表的元素

# 访问列表的元素
"""
访问元素的方法:
"""
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 exitdef 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=Falsewhile 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 =Trueelif 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)一样'''

笨方法学python 34-38相关推荐

  1. python38使用_笨方法学Python 习题38:列表的操作

    列表的操作: 这里先复习一下之前遇见过的函数:split()通过指定分隔符对字符串进行切片,如果参数num有指定值,则仅分隔num个子字符 str.split(str="", nu ...

  2. 《 笨方法学 Python 》_ 目录

    < 笨方法学 Python >(第 3 版)书中代码是 Python 2 版本,本着学习 Python 3 的目的,用 Python 3 完成本书的习题,代码也已上传到 Github. 作 ...

  3. 笔记 | 笨方法学Python

    整理 | 阿司匹林 出品 | 人工智能头条(公众号ID:AI_Thinker) Python 有多好应该不用多说了,毕竟它是"钦定的"最接近 AI 的语言.(当然,PHP 才是最好 ...

  4. 笨方法学Python(二)

    笨方法学Python,习题16 - 21 版本:3.8.0 编辑器:Visual Studio Code 习题16到21讲的是文件的读写和函数的基础,可以通过一个实例来同时练习他们.在下列情景中,我将 ...

  5. 笨方法学python 习题37

    还是在笨方法学python中... 本节的习题是看一下作者列出的python中的各种运算符,尝试来理解这些符号. 在这里,我只列出了一些自己不会的,通过查百度得到得答案,这里来列举一下. (另外有不怎 ...

  6. 笨方法学python 15章疑问

    ** 笨方法学python 15章疑问 在15张中教我们读取文件,但是当我测试能否打开我之前写的py格式的文本时出现了这一幕 文件打开后然后又出现了 File "15.py", l ...

  7. 《笨方法学python》_《笨办法学Python》 第46课手记

    <笨办法学Python> 第46课手记 这节课制作了一个Python的项目骨架,花了我一个晚上和一个早上的时间,原因是我下载的pdf里面只有OX S的命令行,而没有win下的.我为此在知道 ...

  8. 笨方法学python习题4

    变量和命名 #笨方法学python_习题4#定义变量 cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90#计算 cars_not_ ...

  9. 笨方法学python第四版当当_“笨办法”学Python(第3版)

    ZedShaw完善了这个堪称世上较好的Python学习系统.只要跟着学习,你就会和迄今为止数十万Zed教过的初学者一样获得成功. 在这本书中,你将通过完成52个精心设计的习题来学会Python.阅读这 ...

  10. 笨方法学python 习题34

    习题34 python:3.9 animals = ['bear','python','peacock','kangaroo','whale','platypus']print ("The ...

最新文章

  1. CSS中的EM属性-弹性布局
  2. SharePoint 2007 URL地址快速一览表
  3. pdflush内核线程池及其中隐含的竞争
  4. linux的for循环怎么写,Linux命令:for循环写法总结
  5. java.util.scanner sc_关于Java的Scanner的问题,菜鸟求各大神解答
  6. 了解 SharePoint 2010 开发中的关键点
  7. Android第四十五天
  8. 【Ubuntu】Ubuntu16.04+VMware+Win10安装及配置教程
  9. 去掉QQ2008的腾讯迷你首页和聊天时的广告
  10. 遍历排列的实现——VB2005
  11. 青岛鑫江东方城购物中心远程预付费电能管理系统的应用
  12. python :alpha shapes 算法检测边界点
  13. win10计算机初始输入法,Win10默认输入法怎么设置?
  14. [生存志] 第43节 齐文姜齐宣姜争艳
  15. linux怎么运行quartus,如何安裝Linux版本的Quartus II
  16. 计算机专业的文献翻译,计算机专业外文文献翻译
  17. 单片机低功耗配置及注意事项
  18. html如何添加时钟效果,五步轻松实现JavaScript HTML时钟效果
  19. 【C语言进阶】③探究浮点数在内存中的存储方式
  20. Nginx使用场景及相关配置

热门文章

  1. RabbitMQ学习笔记 - mandatory参数
  2. 脑波设备mindwaveTGC接口示例
  3. 微信用户免密免验证码登录
  4. 树莓派远程监控水位传感器
  5. webgate单点登录原理
  6. 单片机毕设选题 stm32便携用电功率统计系统 - 物联网 嵌入式
  7. 树莓派pico w点灯
  8. 浏览器的缓存机制 优点 缺点 协商缓存和强缓存 浏览器缓存过程 如何判断强缓存是否过期
  9. 推特营销引流入门指南
  10. 实现类似淘票票电影滑动选择的效果