Python 基础速查笔记,摘自 《Python 编程快速上手》

目录

1. Python 基础

1.1 数学操作符

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

1.2 数据类型

数据类型 例子
整型 int 86
浮点型 float 3.14159
字符串 str 'Abel Su'

1.3 字符串连接和复制

>>> 'Abel' + 'Su'
'AbelSu'
>>> 'abel' * 5
'abelabelabelabelabel'

1.4 在变量中保存值

>>> name = 'Abel'
>>> name
'Abel'
>>> name = 'Yuki'
'Yuki'

1.5 变量名

  • 只能是一个词
  • 只能包含字母、数字、下划线
  • 不能以数字开头

1.6 常用函数

#!/usr/local/bin/python3
print('Hello Python!')
print("What's your name?") # waiting for input
name = input()
print('The length of your name is: ' + str(len(name)))
  • print()打印
  • input()读取输入
  • len()返回长度
  • str()转换为字符串
  • int()截断取整
  • float()转换为浮点数

2. 控制流

2.1 布尔值

首字母大写

  • True
  • False

2.2 操作符

# 比较操作符
==
!=
<
>
<=
>=
# 布尔操作符
and
or
not

2.3 if / else / elif

#!/usr/local/bin/python3
if name == 'Alice':
    print('Hi, Alice.')
elif age < 12:
    print('You are not Alice, kiddo.')
elif age > 2000:
    print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
    print('You are not Alice, grannie.')
else:
    print('You are neither Alice nor a little kid')

2.4 while / break / continue

#!/usr/local/bin/python3
name = ''
while name != 'your name':
    print('Please type your name')
    name = input()
print('Thank you!')

也可以用break跳出当前循环

#!/usr/local/bin/python3
name = ''
while True:
    print('Please type your name')
    name = input()
    if name == 'your name':
        break
print('Thank you!')

还可以用continue跳过之后的语句,进入下一次循环

#!/usr/local/bin/python3
while True:
    print('Who are you?')
    name = input()
    if name != 'Joe':
        continue
    print('Hello, Joe. What is the password?')
    password = input()
    if password == 'swordfish':
        break
print('Access granted.')

2.5 for / range

range()三个参数分别为:起始停止步长

#!/usr/local/bin/python3
for i in range(0, 10, 2):
    print(i)

2.6 import / from import

#!/usr/local/bin/python3
import random

for i in range(5):
    print(random.randint(1, 10))

或者使用from import语句,此时调用randint函数不需要random.前缀

#!/usr/local/bin/python3
from random import *

for i in range(5):
    print(randint(1, 10))

2.7 sys.exit()

调用sys.exit()函数,可以让程序提前终止

#!/usr/local/bin/python3
import sys

while True:
    print('Type exit to exit')
    response = input()
    if response == 'exit':
        sys.exit()
    print('You typed ' + response + '.')

3. 函数

3.1 def 语句和参数

#!/usr/local/bin/python3
def hello(name):
    print('Hello ' + name)

hello('Alice')
hello('Bob')

3.2 return 语句和返回值

#!/usr/local/bin/python3
import random

def getAnswer(answerNumber):
    if answerNumber == 1:
        return 'It is certain'
    elif answerNumber == 2:
        return 'It is decidedly so'
    elif answerNumber == 3:
        return 'Yes'
    elif answerNumber == 4:
        return 'Reply hazy try again'
    elif answerNumber == 5:
        return 'Ask again later'
    elif answerNumber == 6:
        return 'Concentrate and ask again'
    elif answerNumber == 7:
        return 'My reply is no'
    elif answerNumber == 8:
        return 'Outlook not so good'
    elif answerNumber == 9:
        return 'Very doubtful'

r = random.randint(1, 9)
fortune = getAnswer(r)
print(fortune)

3.3 None 值

None值是NoneType数据类型的唯一值。

  • 对于所有没有return语句的函数定义,Python 都会在末尾加上return None
  • 如果return语句不带返回值,也会默认返回None

这类似于whilefor循环隐式的以continue语句结尾

>>> spam = print('Hello')
Hello
>>> None == spam
True

3.4 print() 和关键字参数

print()函数默认在行末打印换行,可以设置end关键字参数替换行末的换行符:

>>> print('Hello', end=' ')
Hello >>>

如果向print()传入多个字符串值,则该函数会自动的用一个空格来分隔它们:

>>> print('Arsenal', 'Chelsea', 'Liverpool')
Arsenal Chelsea Liverpool

传入sep关键字参数,替换默认的分隔字符串

>>> print('Arsenal', 'Chelsea', 'Liverpool', sep=',')
Arsenal,Chelsea,Liverpool

3.5 global 语句

如果需要在一个函数内修改全局变量,则使用global语句

#!/usr/local/bin/python3
def spam():
    global eggs
    eggs = 'spam'

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

3.6 异常处理

#!/usr/local/bin/python3
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

4. 列表

5. 字典和结构化数据

6. 字符串操作

更新中…

参考文章

  1. 《Python 编程快速上手》