Python入门数的读书笔记

入门书地址

三引号 (""" 或 ''') 来指定多行字符串
字符串是不可变的
输出小数点后三位 print('{0:.3f}'.format(1 / 3))
输出字符串长度为 11 print('{0:_^11}'.format('hello')) ___hello___
print 默认以 '\n' 结尾,要以空白结尾的话 print('a', end = '')

在一个字符串中,一个放置在末尾的反斜杠表示字符串将在下一行继续,但不会添加新的一行
print('This is the first sentence.\
This is the second sentent')
This is the first sentence.This is the second sentent

如果你需要指定一些未经过特殊处理的字符串,比如转义序列,那么你需要在字符串前增加 r 或 R 来指定一个 原始(Raw) 字符串
print(r"Newlines are indicated by \n")
Newlines are indicated by \n

如果你有一行非常长的代码,你可以通过使用反斜杠将其拆分成多个物理行。这被称作显式行连接

** 乘方
//整除

运算发优先级由最低优先级到最高优先级
lambda:Lambda 表达式
if - else :条件表达式
or:布尔“或”
and:布尔“与”
not x:布尔“非”
in, not in, is, is not, <, <=, >, >=, !=, ==:比较,包括成员资格测试(Membership Tests)和身份测试(Identity Tests)。
|:按位或
^:按位异或
&:按位与
<<, >>:移动
+, -:加与减
*, /, //, %:乘、除、整除、取余
+x, -x, ~x:正、负、按位取反
**:求幂
x[index], x[index:index], x(arguments...), x.attribute:下标、切片、调用、属性引用
(expressions...), [expressions...], {key: value...}, {expressions...}:表示绑定或元组、表示列表、表示字典、表示集合

if guess == num:
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
elif guess < num:
print('No, it is a little higher than that')
else:
print('No, it is a little lower than that')

内置函数range()
for i in range(1, 5):
print(i)

告诉 Python 这一变量并非局部的,而是全局(Global)的。我们需要通过 global 语句来完成这件事
x = 10
def f():
global x
x = 2

可变参数
当我们声明一个诸如 *param 的星号参数时,从此处开始直到结束的所有位置参数(Positional Arguments)都将被收集并汇集成一个称为“param”的元组(Tuple)。
类似地,当我们声明一个诸如 **param 的双星号参数时,从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为 param 的字典(Dictionary)。
def total(a = 3, *number, **phontbook):
print('a', a)
for i in number:
print('number is ', i)
for first, second in phontbook.items():
print(first, second)

total(10, 4, 65, 2, Jack = 25, John = 2352, Inge = 2461)

a 10
number is 4
number is 65
number is 2
Jack 25
John 2352
Inge 2461

文档字符串 DocString
我们可以通过使用函数的 __doc__(注意其中的双下划綫)属性(属于函数的名称)来获取函数 print_max 的文档字符串属性
def print_max(x, y):
'''print the max number in the x and y

they are int'''
if x > y:
print(x)
print(y)
'''This is another strings'''

print_max(3, 5)
print(print_max.__doc__)

5
print the max number in the x and y

they are int

列表 是一种用于保存一系列有序项目的集合,也就是说,你可以利用列表保存一串项目的序列。
shoplist = ['apple', 'mango', 'carrot', 'banana']

元组(Tuple)用于将多个对象保存到一起。你可以将它们近似地看作列表,但是元组不能提供列表类能够提供给你的广泛的功能。
元组的一大特征类似于字符串,它们是不可变的,也就是说,你不能编辑或更改元组。
元组是通过特别指定项目来定义的,在指定项目时,你可以给它们加上括号,并在括号内部用逗号进行分隔。
元组通常用于保证某一语句或某一用户定义的函数可以安全地采用一组数值,意即元组内的数值不会改变。
zoo = ('puthon', 'elephant', 'penguin')
print('Number of animal in the zoo is', len(zoo))

new_zoo = 'monkey', 'camel', zoo
print('Number of animal in the new zoo is', len(new_zoo))
print(new_zoo)
print(new_zoo[2])
print(new_zoo[2][2])

Number of animal in the zoo is 3
Number of animal in the new zoo is 3
('monkey', 'camel', ('puthon', 'elephant', 'penguin'))
('puthon', 'elephant', 'penguin')
penguin

一个空的元组由一对圆括号构成,就像 myempty = () 这样。然而,一个只拥有一个项目的元组并不像这样简单。
你必须在第一个(也是唯一一个)项目的后面加上一个逗号来指定它,如此一来 Python 才可以识别出在这个表达式想表达的究竟是一个元组还是只是一个被括号所环绕的对象,
也就是说,如果你想指定一个包含项目 2 的元组,你必须指定 singleton = (2, )。

字典就像一本地址簿,如果你知道了他或她的姓名,你就可以在这里找到其地址或是能够联系上对方的更多详细信息,换言之,我们将键值(Keys)(即姓名)与值(Values)(即地址等详细信息)联立到一起。
在这里要注意到键值必须是唯一的,正如在现实中面对两个完全同名的人你没办法找出有关他们的正确信息。
另外要注意的是你只能使用不可变的对象(如字符串)作为字典的键值,但是你可以使用可变或不可变的对象作为字典中的值。基本上这段话也可以翻译为你只能使用简单对象作为键值。
在字典中,你可以通过使用符号构成 d = {key : value1 , key2 : value2} 这样的形式,来成对地指定键值与值。
在这里要注意到成对的键值与值之间使用冒号分隔,而每一对键值与值则使用逗号进行区分,它们全都由一对花括号括起。
另外需要记住,字典中的成对的键值—值配对不会以任何方式进行排序。如果你希望为它们安排一个特别的次序,只能在使用它们之前自行进行排序。
a = {'Swaroop' : '[email protected]',
'Larry' : '[email protected]',
'Matsumoto' : '[email protected]',
'Spammer' : '[email protected]'}

print('Swarrop\'s address is', a['Swaroop'])

del a['Spammer']

print(len(a))

for name, b in a.items():
print('Contact {} at {}'.format(name, b))

a['Guido'] = '[email protected]'
if 'Guido' in a:
print(a['Guido'])

Swarrop's address is [email protected]
3
Contact Swaroop at [email protected]
Contact Larry at [email protected]
Contact Matsumoto at [email protected]
[email protected]

序列的主要功能是资格测试(Membership Test)(也就是 in 与 not in 表达式)和索引操作(Indexing Operations),它们能够允许我们直接获取序列中的特定项目。
上面所提到的序列的三种形态——列表、元组与字符串,同样拥有一种切片(Slicing)运算符,它能够允许我们序列中的某段切片——也就是序列之中的一部分。
a = ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'

print(a[0])
print(a[1])
print(a[-1])
print(a[-2])
print(name[0])

print(a[1 : 3])
print(a[2 : ])
print(a[1 : -1])
print(a[ : ])

print(name[1 : 3])
print(name[2 : ])
print(name[1 : -1])
print(name[ : ])

apple
mango
banana
carrot
s
['mango', 'carrot']
['carrot', 'banana']
['mango', 'carrot']
['apple', 'mango', 'carrot', 'banana']
wa
aroop
waroo
swaroop

你同样可以在切片操作中提供第三个参数,这一参数将被视为切片的步长(Step)(在默认情况下,步长大小为 1)
a = ['apple', 'mango', 'carrot', 'banana']
print(a[ :: 2])
print(a[1 : 4 : 2])

['apple', 'carrot']
['mango', 'banana']

集合(Set)是简单且不重复的对象的无序集合(Collection)
>>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}

引用
你必须使用切片操作来制作副本。如果你仅仅是将一个变量名赋予给另一个名称,那么它们都将“查阅”同一个对象
a = ['apple', 'mango', 'carrot', 'banana']
b = a

del a[0]
print(a)
print(b)

c = a[:]
del a[0]
print(a)
print(c)

['mango', 'carrot', 'banana']
['mango', 'carrot', 'banana']
['carrot', 'banana']
['mango', 'carrot', 'banana']


name = 'Swaroop'

if name.startswith('Swa'):
print('Yes, the string starts with "Swa"')

if 'a' in name:
print('Yes, it contains the string "a"')

if name.find('war') != -1:
print('Yes, it contains the string "war"')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

类方法与普通函数只有一种特定的区别——前者必须多加一个参数在参数列表开头,这个名字必须添加到参数列表的开头,但是你不用在你调用这个功能时为这个参数赋值,Python 会为它提供。这种特定的变量引用的是对象本身,按照惯例,它被赋予 self 这一名称。

__init__ 方法会在类的对象被实例化(Instantiated)时立即运行。这一方法可以对任何你想进行操作的目标对象进行初始化(Initialization)操作。
class Person:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello world', self.name)

Hello world Hello world

p = Person('Hello world')
p.say_hi()


class Robot:
"""This is a robot with a name"""

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

def say_hi(self):
print('Hello world, I am ', self.name)

@classmethod
def how_many(cls):
print('We have {:d} robots.'.format(cls.population))

d1 = Robot("R2-D2")
d1.say_hi()
Robot.how_many()

d2 = Robot("C-2P0")
d2.say_hi()
Robot.how_many()

d1.die()
d2.die()
Robot.how_many()

(InitializingR2-D2)
Hello world, I am R2-D2
We have 1 robots.
(InitializingC-2P0)
Hello world, I am C-2P0
We have 2 robots.
R2-D2 is being destroyed
C-2P0 is being destroyed
We have 0 robots.
所有的类成员都是公开的。但有一个例外:如果你使用数据成员并在其名字中使用双下划线作为前缀,形成诸如 __privatevar 这样的形式,
Python 会使用名称调整(Name-mangling)来使其有效地成为一个私有变量。
因此,你需要遵循这样的约定:任何在类或对象之中使用的变量其命名应以下划线开头,其它所有非此格式的名称都将是公开的,并可以为其它任何类或对象所使用。

继承
class SchoolMember:
'''代表任何学校里的成员。'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {})'.format(self.name))

def tell(self):
'''告诉我有关我的细节。'''
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")


class Teacher(SchoolMember):
'''代表一位老师。'''
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(SchoolMember):
'''代表一位学生。'''
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. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)

# 打印一行空白行
print()

members = [t, s]
for member in members:

我们可以通过使用 try..except 来处理异常状况。一般来说我们会把通常的语句放在 try 代码块中,将我们的错误处理器代码放置在 except 代码块中。
try:
text = input('Enter something --> ')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {}'.format(text))

抛出异常
你能够引发的错误或异常必须是直接或间接从属于 Exception(异常) 类的派生类。
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)

Enter something --> a
ShortInputException: The input was 1 long, expected at least 3

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.txt")
except KeyboardInterrupt:
print("!! You cancelled the reading from the file.")
finally:
if f:
f.close()
print("(Cleaning up: Closed the file)")

 


# 对全体师生工作
member.tell()

# 打开文件以编辑('w'riting)
f = open('poem.txt', 'w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close()
我们使用内置的 open 函数并指定文件名以及我们所希望使用的打开模式来打开一个文件。
打开模式可以是阅读模式('r'),写入模式('w')和追加模式('a')。我们还可以选择是通过文本模式('t')还是二进制模式('b')来读取、写入或追加文本。

__init__(self, ...)
这一方法在新创建的对象被返回准备使用时被调用。
__del__(self)
这一方法在对象被删除之前调用(它的使用时机不可预测,所以避免使用它)
__str__(self)
当我们使用 print 函数时,或 str() 被使用时就会被调用。单语句块
__lt__(self, other)
当小于运算符(<)被使用时被调用。类似地,使用其它所有运算符(+、> 等等)时都会有特殊方法被调用。
__getitem__(self, key)
使用 x[key] 索引操作时会被调用。
__len__(self)
当针对序列对象使用内置 len() 函数时会被调用

单语句块
如果你的语句块只包括单独的一句语句,那么你可以在同一行指定它,例如条件语句与循环语句。
if flag: print('Yes')

 

猜你喜欢

转载自www.cnblogs.com/shuizhidao/p/9648880.html
今日推荐