第四章 Python外壳:代码结构
Python的独特语法:
- 不使用分号结束语句,而是回车;
- 通过代码缩进来区分代码块;
- if、while、for等,都不用括号,但不能没有冒号(:)。
如何将一行命令分为多行?
>>> myNameIs = "Li\
Zhi\
Xin.\
"
>>> myNameIs
'LiZhiXin.'
4.1 条件语句和循环语句
如何使用if、elif和else进行比较?
>>> a = 1
>>> if a < 2:
print ("yes")
elif a > 2:
print ("no")
else:
print ("chaos") yes
如何连接条件表达式?
python中没有!、&& 和 || 运算符,分别用 not、and 和 or代替。
>>> not 1
False
>>> 5 < 6 and 1 < 2
True
>>> 5 < 6 or 1 > 2
True
python中有哪些假值?
>>> False
False
>>> None
>>> 0
0
>>> 0.0
0.0
>>> ''
''
>>> []
[]
>>> ()
()
>>> {}
{}
>>> set()
set()
如何使用while进行循环?
>>> count = 1
>>> while count <= 5:
print(count)
count += 1 1
2
3
4
5
如何跳出循环?
>>> while True:
stuff = input("string to calpitalize [type q to quit]:")
if stuff == 'q':
break
print(stuff.capitalize()) string to calpitalize [type q to quit]:li zhi xin
Li zhi xin
string to calpitalize [type q to quit]:q
>>>
如何跳到循环开始(用于跳过特定条件的循环)?
>>> while True:
value = input("Interger, please [q to quit]: ")
if value == 'q':
break
number = int(value)
if number % 2 == 0:
continue
print(number, "squared is ", number*number) Interger, please [q to quit]: 1
1 squared is 1
Interger, please [q to quit]: 2
Interger, please [q to quit]: 3
3 squared is 9
Interger, please [q to quit]: 4
Interger, please [q to quit]: q
循环外的else是如何使用的?
>>> numbers = [1,3,5]
>>> position = 0
>>> while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
position += 1
else:
print("No even number found.") No even number found.
*如何使用for进行迭代(很独特)?
python中的for很牛逼,可以在数据结构和具体实现未知的情况下,遍历整个数据结构:
>>> rabbits = ['a', 'b', 'c', 'd']
>>> current = 0
>>> while current < len(rabbits):
print(rabbits[current])
current += 1 a
b
c
d
>>> for rabbit in rabbits:
print(rabbit) a
b
c
d
>>> word = 'cat'
>>> for letter in word:
print(letter) c
a
t
>>> a = {'a':'b', 'c':'d', 'e':'f'}
>>> for key in a:
print(key) a
c
e
>>> for value in a.values():
print(value) b
d
f
>>> for item in a.items():
print(item) ('a', 'b')
('c', 'd')
('e', 'f')
>>> for key, value in a.items():
print(key, value) a b
c d
e f
如何用zip()函数进行迭代?
对多个序列使用并行迭代,就是一起迭代,等价于将多个序列有序合并了。
>>> c = 0.1, 0.2, 0.3
>>> a = (1, 2, 3)
>>> b = ['a', 'b', 'c', 'd']
>>> c = 0.1, 0.2, 0.3, 0.4, 0.5,
>>> for e, f, g in zip(a, b, c):
print(e, ' ', f, ' ', g) 1 a 0.1
2 b 0.2
3 c 0.3
list()、zip()和 dict()可以灵活运用。
如何生成特定区间的自然数序列?
range()的使用方法类似切片,但是却是使用‘,’分隔,而不是‘:’。
>>> for x in range(0,3):
print(x) 0
1
2
>>> list(range(0,3))
[0, 1, 2]
4.2 推导式(python特有)
从一个或多个迭代器创建数据结构,可以将循环和条件结合。
列表推导式
>>> number_list = [number for number in range(1,6)]
>>> number_list
[1, 2, 3, 4, 5]
>>> a_list = [number for number in range(1,6) if number % 2 ==1]
>>> a_list
[1, 3, 5]
>>> rows = range(1,4)
>>> cols = range(1,3)
>>> cells = [(row, col) for row in rows for col in cols]
>>> for cell in cells:
print(cell) (1, 1)
(1, 2)
(2, 1)
(2, 2)
(3, 1)
(3, 2)
字典推导式
>>> word = 'letters'
>>> letter_counts = {letter:word.count(letter) for letter in word}
>>> letter_counts
{'l': 1, 't': 2, 'r': 1, 's': 1, 'e': 2}
函数
python中参数有哪几种使用方法?
>>> def func(a, b, c):
print('a is ', a, 'b is ', b, 'c is ', c) >>> func(1, 2, 3)
a is 1 b is 2 c is 3
>>> func(c = 1, b = 2, a = 3)
a is 3 b is 2 c is 1
>>> d = [1, 2, 3]
>>> func(*d)
a is 1 b is 2 c is 3
>>> e = {'c':1, 'b':2, 'a':3}
>>> func(**e)
a is 3 b is 2 c is 1
生成器
装饰器
命名空间和作用域
异常
第四章 Python外壳:代码结构的更多相关文章
- [Python学习笔记][第四章Python字符串]
2016/1/28学习内容 第四章 Python字符串与正则表达式之字符串 编码规则 UTF-8 以1个字节表示英语字符(兼容ASCII),以3个字节表示中文及其他语言,UTF-8对全世界所有国家需要 ...
- [Python笔记][第四章Python正则表达式]
2016/1/28学习内容 第四章 Python字符串与正则表达式之正则表达式 正则表达式是字符串处理的有力工具和技术,正则表达式使用预定义的特定模式去匹配一类具有共同特征的字符串,主要用于字符串处理 ...
- Unity 游戏框架搭建 2019 (三十九、四十一) 第四章 简介&方法的结构重复问题&泛型:结构复用利器
第四章 简介 方法的结构重复问题 我们在上一篇正式整理完毕,从这一篇开始,我们要再次进入学习收集示例阶段了. 那么我们学什么呢?当然是学习设计工具,也就是在上篇中提到的关键知识点.这些关键知识点,大部 ...
- 0003.5-20180422-自动化第四章-python基础学习笔记--脚本
0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...
- “全栈2019”Java异常第四章:catch代码块作用域详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java异 ...
- 《Python CookBook2》 第四章 Python技巧 对象拷贝 && 通过列表推导构建列表
(先学第四章) 对象拷贝 任务: Python通常只是使用指向原对象的引用,并不是真正的拷贝. 解决方案: >>> a = [1,2,3] >>> import c ...
- 第四章:重构代码[学习Android Studio汉化教程]
第四章 Refactoring Code The solutions you develop in Android Studio will not always follow a straight p ...
- Python项目代码结构
目录结构组织方式 简要解释一下: bin/: 存放项目的一些可执行文件,当然你可以起名script/之类的也行. luffy/: 存放项目的所有源代码.(1) 源代码中的所有模块.包都应该放在此目录. ...
- 《Python核心编程》 第四章 Python对象- 课后习题
练习 4-1. Python对象.与所有Python对象有关的三个属性是什么?请简单的描述一下. 答:身份.类型和值: 身份:每一个对象都有一个唯一的身份标识自己,可以用id()得到. 类型:对象的 ...
随机推荐
- Spring 的优秀工具类盘点
文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...
- haha
[问题描述] 栈是一种强大的数据结构,它的一种特殊功能是对数组进行排序.例如,借助一个栈,依次将数组1,3,2按顺序入栈或出栈,可对其从大到小排序:1入栈:3入栈:3出栈:2入栈:2出:1出栈.在上面 ...
- Python 2.7.9 Demo - isinstance
#coding=utf-8 #!/usr/bin/python a = 'abc'; print isinstance(a, str);
- SVN Unable to connect to a repository at URL问题解决
图1 之前用的好好的,不知道为什么今天就不行了,根据网上给的方法TortoiseSVN -> Settings -> Saved Data,点击个个"Clear"按钮, ...
- 我的android学习经历29
四大组件之广播接收者BroadcastReceiver 新建广播接收器 需要新建一个类继承类BroadcastReceiver,并且重写其中的方法onReceive(),不要在这个方法中添加过多的逻辑 ...
- 【leetcode❤python】299. Bulls and Cows
class Solution(object): def getHint(self, secret, guess): """ :type ...
- 关于跨域的ajax
$.getJSON("http://query.yahooapis.com/v1/public/yql?callback=?", { q: "select * from ...
- Python ftplib
http://automationtesting.sinaapp.com/blog/m_ftplib https://docs.python.org/2/library/ftplib.html 概述 ...
- jdk安装环境变量设置
设置JAVA_HOME,点击新建,变量名:JAVA_HOME,变量值:D:\java\jdk1.7.0,即刚才jdk安装的路径. 设置CLASSPATH属性,变量名:CLASSPATH,变量值:. ...
- apue和error
在做进程环境测试的时候,测试demo中出现了apue.h,而标准库中没有这个头文件和其中的函数定义,经查找需要在/usr/include中添加apue.h和error.c.原型可以去这个网站查找. ...