學習筆記20:Python基礎使用(參數,嵌套,列表,元組,字典,字符串等)

(1)函數的定義:可由字母,下劃線和數字組成,但不能以數字開頭,且不能與關鍵字相同

def 函數名():
	函數封裝的代碼

練習1:第一個函數

#注意定義函數之後只表示代碼封裝,需主動調用,函數定義必須寫在調用之前 


def say_hello():
	'''打招呼'''
    print("hello 1")
    print("hello 2")
say_hello()
執行結果:
C:\python\0\venv\Scripts\python.exe C:/python/0/first_函數.py
hello 1
hello 2

Process finished with exit code 0

注:函數定義上方與其他代碼保留兩個空行,且將函數說明用引號寫在函數內部,在PyCharm中可用Ctrl+Q查看函數相關信息

(2)函數參數的使用:在函數名後面的括號內可填寫參數,參數之間使用逗號進行分離;調用函數時按照參數定義(形參)順序依次寫入傳遞的參數值(實參)
函數的返回值:在函數中使用return關鍵字可返回函數值;當調用函數時可使用變量來接收函數的返回結果

練習2:兩個數字的求和

def sum(number1,number2):
    '''兩個數字求和'''
    #調用函數,並使用result變量接收計算結果
    result = number1 + number2
    print("%d + %d = %d" %(number1,number2,result))
sum(1,2)
執行結果:
C:\python\0\venv\Scripts\python.exe C:/python/0/求和.py
1 + 2 = 3

Process finished with exit code 0

練習3:加入函數返回值

def sum(number1,number2):
    '''兩個數字求和'''
    result = number1 + number2
    #可以使用返回值得出計算結果
    return result
#可以使用變量來接收函數執行的返回結果
sum_result = sum(1,2)
print("計算結果:%d" %sum_result)

執行結果:

C:\python\0\venv\Scripts\python.exe C:/python/0/求和.py
計算結果:3

Process finished with exit code 0

注意:return 表示返回,會返回到調用函數的位置,函數內return後續的代碼不會被執行

(3)函數的嵌套
練習4:函數的嵌套

def test1():

    print("*" * 50)
def test2():

    print("-" * 50)
    test1()
    print("+" * 50)
test2()

#打印任意字符任意次數的分隔線
def print_line(char,times):
    print(char * times)
print_line("&",40)


def print_lines(char,times):
    """
    給函數添加文檔註釋:打印多條分割線
    :param char:分隔線的字符
    :param times:分隔線的次數
    """
    row = 1
    while row < 3:
        print_line(char,times)
        row = row + 1
print_lines("!",10)
執行結果:
C:\python\0\venv\Scripts\python.exe C:/python/0/函數嵌套.py
--------------------------------------------------
**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
!!!!!!!!!!
!!!!!!!!!!

Process finished with exit code 0

(4)模塊中的函數:使用import導入模塊;以py結尾的python源文件都是一個模塊;在模塊中的全局變量和函數都是模塊可直接提供給外界的工具;模塊名也是標識符不能以數字開頭,不能與關鍵字重名,若模塊名以數字開頭則不能導入。

練習5:定義一個函數quadratic(a, b, c),求一元二次方程的方程解

import math
def quadratic(a,b,c):
    if a == 0:
        return TypeError("a不能爲0")
    if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)):
        return TypeError("Bad operand type")
    delta = math.pow(b,2) - 4*a*c
    if delta < 0:
        return "無實根"
    x1 = math.sqrt((delta)-b)/(2*a)
    x2 = -math.sqrt((delta)+b)/(2*a)
    return x1,x2
a = int(input("請輸入a:"))
b = int(input("請輸入b:"))
c = int(input("請輸入c:"))
print(quadratic(a,b,c))

執行結果:
D:\python\python程序\venv\Scripts\python.exe D:/python/python程序/方程解.py
請輸入a:2
請輸入b:8
請輸入c:4
(1.224744871391589, -1.5811388300841898)

Process finished with exit code 0

練習6:求n的階乘

def fact(n):
    return fact_iter(n,1)
def fact_iter(num,product):
    if num == 1:
        return product
    return fact_iter(num-1,num * product)
print(fact(6))
執行結果:
D:\python\python程序\venv\Scripts\python.exe D:/python/python程序/階乘.py
720

Process finished with exit code 0

(5)pyc文件:使用解釋器編譯過的文件,即二進制文件(python解釋器模塊的源碼轉換爲字節碼,這樣當用import導入時可優化執行速度。
(6)python中數據類型:數字型(整型,浮點型,布爾型,複數),非數字型(字符串,元組,列表,字典)

  1. 列表:多用在處理相同的數據類型,在其他語言中對應數組,用 [ ] 定義,數據之間用逗號隔開,列表的索引即位置標號從0開始,取值若超出索引範圍則會index out of range出錯。

練習7:列表基礎使用

#按Ctrl+Q可以查看光標所在具體使用方法
name_list= ["zhangshan","lisi","wangwu"]
#1.取值和取索引
print(name_list[2])
print(name_list.index("wangwu"))#使用index方法時,取值必須存在
#2.修改指定位置數據,列表指定索引不能超出範圍
name_list[1] = "李四"
#3.向列表中增加數據
name_list.append("三毛") #列表末尾追加數據
name_list.insert(1,"喃喃")#在列表指定索引位置插入數據
tmp_list = ["哪吒","熬丙","太乙真人"]
name_list.extend(tmp_list)#將其他列表完整內容追加到當前列表
print(name_list)
#4.刪除數據
name_list.remove("wangwu")#可從列表中刪除指定數據,若數據不只一個,則刪除第一次出現的
name_list.pop()#默認刪除列表中最後一個元素
name_list.pop(3)#可刪除指定索引位置數據
print(name_list)
name_list.clear()#清空列表

name_list1= ["zhangsan","lii","wang"]

del name_list1[1]#del 關鍵字本質上是將一個變量從內存中刪除,後續的代碼則不能再使用這個變量,不建議使用
print(name_list1)

#統計
name_list2 = ["zhangs","lii","wangs","uu","uu"]
list_len = len(name_list2)
print("列表中包含%d個元素" %list_len)
print("uu出現了%d次"%name_list2.count("uu"))

#排序
name_list3 = ["bb","cc","tt","ff"]
num1_list = [6,3,9,5,2]
#升序
#name_list3.sort()
#num1_list.sort()
#降序
#name_list3.sort(reverse=True)
#num1_list.sort(reverse=True)
#逆序
name_list3.reverse()
num1_list.reverse()
print(name_list3)
print(num1_list)

#打印python中的關鍵字,關鍵字後面不需要括號,如上面的del
import keyword
print(keyword.kwlist)

#使用迭代(iteration)遍歷列表,順序從列表獲取數據,每一次循環,數據會保存在name變量
name_list4 = ["zhungs","lri","ue"]
for name in name_list4:
    print("我的名字叫%s" %name)
執行結果:
C:\python\0\venv\Scripts\python.exe C:/python/0/列表.py
wangwu
2
['zhangshan', '喃喃', '李四', 'wangwu', '三毛', '哪吒', '熬丙', '太乙真人']
['zhangshan', '喃喃', '李四', '哪吒', '熬丙']
['zhangsan', 'wang']
列表中包含5個元素
uu出現了2次
['ff', 'tt', 'cc', 'bb']
[2, 5, 9, 3, 6]
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
我的名字叫zhungs
我的名字叫lri
我的名字叫ue

Process finished with exit code 0

2.元組:與列表類似,但元組中的變量均不能修改;元組用()定義,數據與數據之間用逗號隔開;元組的索引也從0開始;當元組中只有一個元素時,需要在元素後加入逗號

練習8:元組基礎使用

info_tuple = ("魏無羨",26,1.8)
#1.取值和取索引
print(info_tuple[0])
print(info_tuple.index(1.8))
#2.統計計數
print(info_tuple.count("魏無羨"))
print(len(info_tuple))
#3.使用迭代遍歷元組
for my_info in info_tuple:
    print(my_info)#使用格式字符串輸出不方便,因爲元組中保存的數據類型不同
#4.使用格式化字符輸出,格式化字符後面的‘()’本身就是元組
print("%s 年齡是 %d 身高是 %.2f" %("藍忘機",20,1.8))
info_tuple1 = ("藍湛",20,1.8)
print("%s 年齡是 %d 身高是 %.2f" %info_tuple1)
info_str = "%s 年齡是 %d 身高是 %.2f" %info_tuple1 #使用元組可用來拼接新的字符串
print(info_str)
#元組和列表之間的轉換
info_tuple2 = ("魏嬰",26,1.8)
print(list(info_tuple2))
執行結果:
C:\python\0\venv\Scripts\python.exe C:/python/0/元組.py
魏無羨
2
1
3
魏無羨
26
1.8
藍忘機 年齡是 20 身高是 1.80
藍湛 年齡是 20 身高是 1.80
藍湛 年齡是 20 身高是 1.80
['魏嬰', 26, 1.8]

Process finished with exit code 0

3.字典:存儲多個數據,與列表有序的對象集合不同,字典是無序的;字典用{}定義;用鍵值對存儲數據,鍵值對之間使用逗號分隔;鍵key是索引,值value是數據;鍵和值之間使用冒號分隔;鍵必須唯一;值可取任何數據類型,但鍵只能使用字符串,數字或元組

練習9:字典的基礎使用

#字典是無序的數據集合,輸出的順序與定義的順序無關
lanzan = { "name":"藍湛",
           "age": 20,
           "gender":True,
           "height":1.85
           }
print(lanzan)
weiying_dict = {"name":"魏嬰"}
#1.取值
print(weiying_dict["name"])
#2.增加/修改
weiying_dict["age"] = 27
print(weiying_dict)
weiying_dict["name"] = "魏無羨"
print(weiying_dict)
#3.刪除
weiying_dict.pop("name")
print(weiying_dict)
#4.統計鍵值個數
print(len(lanzan))
#5.合併字典
tem_dict = {"weight":74.5,
            "age": 21}
lanzan.update(tem_dict)
print(lanzan)
#6.清空字典
lanzan.clear()
print(lanzan)
#7.循環遍歷
weiwuxian_dict = {"name":"魏無羨",
                  "qq":"2423434",
                  "phone":"3432545"}
#k是每一次循環中獲取到的鍵值對的key
for k in weiwuxian_dict:
    print("%s - %s" %(k,weiwuxian_dict[k]))

#字典和列表的聯合使用:將多個字典放在一個列表中再進行遍歷
card_list = [
    {"name":"魏無羨",
    "qq":"333333",
     "phone":"11111"},
    {"name": "藍忘機",
     "qq": "222222",
     "phone": "88888"},
]
for card_info in card_list:
    print(card_info)
執行結果:
C:\python\0\venv\Scripts\python.exe C:/python/0/字典.py
{'name': '藍湛', 'age': 20, 'gender': True, 'height': 1.85}
魏嬰
{'name': '魏嬰', 'age': 27}
{'name': '魏無羨', 'age': 27}
{'age': 27}
4
{'name': '藍湛', 'age': 21, 'gender': True, 'height': 1.85, 'weight': 74.5}
{}
name - 魏無羨
qq - 2423434
phone - 3432545
{'name': '魏無羨', 'qq': '333333', 'phone': '11111'}
{'name': '藍忘機', 'qq': '222222', 'phone': '88888'}

Process finished with exit code 0

4.字符串:可用雙引號或者單引號定義;len函數統計字符串長度;count統計子字符串在大字符串中出現的次數,若子字符串不存在則次數爲0;index統計字符串在大字串中出現的位置,若子字符串不存在程序會報錯。

練習10:字符串的基本使用

str1 = "hello python"
str2 = '我愛看”陳情令"'
print(str2)
print(str1[0])
for char in str2:
    print(char)
print(len(str1))
print(str1.count("o"))
print(str1.index("o"))
space_str = "   \t\n\r" #判斷空白字符
print(space_str.isspace())
num_str = "\u00b2"#判斷字符串是否只包含數字,下列三種均不能判斷小數
print(num_str)#平方
print(num_str.isdecimal())#只能判斷單純的數字
print(num_str.isdigit())#可判斷單純數字和unicode的數字
print(num_str.isnumeric())#可判斷單純數字,中文數字和unicode的數字

hell_str = "hello world"
print(hell_str.startswith("Hello"))#判斷是否以字符串開始
print(hell_str.endswith("world"))#判斷是否以字符串結束
print(hell_str.find("o"))#判斷子字符串在字符串中的位置,與index的區別在於當查找的字符不存在時不報錯
print(hell_str.replace("world","boji"))#替換字符串,會返回新字符串,但注意不會改變原有字符串
print(hell_str)

poem = ["\t\n白日依",
        "黃河",
        "入了海流\t\n"
]
for poem_str in poem:
    print("|%s|"% poem_str.strip().center(10," "))#strip去除空白字符,center中心對齊;ljust向左對齊;rjust向右對齊

poem1 = "燈管\t 王之渙 \t白日依山盡 \t \n黃河"
poem_list = poem1.split()#拆分字符串
print(poem_list)
result = " ".join(poem_list)
print(result)

#切片方法適用於字符串,列表,元組,可採用倒序順序方法
#字符串[開始索引:結束索引:步長]
num_str = "01234567"
print(num_str[2:6])
print(num_str[2:])
print(num_str[:6])
print(num_str[-1:])
print(num_str[:])
print(num_str[::2])
print(num_str[::-1])
C:\python\0\venv\Scripts\python.exe C:/python/0/字符串.py
我愛看”陳情令"
h
我
愛
看
”
陳
情
令
"
12
2
4
True
²
False
True
True
False
True
4
hello boji
hello world
|   白日依    |
|    黃河    |
|   入了海流   |
['燈管', '王之渙', '白日依山盡', '黃河']
燈管 王之渙 白日依山盡 黃河
2345
234567
012345
7
01234567
0246
76543210

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章