Python基础
基本用法
- 定义:test=’aa’,变量无类型
- print(‘print something’)
- input_data = input(‘input message’)
- if else
1
2
3
4if 3>= 1:
XXX
else:
XXX
Lists and Dictionaries
- list = [‘a’,’b’,12] -> 可存储任意类型
remove and delete of list
1
2list.remove(index or value);
del list[index]add item to list
1
list.append('xxx')
dictionary(key:value)
1
slang={'cheerio':'goodbye','yonks':'ages'}
add or update dictionary item
1
slang['smashing'] = 'terrific'
remove dictionary item
1
del slang[‘cheerio']
get dictionary item
1
slang.get(‘cheerio')
Comparing lists : my_list==your_list;true->same elements and same order
- Comparing Dictionaries : my_dict == your_dict;true->same elements order没有要求
- List of list : 二维数组menus[0][1]
- dictionary of lists : key value,value是list dic[‘key’][2]
Loops
for loop
1
2for price in prices:
do somthing(不需要花括号,有缩进)random
1
2
3
4import random
random.random() ->[0.0,1.0];
random.choice([1,2,3,4,5,6]) ->a random choice from list;
random.randint(1,1000) ->random number in this rangerange(10) -> [0,1,2,3,4,5,6,7,8,9]
- range(start-num,stop-num,step-num)
for dictionary
1
2for name,price in menu_prices.items():
print(name,’:$’,price)print(name,’:$’,format(price,’.2f’),sep=‘ ‘)
- while
1
2while (x>= 1):
XXX
Functions
定义
1
2
3def average(numbers):
...
return avgmain(): best practice in Python
- scope: 不同方法中同名变量为不同变量,当一个方法调用另一个方法,两个方法中的同名变量属于各自方法不会相互影响值,当这个变量在两个方法外定义,则该变量是全局的,它们同一变量
Files
open
1
2
3
4
5open(‘filename’,’w’)
# -> 2nd param:
# w-write(while override the file)
# a-append(while append data to the file)
# r-readwrite & close
1
2file.write(‘XXX')
file.close()read
1
2# open file for r mode
file_name.read()read line
1
2
3file_name.redline()
for line in opend_file:
line.strip() # 过滤前后空白show, time = line.split(‘ - ‘)
- Exceptions
1
2
3
4
5
6
7try:
XXX
except:
XXX
except ValueError as err:
print(err)
Modules
Installing & Using modules
1
pip install requests
http request
1
2
3import requests
my_request=requests.get(‘url’)
menu_list=my_request.json()Creating Modules
1
2module_name.py -> module_name.py中定义这个module的方法
import module_name