Python杂笔1

2020-05-09  本文已影响0人  ayusong870

PS:以下内容针对python3

1. 数学操作符,优先级由高到低:

操作符 操作 例子 求值为
** 指数 2 ** 3 8
% 取模/取余数 22 % 8 6
// 整除/商数取整 22 // 8 2
/ 除法 22 / 8 2.75
* 乘法 3 * 5 15
- 减法 5 - 2 3
+ 加法 2 + 2 4

2. input()函数:

函数等待用户在键盘上输入一些文本,并按下回车键。 

myName = input() 

3. IF控制语句:

if name == 'Mary':
      print('Hello Mary') 
if password == 'swordfish':
      print('Access granted.') 
elif age < 12:
      print('You are not Alice, kiddo.') 
else:
      print('Wrong password.')

4. While循环语句

spam = 0 
while spam < 5:
     print('Hello, world.')
     spam = spam + 1 
name = ''
while name != 'your name':
     print('Please type your name.')
     name = input()
print('Thank you!')  

5. For循环和range语句:

print('My name is')
for i in range(5):
     print('Jimmy Five Times (' + str(i) + ')') 
for i in range(12, 16):
     print(i)
for i in range(0, 10, 2):
     print(i)
for i in range(5, -1, -1):
     print(i)

6. 函数定义:

def hello(name):
      print('Hello ' + name) 
hello()

7. global语句:

如果需要在一个函数内修改全局变量,就使用 global 语句。如果在函数的顶部有global eggs 这样的代码,它就告诉 Python,“ 在这个函数中,eggs 指的是全局变量,所以不要用这个名字创建一个局部变量。”例如:

def spam():
     global eggs
     eggs = 'spam'
eggs = 'global' 
spam() 
print(eggs)  

8. 异常处理:

def spam(divideBy):
     try:
         return 42 / divideBy
     except ZeroDivisionError:
         print('Error: Invalid argument.')  
print(spam(2))
print(spam(12))
print(spam(0)) 
print(spam(1) 
21.0
3.5
Error: Invalid argument. 
None
42.0

9. 列表:

>>> [1, 2, 3]
[1, 2, 3] 
>>> ['cat', 'bat', 'rat', 'elephant'] 
['cat', 'bat', 'rat', 'elephant']
>>> ['hello', 3.1415, True, None, 42] 
['hello', 3.1415, True, None, 42]  
>>> spam = ['cat', 'bat', 'rat', 'elephant'] 
>>> spam 
['cat', 'bat', 'rat', 'elephant']

下标

>>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] 
>>> spam[0] 
['cat', 'bat'] 
>>> spam[0][1] 
'bat' 
>>> spam[1][4] 
50 

负下标:

>>> spam = ['cat', 'bat', 'rat', 'elephant'] 
>>> spam[-1] 
'elephant' 
>>> spam[-3] 
'bat'

切片:

>>> spam = ['cat', 'bat', 'rat', 'elephant'] 
>>> spam[0:4] 
['cat', 'bat', 'rat', 'elephant'] 
>>> spam[1:3] 
['bat', 'rat']
 >>> spam[0:-1]
['cat', 'bat', 'rat']
>>> spam = ['cat', 'bat', 'rat', 'elephant'] 
>>> spam[:2] 
['cat', 'bat'] 
>>> spam[1:] 
['bat', 'rat', 'elephant'] 
>>> spam[:] 
['cat', 'bat', 'rat', 'elephant']

连接复制:

>>> [1, 2, 3] + ['A', 'B', 'C'] 
[1, 2,  3,  'A',  'B',  'C'] 
>>> ['X', 'Y', 'Z'] * 3 
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z'] 
>>> spam = [1, 2, 3] 
>>> spam = spam + ['A', 'B', 'C'] 
>>> spam 
[1, 2, 3, 'A', 'B', 'C']

删除

>>> spam = ['cat', 'bat', 'rat', 'elephant'] 
>>> del spam[2] 
>>> spam 
['cat', 'bat', 'elephant'] 
>>> del spam[2] 
>>> spam
 ['cat', 'bat']

In和not in

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas'] 
True
>>> 'howdy' not in ['hello', 'hi', 'howdy', 'heyas']
False 

多重赋值:

>>> cat = ['fat', 'black', 'loud'] 
>>> size, color, disposition = cat

增强的赋值操作符

增强的赋值语句 等价的赋值语句
spam += 1 spam = spam + 1
spam -= 1 spam = spam - 1
spam *= 1 spam = spam * 1
spam /= 1 spam = spam / 1
spam %= 1 spam = spam % 1

Index方法:

>>> spam = ['hello', 'hi', 'howdy', 'heyas'] 
>>> spam.index('hello') 
0    

用 list()和 tuple()函数来转换类:

>>> tuple(['cat', 'dog', 5]) 
('cat', 'dog', 5) 
>>> list(('cat', 'dog', 5)) 
['cat', 'dog', 5] 
>>> list('hello') 
['h', 'e', 'l', 'l', 'o']   

引用:

>>> spam = [0, 1, 2, 3, 4, 5]
>>> cheese = spam
>>> cheese[1] = 'Hello!' 
>>> spam 
[0, 'Hello!', 2, 3, 4, 5] 
>>> cheese
[0, 'Hello!', 2, 3, 4, 5] 

** copy 模块的 copy()和 deepcopy()函数:**

>>> import copy 
>>> spam = ['A', 'B', 'C', 'D'] 
>>> cheese = copy.copy(spam) 
>>> cheese[1] = 42
 >>> spam 
['A', 'B', 'C', 'D'] 
>>> cheese 
['A', 42, 'C', 'D'] 

deepcopy将复制列表中包含的列表

10. 字典类型数据:

>>> myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'} 
>>> myCat['size'] 'fat' 
>>> 'My cat has ' + myCat['color'] + ' fur.' 
'My cat has gray fur.' 

** keys()、values()和 items()方法 **

>>> spam = {'color': 'red', 'age': 42} 
>>> for v in spam.values():
         print(v)  
red 
42  
>>> for k in spam.keys():
         print(k)  
color 
Age
 >>> for i in spam.items():
         print(i)  
('color', 'red') 
('age', 42) 

字典的get方法:

>>> picnicItems = {'apples': 5, 'cups': 2} 
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.' 
'I am bringing 2 cups.' 
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.' 
'I am bringing 0 eggs.'

字典的setdefault()方法

>>> spam = {'name': 'Pooka', 'age': 5} 
>>> spam.setdefault('color', 'black') 
'black' 
>>> spam 
{'color': 'black', 'age': 5, 'name': 'Pooka'} 
>>> spam.setdefault('color', 'white') 
'black'
 >>> spam {'color': 'black', 'age': 5, 'name': 'Pooka'} 

漂亮打印
如果程序中导入 pprint 模块,就可以使用 pprint()和pformat()函数,它们将“漂亮 打印”一个字典的字。如果想要字典中表项的显示比 print()的输出结果更干净,这就有用了。

import pprint 
message = 'It was a bright cold day in April, and the clocks were striking thirteen.' 
count = {}  
for character in message:
     count.setdefault(character, 0)
     count[character] = count[character] + 1  
pprint.pprint(count)

当程序运行时,输出看起来更干净,键排过序。

{' ': 13, 
 ',': 1, 
 '.': 1, 
 'A': 1, 
 'I': 1, 
 'a': 4, 
 'b': 1, 
 'c': 3, 
 'd': 3, 
 'e': 5, 
 'g': 2, 
 'h': 3, 
 'i': 6, 
 'k': 2, 
 'l': 3, 
 'n': 4, 
 'o': 2,  
 'p': 1, 
 'r': 5, 
 's': 3, 
 't': 6, 
 'w': 2, 
 'y': 1}  

如果字典本身包含嵌套的列表或字典,pprint.pprint()函数就特别有用。如果希望得到漂亮打印的文本作为字符串,而不是显示在屏幕上,那就调用 pprint.pformat()。下面两行代码是等价的:

pprint.pprint(someDictionaryValue)
print(pprint.pformat(someDictionaryValue)) 

11. Public,private,protect

java的顶级对象是类,所有的权限都是相对于类(对象)的成员变量/方法来说的,但Python的顶级对象还包括变量和函数,所以权限就有点不一样了。在类中,默认的是public,私有的在前面加两个下划线,保护的加一个下划线。

上一篇 下一篇

猜你喜欢

热点阅读