写在前面
作者是一名前端开发,站在前端开发角度开始学习。所以比较适合前端同学阅读。
练习使用编辑器Mu
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 数据类型
| 数据类型 | 例子 |
|---|---|
| 整数 | -2、-1、0、1、2 |
| 浮点数 | -1.23、-1.0、0.0、1.0、1.23 |
| 字符串 | 'a'、'ab'、'1' |
1.3 字符串连接和复制
'Alice' + 'Bob'
# 'AliceBob'
'Alice' * 2
# 'AliceAlice'
1.4 变量名和赋值操作
spam = 40
print(spam)
eggs = 2
print(spam + eggs)
1.5 注释和内部函数
注释使用 # 内容表示
# This program says hello and asks for my name
- print()
print('hello world!')
- input()
myName = input()
print(myName)
- len()
print(len('111')) # 3
- str()
print(str(29)) # '29'
- int()
print(int('42')) # 42
- float()
print(float('3.14')) # 3.14
print(float(10)) # 10.0
2. 控制流
2.1 布尔值
True、False
2.2 比较操作符
| 操作符 | 含义 |
|---|---|
| == | 等于 |
| != | 不等于 |
| < | 小于 |
| > | 大于 |
| <= | 小于等于 |
| >= | 大于等于 |
2.3 布尔操作符
and 相当于 && or 相当于 || not 布尔值取反 相当于 !
2.4 控制流的元素
- 条件
if 条件:
else if 条件:
else:
注意这里条件书写缩进
name = 'gong'
password = '1234'
if name == 'gong':
print('Hello, gong')
if password == '123':
print('123')
else:
print('errors')
- while循环语句
spam = 0
while span < 5
print('hello world')
spam = spam + 1
- break
停止运行中循环
- continue
跳过一次循环
- for 和 range()
for i in range(5):
print(i)
range(): 获取3个参数,参1:数值起始、参2:数值结束、参3:数值增长值
2.5 导入模块
注意:在python文件命名时不要使用关键词,例如:random.py
# 引入多个用逗号隔开
import random, sys, os, math
# from random import * # 使用此方法引入可以直接使用randint(),但不推荐使用,不便于代码阅读
for i in range(5):
print(random.randint(1, 10))
2.6 sys.exit()函数提前结束程序
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
2.7 实战---小程序:猜数字
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a nubmer between 1 an 20')
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess > secretNumber:
print('Your guess is too high')
continue
elif guess < secretNumber:
print('Your guess is too low')
continue
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
break
else:
print('Nope. The number I was thinkung of was ' + str(secretNumber))
break
2.8 实战---小程序:剪刀、石头、布
import sys, random
print('SCISSORS, ROCK, CLOTH')
wins = 0
losses = 0
ties = 0
while True:
print('%s Wins, %s Losses, %s Ties' % (wins, losses, ties))
while True:
print('Enter your move: (s)cissors (r)ock (c)loth or (q)uit')
playerMove = input()
if playerMove == 'q':
sys.exit()
elif playerMove == 's' or playerMove == 'r' or playerMove == 'c':
break
print('Type one of s, r, c or q.')
# Display what the player chose:
if playerMove == 's':
print('SCISSIRS versus...')
if playerMove == 'r':
print('ROCK versus...')
if playerMove == 'c':
print('CLOTH versus...')
# Display what the computer chose:
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerMove = 's'
print('SCISSIRS')
if randomNumber == 2:
computerMove = 'r'
print('ROCK')
if randomNumber == 3:
computerMove = 'c'
print('CLOTH')
if playerMove == computerMove:
print('It is a tie!')
elif playerMove == 'r' and computerMove == 's':
print('You win!')
wins = wins + 1
elif playerMove == 'c' and computerMove == 'r':
print('You win!')
wins = wins + 1
elif playerMove == 's' and computerMove == 'c':
print('You win!')
wins = wins + 1
else:
print('You lose!')
losses = losses + 1
3. 函数
3.1 def语句和参数、返回值return语句
none 数据类型是NoneType
def hello(name):
print('hello, ' + name)
return name + ': hello, def'
res = hello('python')
print(res)
3.2 None值
spam = print('hello, None')
None == spam # True
3.3 关键字参数和print()函数
print('hello')
print('world')
# print函数自动在传入的字符串末尾添加了换行符。可以设置end关键字参数来改变
print('hello', end = '')
print('world')
# 传入多个字符串,会自动添加空格分隔,可以设置sep关键字替换
print('cats', 'dogs', 'mice') # cats dogs mice
print('cats', 'dogs', 'mice', sep=',') # cats,dogs,mice
3.4 调用栈
def a():
print('a() starts')
b()
d()
print('a() returns')
def b():
print('b() starts')
c()
print('b() retruns')
def c():
print('c() starts')
print('c() returns')
def d():
print('d() starts')
print('d() returns')
a()
# a() starts
# b() starts
# c() starts
# c() returns
# b() returns
# d() starts
# d() returns
# a() returns
3.5 局部和全局作用域
# 1. 局部作用域不能在全局作用域使用
# ...
# 2. 局部作用域不能使用其他作用域内的变量
def spam2():
eggs2 = 99
bacon2()
print(eggs2)
def bacon2():
ham2 = 101
eggs2 = 0
spam2() # 99
# 3. 全局变量可以在局部作用域中读取
def spam3():
print(age)
age = 42
spam3() # 42
print(age)
# 4. 名称相同的局部变量和全局变量
def spam4():
eggs = 'spam local'
print(eggs) # spam local
def bacon4():
eggs = 'bacon local'
print(eggs) # bacon local
spam4()
print(eggs) # bacon local
eggs= 'global'
bacon4()
print(eggs) # global
# bacon local
# spam local
# bacon local
# global
3.6 global语句
def spam():
# global语句告诉python eggs是一个全局变量,不要在创建一个局部eggs
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs) # spam
3.7 异常处理
def spam(divideBy):
try:
return 42 / divideBy
except:
print('Error:Invaid argument')
print(spam(2)) # 21.0
print(spam(0))
# Error:Invaid argument
# None
print(spam(12)) # 3.5
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2)) # 21.0
print(spam(0)) # Error: Invalid argument.
print(spam(12)) # print(spam(12)) 未执行,一但跳转到except后,不会在执行try中代码
except:
print('Error: Invalid argument.')
3.8 小程序:Zigzag
import time, sys
indent = 0 # How many spaces to indent.
indentIncreasing = True # Whether the indentation is increasing or not.
try:
while True:
print(' ' * indent, end = '');
print('********')
time.sleep(0.01)
if indentIncreasing:
indent = indent + 1
if indent == 20:
indentIncreasing = False
else:
indent = indent - 1
if indent == 0:
indentIncreasing = True
except:
sys.exit()
3.9 collatz
# 编写一个名为collatz函数,他有一个名为number的参数。
# 如果参数是偶数,那么collatz就输出number // 2,并返回改值。
# 如果参数是奇数,collatz就输出并返回3 * number + 1
# 然后编写一个程序,让用户输入一个整数,并不断对这个数调用collatz,直到返回值为1
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
print(3 * number + 1)
return 3 * number + 1
print('请输入一个整数:')
integer = int(input())
while integer != 1:
try:
integer = collatz(integer)
except:
print('Error: collatz input error.')
4. 列表
4.1 列表数据类型
. . .(省略与javascript数组一样部分)
4.1.1 负数索引
# 负数索引从列表最后一个开始递增
spam = ['a', 'b', 'c']
spam[-1] // 'c'
spam[-2] // 'b'
4.1.2 列表切片
spam[0,3]: [起始下标,结束下标],结果不包括结束下标, 不写默认是 [0, len(spam)]
spam = ['a', 'b', 'c', 'd', 'e', 'f']
spam[0:3] # ['a', 'b', 'c']
spam[0:-1] # ['a', 'b', 'c', 'd', 'e']
spam[0:] # ['a', 'b', 'c', 'd', 'e', 'f']
spam[:3] # ['a', 'b', 'c']
spam[:] # ['a', 'b', 'c', 'd', 'e', 'f']
4.1.3 列表连接和列表复制
spam1 = ['a', 'b', 'c', 'd', 'e', 'f']
spam2 = [1, 2, 3]
print(spam1 + spam2) # ['a', 'b', 'c', 'd', 'e', 'f', 1, 2, 3]
print(spam2 * 2) # ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f']
4.1.4 del语句
spam1 = ['a', 'b', 'c', 'd', 'e', 'f']
del spam1[1]
print(spam1) # ['a', 'c', 'd', 'e', 'f']
4.2 使用列表
4.2.1 in和not in
'howdy' in ['hello', 'hi', 'howdy', 'heyas'] # True
'cats' in ['hello', 'hi', 'howdy', 'heyas'] # False
4.2.2 多重赋值技巧
cat = ['fat', 'black', 'loud']
size, color, disposition = cat
print(size, color, disposition) # 'fat', 'black', 'loud'
4.2.3 enumerate()函数与列表一起使用
supplies = ['pens', 'staplers', 'binders']
for index, item in enumerate(supplies):
print(index, item)
# 0 pens
# 1 staplers
# 2 binders
4.2.4 random.choice 和 random.shuffle
import random
pets = ['Dog', 'Cat', 'Moose']
# 随机函数
random.choice(pets)
random.choice(pets)
random.choice(pets)
# 原列表随机排序
random.shuffle(pets)
print(pets)
random.shuffle(pets)
print(pets)
random.shuffle(pets)
print(pets)
4.3 列表原生方法
spam = ['hello', 'hi', 'howdy', 'heyas']
spam.index('hi') # 1 根据列表值获取指定项下标
spam.append('hi2') # 向原列表最后面添加值
print(spam) # ['hello', 'hi', 'howdy', 'heyas', 'hi2']
spam.insert(1, 'haha') # 向列表指定下标元素前插入值
print(spam) # ['hello', 'haha', 'hi', 'howdy', 'heyas', 'hi2']
spam.remove('hello') # 删除列表中指定项
print(spam) # ['haha', 'hi', 'howdy', 'heyas', 'hi2']
spam.sort() # 排序
print(spam) # ['haha', 'heyas', 'hi', 'hi3', 'howdy']
spam.reverse() # 反转
print(spam) # ['howdy', 'hi3', 'hi', 'heyas', 'haha']
4.4 元组数据类型
eggs = ('hello', 1, 0.5)
eggs[0] # 'hello'
type(eggs) # type()判断类型 <class 'tuple'>
4.4.1 用list()和tuple()函数来转换类型
tuple(['hello', 1, 0.5]) # ('hello', 1, 0.5)
list(('hello', 1, 0.5)) # ['hello', 1, 0.5]
list('hello') # ['h', 'e', 'l', 'l', 'o']
4.5 引用
引用类型...
4.5.1 标识和id()函数
# 在内存中创建'Howdy'字符串,返回存储字符串的数字内存地址
id('Howdy') # 2815971417904
spam = ['hello', 1, 0.5]
spam2 = spam
spam3 = ['world', 2, 0.6]
id(spam) # 2316173112320
id(spam2) # 2316173112320
id(spam3) # 2504695149952
4.5.2 copy模块的copy()和deepcopy()函数
import copy
spam = ['A', 'B', 'C', 'D']
spam2 = copy.copy(spam)
id(spam) # 3074513356992
id(spam2) # 3074513287040
spam3 = [[1,2],1]
spam4 = copy.copy(spam3)
spam5 = copy.deepcopy(spam3)
id(spam3[0]) # 2047358257536
id(spam4[0]) # 2047358257536
id(spam5[0]) # 2047358257024
4.6 小程序:Conway的生命游戏
import random, time, copy
WIDTH = 60
HEIGHT = 20
nextCells = []
for x in range(WIDTH):
column = []
for y in range(HEIGHT):
# if random.randint(0, 1) == 0:
if (x, y) in ((1, 0), (2, 1), (0, 2), (1, 2), (2, 2)):
column.append('#')
else:
column.append(' ')
nextCells.append(column)
while True:
print('\n\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end = '')
print() # Print a newline at the end of the row.
for x in range(WIDTH):
for y in range(HEIGHT):
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[leftCoord][y] == '#':
numNeighbors += 1
if currentCells[rightCoord][y] == '#':
numNeighbors += 1
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][belowCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y] = '#'
else:
nextCells[x][y] = ' '
time.sleep(1)
4.7 项目实战
4.7.1 逗号代码
def fn(arr):
s = ''
for item in arr:
if (s == ''):
s = item
else:
s += (', ' + item)
return s
a = fn(['apples', 'bananas', 'tofu', 'cats'])
4.7.2 掷硬币连胜
import random
numberOfSteaks = 0
t = 'TTTTTT'
h = 'HHHHHH'
def getOneGroup():
countStr = ''
for num in range(100):
rNum = random.randint(0, 1)
if (rNum == 0): # 反面
countStr += 'T'
else: # 正面
countStr += 'H'
return countStr
for experimentNumber in range(10):
s = getOneGroup()
if t in s:
numberOfSteaks += 1
if h in s:
numberOfSteaks += 1
print('Chance of streak: %s%%' % (numberOfSteaks / 100)) # Chance of streak: 0.16%
4.7.3 字符图网络
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
for i in range(len(grid[0])):
for j in range(len(grid)):
print(grid[j][i], end = '')
print()
后续待更新中...