def getInfo(name,age,sex="男"):
obj = {
"name":name,
"age":age,
"sex":sex
}
print(obj)
getInfo(age=12,name='zhangsan')
lists=['aa',20,'女']
getInfo(*lists)
複製代碼
getInfo(age=12,name='zhangsan')能夠錯位傳參數,*list表明將列表或者元祖類型的元素做爲參數傳給函數,相似於ES6 ...解構操做
解構字典時使用「**」python
# 解構字典類型
def insertUsers(name,pwd,**others):
print(others) # {'job': '學生', 'email': '123@163.com'}
insertUsers('luoj','123456',job="學生",email='123@163.com')
複製代碼
lists=[1,2,3,4,5,6,7,8,9,10]
copy_list=lists[0:] # 拷貝一份列表數據
lists[0]='aaa'
print(copy_list)
print(lists[0:2])
複製代碼
取字符串 :bash
key="123ABCDEDG"
print(key[0:2]) #12
複製代碼
dic = {
"a":1,
"b":2,
"c":3
}
# 遍歷key
for key in dic:
print(key)
# 遍歷value
for values in dic.values():
print(values)
#同時遍歷key,value
for key,value in dic.items():
print(key+':'+str(value))
複製代碼
遍歷列表類型:模塊化
lists=["a","b","c","d"]
# 遍歷key
for values in lists:
print(values)
# list無索引,可以使用enumerate函數
for key,values in enumerate(lists):
print(key,values)
複製代碼
九九表:函數
for i in range(1,10):
str1=''
for j in range(1,i+1):
str1+=" "+str(i)+'*'+str(j)
print(str1)
複製代碼
a=list(range(1,10)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
b=[x*x for x in a] # [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(b)
複製代碼
能夠添加條件以及多重循環。ui
a=list(range(1,10)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
b=[x*x for x in a if x%2 == 0] # [4, 16, 36, 64]
c='ABC'
d='123'
print([m+n for m in c for n in d]) # ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
複製代碼
使用import導入包名,在同一目錄下能夠直接import + 文件名
tools.pyspa
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Mango'
count=0;
_name="luoj";
def __greet__():
return "hello,world"
# 求列表中數字平均數
def avg(lists=[]):
init=0;
for values in lists:
init+=values
return init/len(lists)
print(__name__) #__main__
if(__name__=='__main__'):
print(avg([2,8]))
複製代碼
python內置了__name__變量 若是你在命令行直接執行了 python tools.py ,則__name__=='main' 表明這個文件做爲主程序入口 若是你在其餘文件下引入tools.py ,則這個文件不是主程序入口,此時tools.py下的__name__=='tools',而做爲主程序的main.py下的__name__=='main'命令行
import tools
print(__name__) #__main__
print(tools.count) # 0
print(tools.__greet__()) #
print(tools._name)
複製代碼
import時沒必要考慮變量名衝突問題,python內部已經處理好了。此外能夠使用from語句導入模塊中特定的變量,例如:code
from fibo import fib, fib2
複製代碼