文章目录
对于熟练 C 语言和 C# 语言的来说,python 很简单,但不是特别习惯。
windows Python 安装路径:
进入 cmd ,命令: where python
1. print & input
# 字符串可以运算
print('*' * 10)
# 输出: **********
name = input('what is your name ')
print(name)
course = '''
Hi
xhr !'''
print(course[0]) # 输出了换行
print(course[1]) # 输出 H
print(course[-1]) # 输出 !
course = 'abcdefghijklmn'
print(course[3:6]) # 输出 def [3,6)
print(course[3:]) # 输出 defghijklmn [3,+∞)
print(course[:3]) # 输出 abc [0,3)
print(course[1:-1]) # 输出 bcdefghijklm [1,-1)
course = 'abcdefghijklmn'
another = course[:]
print(another) # 输出 abcdefghijklmn
2. 类型转换
year = int(input('year: '))
print(2020 - year)
print(type(year))
3. string
name = 'xhr'
sex = 'man'
msg = f'{name} [{sex}] is a coder'
print(msg) # xhr [man] is a coder
msg = 'xhr is a coder'
print(msg.split()) # ['xhr', 'is', 'a', 'coder']
print(len(msg)) # 14
print(msg.upper()) # XHR IS A CODER
print(msg.find('is')) # 4
print(msg.replace('is', 'was')) # xhr was a coder
print('was' in msg) # False
4. 运算
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
print(10 ** 3) # 1000 幂运算
四舍六入 五成双
print(round(2.9)) # 3
print(round(2.5)) # 2
print(round(3.5)) # 4
import math
print(math.ceil(2.1)) # 3
print(math.floor(2.9)) # 2
5. if & elif & else
temperature = 18
if temperature > 40:
print("hot day")
print("swim")
elif temperature < 15:
print("cold day")
print("sleep")
else:
print("good day")
if (temperature > 15) and (temperature < 25):
print("have fun")
# && -> and
# || -> or
# ! -> not
6. 循环
6.1 while loop
python 的 while 居然有 else ,好像还挺有用,如果提前退出循环不会执行 else ,循环正常退出执行 else。
i = 1
while i <= 5:
print(i * '*')
i += 1
if i > 3:
break
else:
print('Done')
6.2 for loop
类似 C# 的 foreach,range 函数左闭右开 [5,10),返回类似 C# 迭代器的对象。
for item in ['xhr1', 'xhr2', 'xhr3']:
print(item)
for item in range(5, 10):
print(item)
for item in range(5, 10, 2): # 5 7 9
print(item)
7. list
7.1 一维链表
不知道 python 官方翻译是啥,还是叫链表顺口。
names = ['xhr', 'ly', 5, 3.14]
print(names)
# 输出 :
# ['xhr', 'ly', 5, 3.14]
print(names[0]) # xhr
print(names[3]) # 3.14
print(names[-2]) # 5
print(names[1:3]) # ['ly', 5]
常用方法
nums = [5, 4, 1, 7]
nums2 = nums.copy()
nums.append(20)
print(nums) # [5, 4, 1, 7, 20]
nums.insert(0, 30) # (index, obj)
print(nums) # [30, 5, 4, 1, 7, 20]
nums.remove(5)
print(nums) # [30, 4, 1, 7, 20]
print(nums.index(7)) # 3
print(nums.pop()) # 20
print(nums) # [30, 4, 1, 7]
nums.sort()
print(nums) # [1, 4, 7, 30]
nums.reverse()
print(nums) # [30, 7, 4, 1]
print(nums2) # [5, 4, 1, 7]
如果对象不在链表中,使用链表的 index 方法会导致错误,所以用下面这个方法来查找链表中是否存在某对象比较安全:
nums = [1, 2, 3, 5]
print(4 in nums) # False
print(4 not in nums) # True
7.2 二维链表
matrix = [
['xhr', 2, 3],
['jay', 5, 6, 555],
[7, 'ly', 9],
]
print(matrix[0][0]) # xhr
print(matrix[1][0]) # jay
print(matrix[1][1]) # 5
print(matrix[1][3]) # 555
for row in matrix:
for item in row:
print(item)
8. tuple
类似数组,但是也不一样,不能对元组进行任何修改。
nums = (1, 'xhr', 3, 5)
print(nums) # (1, 'xhr', 3, 5)
9. unpacking
coordinates = (1, 2, 3)
x, y, z = coordinates
print(x) # 1
print(y) # 2
print(z) # 3
10. key value pair(dictionary)
使用 get 方法,如果不存在该 key ,不会报错,返回 None (可以提供默认值,不存在key时返回默认值)
请注意,不要像下面那样单双引号混用,这里只是测试。
customer = {
'name': 'xhr',
'money': 0,
'home': 'none',
'is_xuezha': True,
}
print(customer["name"]) # xhr
print(customer.get('xx')) # None
print(customer.get('is_xuezha')) # True
print(customer.get("xx", "xx is null")) # xx is null
customer['name'] = 'ly'
print(customer["name"]) # ly
customer['birthdate'] = '1970.1.1'
print(customer["birthdate"]) # 1970.1.1
inputs = input('your phone : ')
nums = {
1: 'one',
2: 'two',
3: 'three',
4: 'fore',
}
output = ''
for i in inputs:
output += nums.get(int(i), '?') + ' '
print(output)
# 输入: 2541
# 输出: two ? fore one
11. function
强迫症的 python 要求函数定义后要空两行,否则报警告。
def __greet_user(name):
print(f'hi {name} !')
print('in func __greet_user')
def greet_user(*user):
if len(user) == 0:
__greet_user('')
elif len(user) == 1:
__greet_user(user[0])
else:
print("fault : too many users")
greet_user('xhr')
greet_user()
def clac_cost(count, price):
return count * price
total = clac_cost(price=3.3, count=5)
print(total) # 16.5
12. try & except
输入字母,输出 ValueError
输入 0 ,输出 other except
try:
age = int(input('Age: '))
income = 10000
print(income / age)
except ValueError:
print("ValueError")
except Exception:
print("other except")
13. class
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
def draw(self):
print(f'({self.x}, {self.y})')
p1 = Point(10, 20)
p1.draw() # (10, 20)
p1.move(-5, 5)
p1.draw() # (5, 25)
14. inherit
class Animal:
def __init__(self, name):
self.name = name
def walk(self):
print(f'{self.name} is walking')
class Dog(Animal):
def __init__(self, name):
Animal.__init__(self, name)
class Cat(Animal):
def __init__(self):
super(Cat, self).__init__('cat')
dog = Dog('dog_xiaoming')
dog.walk() # dog_xiaoming is walking
cat = Cat()
cat.walk() # cat is walking
15. modules
新建一个 xhr_module.py ,一个文件就是一个模块。
def walk():
print('walk')
def sleep():
print('sleep')
在 app.py 中
import xhr_module
from xhr_module import sleep
xhr_module.walk() # walk
sleep() # sleep
16. package
一个文件夹就是一个 package,在文件夹中新建 __init__.py ,再新建其他 .py 文件。
xhr_package 是一个 package
package_test 是一个 module
pack_walk 和 pack_sleep 是 package_test 种的函数
import xhr_package.package_test
from xhr_package.package_test import pack_sleep
xhr_package.package_test.pack_walk() # pack_walk
pack_sleep() # pack_sleep
17. standard library
google “python 3 module index”
常用模块:
- datetime
- random
import random
for i in range(3):
print(random.random())
for i in range(3):
print(random.randint(10, 99))
members = ['xhr', 'ly', 'jay', 'others']
print(random.choice(members))
- pathlib
from pathlib import Path
path = Path('xhr_package')
print(path.exists()) # True
from pathlib import Path
path = Path() # 默认为当前目录
for pyfile in path.glob('*.py'): # 搜索
print(pyfile)
18. open source library
-
sms
Simple and straightforward way to send text messages -
openpyxl
A Python library to read/write Excel 2010 xlsx/xlsm files
在终端执行 pip install openpyxl,就可以导入了
import openpyxl as xl
from openpyxl.chart import BarChart, Reference
wb = xl.load_workbook('test.xlsx')
sheet = wb['Sheet1']
cell = sheet['a1']
cell = sheet.cell(1, 1)
print(cell.value)
for row in range(2, sheet.max_row + 1):
old_cell = sheet.cell(row, 3)
new_cell = sheet.cell(row, 4)
new_cell.value = old_cell.value * 0.95
ref = Reference(sheet, min_row=2,
max_row=sheet.max_row,
min_col=4, max_col=4)
chart = BarChart()
chart.add_data(ref)
sheet.add_chart(chart, 'e2')
wb.save('test2.xlsx')
python document
python 3 standard library
open source library: pypi
python