欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

笔记_简明Python教程_Byte_of_Python

程序员文章站 2022-04-12 16:33:30
1. 局部变量、全局变量 局部变量: Change local x to 2x is still 50 全局变量: x is 50Change global x to 2Value of x is 2 2. 带默认值的参数,关键字参数 a is 3 and b is 5 and c is 10a i ......

 

1. 局部变量、全局变量

  局部变量:

1 x = 50
2 def func(x):
3     x = 2
4     print('Change local x to',x)
5 
6 func(x)
7 print('x is still',x)
输出:

Change local x to 2
x is still 50

 

  全局变量:

 1 x = 50
 2 def func():
 3     global x
 4 
 5     print('x is',x)
 6     x = 2
 7     print('Change global x to',x)
 8 
 9 func()
10 print('Value of x is',x)

输出:

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

 

 

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

1 def func(a, b=5, c=10):
2     print('a is',a, 'and b is', b, 'and c is', c)
3 
4 func(3)
5 func(25, c=7)
6 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

 1 # ========list 列表[]=========
 2 # ds_using_list
 3 shoplist = ['apple', 'mango', 'carrot', 'banana']
 4 
 5 print('I have', len(shoplist), 'items to purchase.')
 6 
 7 print('These items are:', end=' ')
 8 for item in shoplist:
 9     print(item, end=' ')
10 
11 #append
12 print('\nI also have to buy rice.')
13 shoplist.append('rice')             #list.append此函数用来在list末尾添加元素
14 print('My shop list is now:', shoplist)
15 
16 #sort
17 print('I will sort my list now.')
18 shoplist.sort()                     #sort排序
19 print('Sorted shop list is', shoplist)
20 
21 # how to del from list
22 print('The first item I will buy is', shoplist[0])
23 olditem = shoplist[0]
24 del shoplist[0]
25 print('I bought the', olditem)
26 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. 元组

 1 # =========tuple 元组()========
 2 # ds_using_tuple
 3 zoo = ('python', 'tiger', 'elephant')
 4 print('Number of animals in the zoo is', len(zoo))
 5 
 6 new_zoo = 'monkey', 'camel', zoo
 7 print('Number of CAGES in the new zoo is', len(new_zoo))
 8 print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
 9 print('All the animals in new zoo are', new_zoo)
10 print('Animals brought from the old zoo is', new_zoo[2])
11 print('Last animal brought from old zoo is', new_zoo[2][2])
12 
13 # 包含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. 字典

 1 # =========dict 字典{:}==========
 2 # ds_using_dict
 3 #ab is address book
 4 ab = {
 5     'Swaroop': 'swaroop@swaroopch.com',
 6     'Larry': 'larry@wall.org',
 7     'Matsumoto': 'matz@ruby-lang.org',
 8     'Spammer': 'spammer@hotmail.com'
 9 }
10 
11 print("Swaroop's address is", ab['Swaroop'])
12 
13 #delete a key
14 del ab['Spammer']
15 
16 print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
17 #format前是“点”(.)
18 
19 #add a key
20 ab['Guido'] = 'guido@python.org'
21 
22 if 'Guido' in ab:
23     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. 序列

 1 # =============序列(列表、元组、字符串都是序列Sequence的一种)=============
 2 # 序列的主要功能是资格测试(也就是in与not in表达式)和索引操作
 3 # 列表、元组和字符串(序列的三种形态),同样拥有切片运算符,它允许我们对序列切片(获得序列中的一部分)
 4 # ds_seq
 5 shoplist = ['apple', 'mango', 'carrot', 'banana']
 6 name = 'LeonardoDiCaprio'
 7 
 8 # 索引或“下标”操作符
 9 print('Item 0 is', shoplist[0])
10 print('Item 1 is', shoplist[1])
11 print('Item 2 is', shoplist[2])
12 print('Item 3 is', shoplist[3])
13 print('Item -1 is', shoplist[-1])
14 print('Item -2 is', shoplist[-2])
15 # 索引为负值,表示倒序索引
16 print('Character 0 is', name[0])
17 
18 #对list切片
19 print('shoplist:',shoplist)
20 print('Item 1 to 3 is', shoplist[1:3])
21 print('Item 2 to end is', shoplist[2:])
22 print('Item 1 to -1 is', shoplist[1:-1])
23 print('Item start to end is', shoplist[:])
24 
25 #对字符串切片
26 print('name:', name)
27 print('characters 1 to 3 is', name[1:3])
28 print('characters 2 to end is', name[2:])
29 print('characters 1 to -1 is', name[1:-1])
30 print('characters start to end is', name[:])
31 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. 集合

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

True
False

 

 

8. 引用

 1 # Reference引用
 2 #ds_reference
 3 print('Simple Assignment')
 4 shoplist = ['apple', 'mango', 'carrot', 'banana']
 5 # mylist是指向同一对象的另一种名称
 6 mylist = shoplist
 7 
 8 # delete 0
 9 del shoplist[0]
10 
11 print('shoplist is', shoplist)
12 print('mylist is', mylist)
13 if 'apple' in mylist:
14     print('mylist is different with shoplist')
15 else:
16     print('mylist is the same list with shoplist')
17 
18 print('Copy by making a full slice')
19 # 通过生成一份完整的切片,制作一份列表的副本
20 mylist = shoplist[:]
21 del mylist[0]
22 
23 print('shoplist is', shoplist)
24 print('mylist is', mylist)
25 if shoplist[0] not in mylist:
26     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. 列表推导

1 # 列表推导
2 listone = [2, 3, 4]
3 listtwo = [2*i for i in listone if i>2]
4 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所列出的其中一个目录下。

1 def say_hi():
2     '''This is my module
3     I'm learning to coding my own module
4     导入模块,则必须在相同目录下,或者把模块放置在sys.path所列出的其中一个目录下
5     '''
6     print('Hi, this is mymodule speaking.')
7 
8 __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. 继承

 1 # 继承
 2 # 基类和派生类/超类和子类
 3 
 4 # coding = UTF-8
 5 
 6 class SchoolMember:
 7     '''代表任何学校里的成员。'''
 8     def __init__(self, name, age):
 9         self.name = name
10         self.age = age
11         print('(Initialized SchoolMember:{})'.format(self.name))
12 
13     def tell(self):
14         '''tell me about detail'''
15         print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
16 
17 
18 class Teacher:
19     '''代表一位老师'''
20     def __init__(self, name, age, salary):
21         SchoolMember.__init__(self, name, age)
22         self.salary = salary
23         print('(Initialized Teacher: {})'.format(self.name))
24 
25     def tell(self):
26         SchoolMember.tell(self)
27         print('Salary:"{:d}"'.format(self.salary))
28 
29 
30 class Student:
31     '''代表一位学生'''
32     def __init__(self, name, age, marks):
33         SchoolMember.__init__(self, name, age)
34         self.marks = marks
35         print('(Initialized Student: {})'.format(self.name))
36 
37     def tell(self):
38         SchoolMember.tell(self)
39         print('Marks: "{:d}"'.format(self.marks))
40 
41 
42 # 实例化
43 t = Teacher('Mrs.Xiang', 21, 12000)
44 s = Student('NemoWang', 22, 87)
45 
46 print()
47 
48 members = [t, s]
49 for member in members:
50     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 ,将返回翻转过的文本。

 1 # 输入与输出
 2 # 做到忽略大小写,空格,标点符号
 3 import string
 4 
 5 def reverse(text):
 6     return text[::-1]
 7 
 8 def is_palindrome(text):    #回文
 9     return text == reverse(text)
10 
11 
12 something = input("Enter text: ")
13 # 忽略大小写
14 something = something.lower()
15 # 忽略空格(将空格替换)
16 something = something.replace(' ','')
17 # 忽略标点符号
18 for char in string.punctuation:
19     something = something.replace(char,'')
20 # 利用string.punctuation来表示中文标点符号是不行的
21 
22 
23 if is_palindrome(something):
24     print("yse, it is a palindrome.")
25 else:
26     print("No, it is not a palindrome.")
27     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)存储对象

 1 import pickle
 2 
 3 # The name of the file where we will store the object
 4 shoplistfile = 'shoplist.data'
 5 # The list of things to buy
 6 shoplist = ['banana', 'apple', 'orange', 'mango']
 7 
 8 # Write to the file
 9 # 以写入二进制模式打开文件
10 f = open(shoplistfile, 'wb')
11 # Dump the object to a file
12 pickle.dump(shoplist, f)    #dump卸载(存储)数据
13 f.close()
14 
15 # Destroy the shoplist variable
16 del shoplist
17 
18 # Read back from the storage
19 f = open(shoplistfile, 'rb')
20 # Load the object from the file
21 storedlist = pickle.load(f) #load装载(加载)数据
22 print(storedlist)
输出:
['banana', 'apple', 'orange', 'mango']

 

 

17. 异常

  抛出异常

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

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

 1 # encoding = UTF-8
 2 
 3 class ShortInputException(Exception):
 4     '''一个由用户定义的异常类'''
 5     def __init__(self, length, atleast):
 6         Exception.__init__(self)
 7         self.length = length
 8         self.atleast = atleast
 9 
10 try:
11     text = input('Enter something -->')
12     if len(text) < 3:
13         raise ShortInputException(len(text), 3)
14 
15 except EOFError:
16     print('Why did you do an EOF on me?')
17 except ShortInputException as ex:
18     print(('ShortInputException: The input was'+
19           ' {0} long, expected at least {1}.')
20           .format(ex.length, ex.atleast))
21 else:
22     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语句。

 1 import sys
 2 import time
 3 
 4 f = None
 5 try :
 6     f = open('poem.txt')
 7     # 我们常用的阅读风格
 8     while True:
 9         line = f.readline()
10         if len(line) == 0:
11             break
12         print(line, end='')
13         sys.stdout.flush()
14         print("Press ctrl+c now")
15         # 确保它能运行一段时间
16         # 每打印一行后插入两秒休眠
17         time.sleep(2)
18 except IOError:
19     print('Could not find file poem.exe')
20 except KeyboardInterrupt:
21     print('!!You cancelled the reading from the file.')
22 finally:
23     if f:
24         f.close()
25     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来自动完成

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

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