11、python函數學習

1.    定義函數函數

def   函數名(形參):編碼

    函數體指針

    return  xxx--------其下面的內容再也不執行ip

---------------------------------------------------------------------------------------------------------------utf-8

2.執行函數字符串

      函數名(實參)input

---------------------------------------------------------------------------------------------------------------it

3.形參,實參(默認按照順序)io

---------------------------------------------------------------------------------------------------------------function

4.執行形參傳入實參,可不按照順序

---------------------------------------------------------------------------------------------------------------

5.函數能夠有默認參數

---------------------------------------------------------------------------------------------------------------

6.動態參數  
#動態參數一,類型爲元祖,傳的參數爲元祖的元素
def f1(*a):
print (a,type(a))
f1(123,234,[456123789],{1:2})
#動態參數二,類型爲字典,傳入的參數爲字典的鍵值對
def f1(**a):
print (a,type(a))
f1(k1=123,k2=456)
#萬能動態參數-------一*較**在前
def f1(*a,**p):
print (a,type(a),type(p))
f1(123,234,[456123789],{1:2},k1=123,k2=456)
---------------------

    ((123, 234, [456123789], {1: 2}), <type 'tuple'>)
    ({'k2': 456, 'k1': 123}, <type 'dict'>)
    ((123, 234, [456123789], {1: 2}), <type 'tuple'>, <type 'dict'>)

---------------------------------------------------------------------------------------------------------------

7.爲動態參數傳入字典,列表

def f1(*args):
print (args,type(args))
l1=[11,22,33,44]
f1(l1)
f1(*l1)
------------------------

 (([11, 22, 33, 44],), <type 'tuple'>)
 ((11, 22, 33, 44), <type 'tuple'>)

------------------------

def f2(**args):
print (args,type(args))
l1={"k1":"123"}
f2(l1=l1)
f2(**l1)
-------------------------

   ({'l1': {'k1': '123'}}, <type 'dict'>)
   ({'k1': '123'}, <type 'dict'>)

---------------------------------------------------------------------------------------------------------------

8.全局變量,局部變量

P="chushujin"
def func1():
#局部變量
a=123
global P #加上此關鍵詞後,全局變量就會被修改,不然不會被修改
print (a)
P="zhangyu"
def func2():
print (P)
func1()
func2()
----------------------

   123
 zhangyu

---------------------------------------------------------------------------------------------------------------

9.lambda表達式

def f1():
return 123
f2=lambda : 123

print f1()
print f2

def f3(a1,a2):
return a1+a2
f4=lambda a1,a2:a1+a2

print f3(1,2)
print f4(2,3)
----------------------

    123
    <function <lambda> at 0x00000000026A2BA8>
    3
    5

---------------------------------------------------------------------------------------------------------------

10.文件操做open
打開文件:open("文件名/文件路徑",模式,編碼)
操做文件
關閉文件
'''
close(),flush(),read(),readline(),seek(),tell(),truncate(),write(),
'''
'''
# f=open("hello.log","r") #默認不寫爲只讀
# data=f.read()
# print data
# f.close()

#只讀 r---不可寫
# f=open("hello.log","r") #默認不寫爲只讀
# data=f.write()-------------報錯
# f.close()

#只寫 w---不可讀
# f=open("hello.log","w") #默認只寫不可讀
# data=f.write("123") #-------------報錯
# f.close()

#a,追加模式【不可讀; 不存在則建立;存在則只追加內容;】
f=open("hello.log","a")
f.write("aaa")
data=f.read()
print data
f.close()

#x, 只寫模式【不可讀;不存在則建立,存在則報錯】-----py3
f=open("hello.log","x")
f=open("hello2.log","x")
f.write("aaa")
==================================================================
二進制方式打開:
#二進制的方式打開
#只讀
# f=open("hello.log","rb")
# data=f.read()
# print (data)
# print (str(data,encoding="utf-8"))
--------------------------------------

 b'\xe4\xb8\xad\xe5\x9b\xbd'
    中國

--------------------------------------
#只寫
# f=open("hello.log","wb")
# f.write(bytes("中國",encoding="utf-8"))
==================================================================
'''
r+:讀寫【可讀,可寫】
w+:寫讀【可讀,可寫】
x+:寫讀【可讀,可寫】
a+:寫讀【可讀,可寫】
'''
#r+:打開文件,write:末尾追加內容,指針末尾,若是讀取時的指在某一位置,寫的時候只會在末尾
#tell():顯示指針的位置
#feek(x):調整指針的位置
f=open("hello.log","r+",encoding="utf-8")
print (f.tell()) #指針的位置,一個漢字3個字節
data=f.read(1)
print (f.tell())
print (type(data),data)
print (f.tell())
data=f.read(1)
print (f.tell())
print (type(data),data)
f.seek(3)
print (f.tell())
--------------------------

 0
    3
    <class 'str'> 中
    3
    6
    <class 'str'> 國
    3

--------------------------
# f.write("中國")
# data=f.read()
# print (type(data),data)
f.close()
--------------------------
#a+:寫讀【可讀,可寫】:打開的同時指針已經在末尾
f=open("hello.log","a+",encoding="utf-8")
print (f.tell())
f.seek(0)
data=f.read()
print (data)
f.write("QA")
--------------------------
#w+:寫讀【可讀,可寫】:先清空,再寫以後就能夠讀了
#只要寫入內容,指針調至最後
f=open("hello.log","w+",encoding="utf-8")
data=f.write("咱們")
f.seek(0)
data=f.read()
print (data)
f.close()
================================================================
'''
readline():只讀取一行
'''
# f=open("hello.log","r+",encoding="utf-8")
# data=f.readline()
# print (data)

readlines:讀取多行
['第一行','第二行'...]
'''
truncate():截斷數據,僅保留指定以前數據
'''
# f=open("hello.log","r+",encoding="utf-8")
# print (f.tell())
# data=f.read()
# print (data)
# f.seek(6)
# f.truncate()
# f.close()

f=open("hello.log","r",encoding="utf-8")

#f.read()

for line in f:
print (line)
==============================================================
'''
關閉:close()至關於with open("xxx","r",encoding="utf-8") as f
自動關閉文件
'''
# with open("hello.log","r",encoding="utf-8") as f:
# # data=f.read()
# # print (data)


'''
同時打開兩個文件,將第一個文件中的數據一行一行寫入第二個文件
with open("源文件","r",encoding="utf-8") as f1,open("新文件","w",encoding="utf-8") as f2:
'''
with open("hello.log","r",encoding="utf-8") as f1,open("hello2.log","w",encoding="utf-8") as f2:
for line in f1:
f2.write(line)

---------------------------------------------------------------------------------------------------------------
11.註冊登陸函數
 
def login(username,password):
'''
用於用戶名密碼的驗證
:param username: 用戶名
:param password: 密碼
:return: True,用戶驗證成功;False,用戶驗證失敗
'''
with open('db', encoding='utf-8') as f:
ret = []
for i in f:
i = i.strip() # 去除首尾的空格和換行符
m = i.split('$') # 經過指定的分隔符對字符串進行切片
if username == m[0] and password == m[1]:
#print("登陸成功")
#break
return True
return False
def register(username,password):    '''    註冊用戶:    1.打開文件,追加a    2.用戶名$密碼    :param username:    :param password:    :return:    '''    with open("db","a",encoding="utf-8") as f:        temp="\n"+username+"$"+password        f.write(temp)    return Truedef user_exist(username):    '''    一行一行的查詢,若是用戶名存在返回true  不存在返回false    :param username: 用戶名    :return: true用戶名存在,false用戶名不存在    '''    with open('db',"r",encoding="utf-8") as f:        for line in f:            line=line.strip()            line_list=line.split("$")            if line_list[0]==username:                return True    return Falsedef main():    print ("歡迎登陸xxxx系統")    inp=input("1:登陸,2:註冊")    if inp=='1':        user = input("請輸入用戶名:")        passwd=input("請輸入密碼:")        is_login=login(user,passwd)        if is_login:            print ("登陸成功")        else:            print ("登陸失敗")    elif inp=='2':        user = input("請輸入用戶名:")        passwd = input("請輸入密碼:")        is_exist=user_exist(user)        if is_exist:            print ("用戶名已存在,請直接登陸")        else:            print ("用戶名不存在,請註冊")            result=register(user,passwd)            if result:                print ("註冊成功")            else:                print ("註冊失敗")main()
相關文章
相關標籤/搜索