1. 局部变量、全局变量

  局部变量:

 x = 50
def func(x):
x = 2
print('Change local x to',x) func(x)
print('x is still',x)
输出:

Change local x to 2
x is still 50

  全局变量:

 x = 50
def func():
global x print('x is',x)
x = 2
print('Change global x to',x) func()
print('Value of x is',x) 输出:

x is 50
Change global x to 2
Value of x is 2

2. 带默认值的参数,关键字参数

 def func(a, b=5, c=10):
print('a is',a, 'and b is', b, 'and c is', c) func(3)
func(25, c=7)
func(b=8, c=9, a=10)
输出:

a is 3 and b is 5 and c is 10
a is 25 and b is 5 and c is 7
a is 10 and b is 8 and c is 9

3. 列表list

 # ========list 列表[]=========
# ds_using_list
shoplist = ['apple', 'mango', 'carrot', 'banana'] print('I have', len(shoplist), 'items to purchase.') print('These items are:', end=' ')
for item in shoplist:
print(item, end=' ') #append
print('\nI also have to buy rice.')
shoplist.append('rice') #list.append此函数用来在list末尾添加元素
print('My shop list is now:', shoplist) #sort
print('I will sort my list now.')
shoplist.sort() #sort排序
print('Sorted shop list is', shoplist) # how to del from list
print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shop list is now', shoplist)
输出:

I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shop list is now: ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now.
Sorted shop list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shop list is now ['banana', 'carrot', 'mango', 'rice']

4. 元组

 # =========tuple 元组()========
# ds_using_tuple
zoo = ('python', 'tiger', 'elephant')
print('Number of animals in the zoo is', len(zoo)) new_zoo = 'monkey', 'camel', zoo
print('Number of CAGES in the new zoo is', len(new_zoo))
print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
print('All the animals in new zoo are', new_zoo)
print('Animals brought from the old zoo is', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2]) # 包含0或1个项目的元组,你必须在第一个(也是唯一一个)项目的后面加上一个逗号来指定它,singleton = (2, )
输出:

Number of animals in the zoo is 3
Number of CAGES in the new zoo is 3
Number of animals in the new zoo is 5
All the animals in new zoo are ('monkey', 'camel', ('python', 'tiger', 'elephant'))
Animals brought from the old zoo is ('python', 'tiger', 'elephant')
Last animal brought from old zoo is elephant

 

列表与元组的区别:
1.列表用[ ], 元组用( )
2.列表内容可变,元组内容不可变,但可通过嵌套的形式添加
3.元组内可嵌套列表
4.在定义只有一个元素的元祖时加入"逗号"以免产生和数学运算的歧义
5.元组通常有不同的数据类型,而列表是相同类型的数据队列。元组表示的是结构,而列表表示的是顺序
6.列表不能当作字典的key, 而元组可以

5. 字典

 # =========dict 字典{:}==========
# ds_using_dict
#ab is address book
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
} print("Swaroop's address is", ab['Swaroop']) #delete a key
del ab['Spammer'] print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
#format前是“点”(.) #add a key
ab['Guido'] = 'guido@python.org' if 'Guido' in ab:
print("\nGuido's address is", ab['Guido'])
输出:

Swaroop's address is swaroop@swaroopch.com

There are 3 contacts in the address-book

Guido's address is guido@python.org

6. 序列

 # =============序列(列表、元组、字符串都是序列Sequence的一种)=============
# 序列的主要功能是资格测试(也就是in与not in表达式)和索引操作
# 列表、元组和字符串(序列的三种形态),同样拥有切片运算符,它允许我们对序列切片(获得序列中的一部分)
# ds_seq
shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'LeonardoDiCaprio' # 索引或“下标”操作符
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
# 索引为负值,表示倒序索引
print('Character 0 is', name[0]) #对list切片
print('shoplist:',shoplist)
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:]) #对字符串切片
print('name:', name)
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])
print('字符串从开始到结束步长为2:', name[::2])
输出:

Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Character 0 is L
shoplist: ['apple', 'mango', 'carrot', 'banana']
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
name: LeonardoDiCaprio
characters 1 to 3 is eo
characters 2 to end is onardoDiCaprio
characters 1 to -1 is eonardoDiCapri
characters start to end is LeonardoDiCaprio
字符串从开始到结束步长为2: LoadDCpi

7. 集合

 # =================集合set================
# 集合是简单对象的无序集合
# 当集合中的项目存在与否比起次序更重要时,使用集合
# 控制台运行以下命令
bri = set(['brazil', 'russia', 'india'])
print('india' in bri)
print('usa' in bri)
输出:

True
False

8. 引用

 # Reference引用
#ds_reference
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist是指向同一对象的另一种名称
mylist = shoplist # delete 0
del shoplist[0] print('shoplist is', shoplist)
print('mylist is', mylist)
if 'apple' in mylist:
print('mylist is different with shoplist')
else:
print('mylist is the same list with shoplist') print('Copy by making a full slice')
# 通过生成一份完整的切片,制作一份列表的副本
mylist = shoplist[:]
del mylist[0] print('shoplist is', shoplist)
print('mylist is', mylist)
if shoplist[0] not in mylist:
print('通过切片制作副本,则mylist不再指向shoplist')
输出:

Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
mylist is the same list with shoplist
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
通过切片制作副本,则mylist不再指向shoplist

9. 列表推导

 # 列表推导
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i>2]
print(listtwo)
输出:
[6, 8]

10. GuessNumber

  使用random模块的randint方法随机获取整数。

# GuessNumber
import random
print("********GuessNumber********")
temp = input("GuessNumber:")
Guess = int(temp)
secret = random.randint(1,100) while Guess != secret:
print("Wrong!")
if Guess<secret:
print("Bigger next time!")
else:
print("Smaller next time!")
Guess = int(input()) print("You smart ass!")
print("Game Over")

11. 自定义模块

  导入模块,则必须在相同目录下,或者把模块放置在sys.path所列出的其中一个目录下。

 def say_hi():
'''This is my module
I'm learning to coding my own module
导入模块,则必须在相同目录下,或者把模块放置在sys.path所列出的其中一个目录下
'''
print('Hi, this is mymodule speaking.') __version__ = '0.1'

12. 类

  类变量是共享的,他们可以被属于该类的所有实例访问,当任何一个对象对类变量做出改变时,发生的变动在其它所有实例中都会得到体现。
  对象变量由类的每一个独立的对象或实例所拥有。

  所有类成员(包括数据成员)都是公开的,所有的方法都是虚拟的。
  如果在数据成员名字中使用双下划线为前缀,Python会使用名称调整使其成为私有变量。

  __init__方法会在类的对象被实例化时立即运行

# 类变量与对象变量:

# oop_objvar.py
# coding = UTF-8

class Robot:
"""表示有一个带有名字的机器人。"""
# 一个类标量,用来计数机器人的数量
population = 0 def __init__(self, name):
"""初始化数据"""
self.name = name
print("(Initializing {})".format(self.name)) #机器人增加人口数量
Robot.population += 1 def die(self):
"""我挂了"""
print("{} is being destroyed!".format(self.name)) Robot.population -= 1 if Robot.population == 0:
print("{} is the last one.".format(self.name))
else:
print("There are still {:d} robots working.".format(Robot.population)) def say_hi(self):
"""来自机器人的诚挚问候
没问题,你做得到。"""
print("Greetings, my masters call me {}.".format(self.name)) @classmethod #类方法 @classmethod装饰器等价于调用:how_many = classmethod(how_many)
def how_many(cls):
"""打印出当前的人口数量"""
print("We have {:d} robots.".format(cls.population))

droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many() droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many() print("\nRobots can do some work here.\n") print("Robots have finished their work. So let's destory them.")
droid1.die()
droid2.die() Robot.how_many() help(Robot.say_hi)
输出:

(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.


Robots can do some work here.


Robots have finished their work. So let's destory them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO is the last one.
We have 0 robots.
Help on function say_hi in module __main__:


say_hi(self)
来自机器人的诚挚问候
没问题,你做得到。

 

13. 继承

 # 继承
# 基类和派生类/超类和子类 # coding = UTF-8 class SchoolMember:
'''代表任何学校里的成员。'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember:{})'.format(self.name)) def tell(self):
'''tell me about detail'''
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ") class Teacher:
'''代表一位老师'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {})'.format(self.name)) def tell(self):
SchoolMember.tell(self)
print('Salary:"{:d}"'.format(self.salary)) class Student:
'''代表一位学生'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized Student: {})'.format(self.name)) def tell(self):
SchoolMember.tell(self)
print('Marks: "{:d}"'.format(self.marks)) # 实例化
t = Teacher('Mrs.Xiang', 21, 12000)
s = Student('NemoWang', 22, 87) print() members = [t, s]
for member in members:
member.tell()
输出:

(Initialized SchoolMember:Mrs.Xiang)
(Initialized Teacher: Mrs.Xiang)
(Initialized SchoolMember:NemoWang)
(Initialized Student: NemoWang)

Name:"Mrs.Xiang" Age:"21" Salary:"12000"
Name:"NemoWang" Age:"22" Marks: "87"

14. 判断输入的字符串是否为回文

  允许存在大小写,空格,英文标点。

  使用切片功能翻转文本。

  可以通过使用 seq[a:b] 来从位置 a 开始到位置 b 结束来对序列进行切片。

  同样可以提供第三个参数来确定切片的步长(Step)。

  默认的步长为 1 ,它会返回一份连续的文本。

  如果给定一个负数步长,如 -1 ,将返回翻转过的文本。

 # 输入与输出
# 做到忽略大小写,空格,标点符号
import string def reverse(text):
return text[::-1] def is_palindrome(text): #回文
return text == reverse(text) something = input("Enter text: ")
# 忽略大小写
something = something.lower()
# 忽略空格(将空格替换)
something = something.replace(' ','')
# 忽略标点符号
for char in string.punctuation:
something = something.replace(char,'')
# 利用string.punctuation来表示中文标点符号是不行的 if is_palindrome(something):
print("yse, it is a palindrome.")
else:
print("No, it is not a palindrome.")
print(reverse(something))
输入:
Rise to vote, sir
输出:
yse, it is a palindrome.

15. 文件

  使用内置的open函数并制定文件名,以及打开模式
  打开模式可以使阅读('r'),写入('w')和追加('a')
  还可以选择通过文本('t')或二进制('b')来读取写入或追加文本
  打开文件以编辑('w'riting)

  如果没有特别指定,
  将假定启用默认的阅读('r'ead)模式

# 文件

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
''' f = open('poem.txt', 'w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close() # 如果没有特别指定,
# 将假定启用默认的阅读('r'ead)模式
f = open('poem.txt')
while True:
line = f.readline() #读取文件的一行
# 零长度指示 EOF
if len(line) == 0:
break
# 每行('line')的末尾
# 都已经有了换行符
# 因为它是从一个文件中进行读取的
print(line, end='')
# 关闭文件
f.close()
输出:

Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

16. pickle

  标准模块Pickle
  通过它可以将任何纯Python对象存储到一个文件中(.data文件存在于py文件所在文件夹)
  并在稍后将其取回
  叫作持久地(Persistently)存储对象

 import pickle

 # The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['banana', 'apple', 'orange', 'mango'] # Write to the file
# 以写入二进制模式打开文件
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f) #dump卸载(存储)数据
f.close() # Destroy the shoplist variable
del shoplist # Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f) #load装载(加载)数据
print(storedlist)
输出:
['banana', 'apple', 'orange', 'mango']

17. 异常

  抛出异常

  通过raise语句来引发一次异常

  用户定义的异常类必须直接或间接从属于Exception类的子类

 # encoding = UTF-8

 class ShortInputException(Exception):
'''一个由用户定义的异常类'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast try:
text = input('Enter something -->')
if len(text) < 3:
raise ShortInputException(len(text), 3) except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print(('ShortInputException: The input was'+
' {0} long, expected at least {1}.')
.format(ex.length, ex.atleast))
else:
print('No exception was raised.')
输入:
a
输出:
ShortInputException: The input was 1 long, expected at least 3.

  try...except也可以结合finally使用

  将finally放在最后,finally语句块的内容通常是做一些后事的处理,比如资源释放

  并且finally语句块是无论如何都要执行的,

  即使在前面的try和except语句块中出现了return,

  都先将finally语句执行完再去执行前面的return语句。

 import sys
import time f = None
try :
f = open('poem.txt')
# 我们常用的阅读风格
while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
sys.stdout.flush()
print("Press ctrl+c now")
# 确保它能运行一段时间
# 每打印一行后插入两秒休眠
time.sleep(2)
except IOError:
print('Could not find file poem.exe')
except KeyboardInterrupt:
print('!!You cancelled the reading from the file.')
finally:
if f:
f.close()
print('(Cleaning up: Closed the file.)')
输出:

Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)

  在try块中获取资源,然后在finally块中释放资源是一种常见的模式

  with语句使得这一过程可以以一种干净的姿态得以完成

  将关闭文件的操作交由with open来自动完成

 with open("poem.txt") as f:
for line in f:
print(line, end='')
输出:

Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

笔记_简明Python教程_Byte_of_Python的更多相关文章

  1. 学习笔记《简明python教程》

    学习笔记<简明python教程> 体会:言简意赅,很适合新手入门 2018年3月14日21:45:59 1.global 语句 在不使用 global 语句的情况下,不可能为一个定义于函数 ...

  2. 笔记|《简明Python教程》:编程小白的第一本python入门书

    <简明Python教程>这本书是初级的Python入门教材,初级内容基本覆盖,对高级内容没有做深入纠结.适合刚接触Python的新手,行文比较简洁轻松,读起来也比较顺畅. 下面是我根据各个 ...

  3. python读书笔记-《简明python教程》上

    1月15日 <简明python教程>上 基本结构: 基础概念+控制流+函数+模块+数据结构+面向对象+I/O+异常+标准库+其他   1.概念 1-0    退出python linux: ...

  4. 《简明python教程》笔记一

    读<简明Python教程>笔记: 本书的官方网站是www.byteofpython.info  安装就不说了,网上很多,这里就记录下我在安装时的问题,首先到python官网下载,选好安装路 ...

  5. 简明Python教程 ~ 随书笔记

    本文是阅读<简明Python教程>所做的随书笔记,主要是记录一些自己不熟悉的用法,或者所看到的比较有意思的内容,本书英文版A Byte of Python, 中文译版 简明Python教程 ...

  6. 《简明Python教程》学习笔记

    <简明Python教程>是网上比较好的一个Python入门级教程,尽管版本比较老旧,但是其中的基本讲解还是很有实力的. Ch2–安装Python:下载安装完成后,在系统的环境变量里,在Pa ...

  7. 简明Python教程自学笔记——命令行通讯录

    [前言]学习Python已经有一段时间了,相关的书籍资料也下载了不少,但是没有一本完整的看完,也没有编出一个完整的程序.今天下午比较清闲就把<简明Python教程>看了一遍,然后根据书里面 ...

  8. (原+转)简明 Python 教程:总结

     简明 Python 教程 说明:本文只是对<简明Python教程>的一个总结.请搜索该书查看真正的教程. 第3章 最初的步骤 1. Python是大小写敏感的. 2. 在#符号右面的内容 ...

  9. 【转】简明 Python 教程

    原文网址:http://woodpecker.org.cn/abyteofpython_cn/chinese/ 简明 Python 教程Swaroop, C. H. 著沈洁元  译www.byteof ...

随机推荐

  1. ROS Learning-003 beginner_Tutorials 创建ROS工作空间

    ROS Indigo beginner_Tutorials-02 创建ROS工作空间 我使用的虚拟机软件:VMware Workstation 11 使用的Ubuntu系统:Ubuntu 14.04. ...

  2. C/C++读写csv文件

    博客转载自:http://blog.csdn.net/u012234115/article/details/64465398 C++ 读写CSV文件,注意一下格式即可 #include <ios ...

  3. p1129 [ZJOI2007]矩阵游戏

    传送门 分析 不难想到将黑点的行列连边,然后判断最大匹配是否等于n 代码 #include<iostream> #include<cstdio> #include<cst ...

  4. spark sql建表的异常

    在使用spark sql创建表的时候提示如下错误: missing EOF at 'from' near ')' 可以看下你的建表语句中是不是create external table ....   ...

  5. 《Effective Java》第3章 对于所有对象都通用的方法

    第8条:覆盖equals时请遵守通用约定 覆盖equals方法看起来似乎很简单,但是有许多覆盖方式会导致错误,并且后果非常严重.最容易避免这类问题的办法就是不覆盖equals方法,在这种情况下,类的每 ...

  6. 解决ScrollView嵌套viewpager滑动事件冲突问题

    重写ScrollView 第一种方案能解决viewpager的滑动问题,但是scrollView有时会滑不动 public class VerticalScrollView extends Scrol ...

  7. widget自定义控件【android.view.InflateException: Binary XML file line #2: Error inflating class...】

    此错误比较难定位,场景是这样的:在一个widget中使用了自定义控件,始终会报 android.view.InflateException: Binary XML file line #2: Erro ...

  8. DataGridView增加全选列

    最近的一个winform的项目中,碰到datagridview控件的第一列添加全选的功能,通常这个功能,有两种实现方式:1. 为控件添加DataGridViewCheckBoxColumn来实现,但是 ...

  9. metasploit 读书笔记-EXPLOITATION

    一、渗透攻击基础 1.常用命令 show exploits 显示Meta框架中所有可用的渗透攻击模块。 show options 显示模块所需要的各种参数 back 返回Meta的上一个状态 sear ...

  10. JavaScript 测试和捕捉(try与catch)

    JavaScript 测试和捕捉 try 语句允许我们定义在执行时进行错误测试的代码块. catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块. JavaScript 语句 try ...