1,注釋(ctrl+/)
單行注釋用#
多行注釋用"""? """
2,變量定義(遵循標(biāo)識符規(guī)則,駝峰命名)
變量名=值
3,數(shù)據(jù)類型
#int
a=1
print(type(a))
#float
b=1.2
print(type(b))
#string
name='中國'
print(type(name))
#tuple
c=(10.20,25)
print(type(c))
#set集合
d={"10","20","中國"}
print(type(d))
#List列
e=[10,'hello',2.3]
print(type(e))
f={"name":"張三","age":15}
print(type(f))
#bool型,true/false
g=8>2
print(type(g))
3,格式化輸出
格式化符號格式數(shù)據(jù)
%s 字符串
%d 帶符號的整數(shù)型
%f 浮點型
name='joseph'
age=26
whight=75.2
stu_id=2
stu_id2=102
# 我的名字是joseph
print("我的名字是%s" % name)
#我的年齡是
print("我的年齡是%d" % age)
#我的體重是
print("我的體重是%f" % whight)? ? --默認(rèn)是保存6為小數(shù)
print("我的體重是%.2f" % whight)? --保留兩位小數(shù)
#我的學(xué)號是
print("我的學(xué)號是%03d" % stu_id)? --比如要輸出002,%03d是輸出3位數(shù),不夠的用0補齊
print("我的學(xué)號是%02d" % stu_id2) --102 要輸出2位數(shù),超過的保持原狀
#我的名字是x,年齡是x,體重是x,學(xué)號是x
print("我的名字是%s,年齡是%d,體重是%.2f,學(xué)號是%02d" % (name,age,whight,stu_id))
print("我的名字是%s,年齡是%s,體重是%s,學(xué)號是%s" % (name,age,whight,stu_id))? --所有類型強制轉(zhuǎn)換為string
print(f"我的名字是發(fā){name},年齡是%{age},體重是{whight},學(xué)號是{stu_id}") --f{}形式比較高效
4,換行符\n,制表符\t(四個空格)
5,輸入
input:1.當(dāng)用戶執(zhí)行到input時,等待用戶全部輸入完才開始執(zhí)行
? 2.接收到數(shù)據(jù)后一般存儲到變量,并以字符串形式處理
password=input("請您輸入密碼:")
print(f"您輸入的密碼是{password}")
print(type(password))
6,數(shù)據(jù)類型轉(zhuǎn)換(跟java的強制轉(zhuǎn)換一樣)
int,float,str,list,tuple,eval
#string轉(zhuǎn)int/float
age="15"
print(type(int(age)))
print(int(age))
print(type(float(age)))
print(float(age))
#List轉(zhuǎn)tuple
b=[15.65,85]
print(type(tuple(b)))
print(tuple(b))
#tuple轉(zhuǎn)list
c=("java","scala","python")
print(type(c))
print(type(list(c)))
print(list(c))
d="(10,20,30)"
print(type(d))
print(eval(d))? #eval將計算機字符串中的有效python表達(dá)式(原來是什么轉(zhuǎn)換后還是什么)
print(type(eval(d)))
7,運算符
算數(shù)運算符(+,-,*,/,//(整除9//4=2),%(取余),**(指數(shù)2**3=8),()括號) --()優(yōu)先級依次** * / // % + -
賦值運算符
? a,b,c=15,(10,15),"hello"? --多變量賦不同值
print(a)
print(b)
print(c)
? a=b=c=15 ? --多變量賦相同值
print(a)
print(b)
print(c)
復(fù)合賦值運算符(+=,-=,*=,/=,//=,%=,**=)
a=10
a+=1+2? #結(jié)果是13,是先執(zhí)行1+2=3,然后再a=a+3
print(a)
比較運算符(==,!=,<,>,>=,<=)
邏輯運算符(and,or,not)
a=1
b=2
c=3
print(a<b)and(b<c)? --兩個都為true返回true
print(a>b)or(b>a) --(a>b)為ture時返回true,否則返回(b>a)的boolen值
print(not(a>c)) --如過(a>c)為真,則返回false,如果(a>c)為假,則返回ture
注意:
a=0
b=2
c=3
print(a and c)? --and運算符,只要有一個值為0則返回0,否則返回結(jié)果為最后一個非0的值
print(b or a) --or 運算符,所有值為0,則返回0,否則返回第一個非0的值
8,條件語句(if)
money=(int(input("請投幣:")))
site=(int(input("請輸入幾個座:")))
if money>=1:
print("歡迎你乘坐28路公交車")
if site>=3 and site<=53:
print("夠咱們仨人座了,趕緊坐下")
elif site<3:
print("不夠咱們仨人座呢,還是等著吧")
else:
print("沒座,等待中")
else:
print("車上座再多,沒錢投幣,,還是跑步吧")
9,三目運算符
a=2
b=3
c=a if a<b else b? --條件成立執(zhí)行的語句 if 條件 else 條件不成立執(zhí)行的語句
print(c)
10,while嵌套循環(huán)及break跟continue的應(yīng)用
i=1
while i<=5:
if i==3:
print(f"媳婦,這是我第{i}次錯了")
i += 1 #內(nèi)循環(huán)+1,是為了不會再遇到i==3
continue? ? #如果是continue,則表示跳出本次循環(huán),接著循環(huán),若是break,則直接終止循環(huán)
print("媳婦我接著錯了")
i+=1 #外循環(huán)+1,是為了接著循環(huán)
#嵌套,各自的條件應(yīng)放在各自的代碼塊區(qū)域,例如:i放在內(nèi)部自己的代碼塊
j=1
while j<=3:
i=1
while i<=5:
print("媳婦,我錯了")
i+=1
print("我錯了,今晚我刷碗")? #這種形式是循環(huán)結(jié)束打印這句
j+=1
print("這是循環(huán)三遍")
#九九乘法表
j=1 #先定義列
while j<=9:
i=1?
while i<=j:? #行<=列
print(f"{i}*{j}={j*i}",end="\t")
i += 1
j+=1
print("\n")
i=1
while i<5:
if i==3:
print("這次沒誠意,接著道歉")
i+=1
continue
print("媳婦,我錯了")
i += 1
else:
print("買個包就行了")
11,for循環(huán)(類似java的增強for循環(huán))
str="joseph"
for i in? str:? #類似于增強for循環(huán)
if i=="p":
break #遇到break循環(huán)結(jié)束,不會打印“哈哈”,如果是contine,不打印'p',接著循環(huán)打印'哈哈'
print(i)
else:
print("哈哈")
12,字符串下標(biāo)及切片
# 序列名[開始位置的下標(biāo):結(jié)束位置的下標(biāo):步長]? --不包含結(jié)束下標(biāo)位置的值
str1 = '012345678'
# print(str1[2:5:1])? # 234
# print(str1[2:5:2])? # 24
# print(str1[2:5])? # 234? --默認(rèn)步長是1
# print(str1[:5])? # 01234 -- 如果不寫開始,默認(rèn)從0開始選取
# print(str1[2:])? # 2345678 -- 如果不寫結(jié)束,表示選取到最后
# print(str1[:])? # 012345678 -- 如果不寫開始和結(jié)束,表示選取所有
# 負(fù)數(shù)測試
# print(str1[::-1])? # 876543210 -- 如果步長為負(fù)數(shù),表示倒敘選取
# print(str1[-4:-1])? # 567 -- 下標(biāo)-1表示最后一個數(shù)據(jù),依次向前類推
# 終極測試
# print(str1[-4:-1:1])? # 567
print(str1[-4:-1:-1])? # 不能選取出數(shù)據(jù):從-4開始到-1結(jié)束,選取方向為從左到右,但是-1步長:從右向左選取
# **** 如果選取方向(下標(biāo)開始到結(jié)束的方向) 和 步長的方向沖突,則無法選取數(shù)據(jù)
print(str1[-1:-4:-1])? # 876
13,字符串常用操作
#1.find查找數(shù)據(jù)? ? 字符串.find("字串",開始位置,結(jié)束位置)
str="hello python and hello java and hello scala"
# new_str=str.find("and")? #13? 不加位置,全盤查找
# new_str=str.find("and",15,35)? #28? 加位置,在開始結(jié)束位置里查找
# new_str=str.find("anda")? #-1? 字符串沒有的,返回-1
# new_str=str.rfind("and")? ? ? #rfind 從右邊開始查找and,然后從左算索引位置
# print(new_str)
# 2.index查找索引值
# new_str=str.indrex("and")? #不加位置,全盤查找
# new_str=str.index("and",15,35)? #加位置,在開始結(jié)束位置里查找
# new_str=str.index("ands")? #如果沒有報錯
# new_str=str.rindex("and")? #從右側(cè)開始查找and,然后從左算索引位置
# print(new_str)
#3.count,字串出現(xiàn)的次數(shù)
# new_str=str.count("and")
# new_str=str.count("hello")
# new_str=str.count("hello",10,60) #當(dāng)結(jié)束位置超過索引值時,按全局查
# print(new_str)
#4.replace替換字串? 字符串.replace("舊字串","新字串","次數(shù)")
# new_str=str.replace("and","he",1)? #替換一次
#new_str=str.replace("and","he",8)? #超過的,就全部替換
# print(new_str)
# 5.split切割,字符串.split(“分割字符”,次數(shù))
#new_str=str.split("and")
#new_str=str.split("and",2)? --如果分割字符是源字符串的字串,分割后源串丟失字串
#print(new_str)
#6.join 字符或字符串合并
# print("_".join(str))
# str2="你好 python"
# print(str2.join(str))
# 7.capitalize,將字符串的第一個字母大寫
#print(str.capitalize()) --Hello python and hello java and hello scala
#8.title 將字符串中每個單詞的首字母大寫
# new_str=str.title()? --Hello Python And Hello Java And Hello
#print(new_str)
#9.lower 將字符串中大寫轉(zhuǎn)小寫
#str2="Hello Java,How Are You"
#new_str=str2.lower()? ? --hello java,how are you
#print(new_str)
#10.upper 字符串所有小寫轉(zhuǎn)大寫
#new_str=str.upper()
#print(new_str)? ? --HELLO PYTHON AND HELLO JAVA AND HELLO SCALA
#11.lstrip去除左空格
# str="? Hello Java"
# new_str=str.lstrip()? ? Hello Java
# print(new_str)
# 12.rstrip刪除字符串右側(cè)空白
# str="Hello MoTo? "
# new_str=str.rstrip()? --Hello MoTo
# print(new_str)
# 13.strip 刪除字符串兩側(cè)空白
# str="? Hello Joseph? "
# new_str=str.strip()? Hello Joseph
# print(new_str)
# 14.ljust 返回原字符串,左對齊,并使用指定字符,填充至對應(yīng)長度的新字符串
# 字符串.ljust(長度,填充字符)
# str="wufan"
# new_str=str.ljust(10,"*")? ? --wufan*****
# new_str=str.ljust(10)? ? ? ? ? --wufan? ? 不寫默認(rèn)是空格
# print(new_str)
# 15.rjust? 返回原字符串,右對齊,并使用指定字符,填充至對應(yīng)長度的新字符串
# str="wufan"
# new_str=str.rjust(10,"#")? #####wufan
# print(new_str)
# 16.center 返回原字符串,中心對齊,并使用指定字符,填充至對應(yīng)長度的新字符串
# str="wufan"
# new_str=str.center(10,"*")? **wufan***
# print(new_str)
# 17.startswith 是否以指定字串開始,真返回ture,假返回false,如果寫位置,則再指定范圍內(nèi)查找
# 18.endswith 是否以指定字串結(jié)束,真返回ture,假返回false,如果寫位置,則再指定范圍內(nèi)查找
# 字符串.startswith("字串/字母",開始位置,結(jié)束位置)
# new_str=str.startswith("hel")
# new_str=str.startswith("hel",10,20)
# new_str=str.endswith("scala")
# print(new_str)
# 19.isalpha,字符串中全是字母
# 20.isalnum? 字母或數(shù)字
# 21.isspace? 只包含空格
# str="abc"
# str2="abc12"
# str3="java haha"
# print(str.isalpha())
# print(str2.isalnum())
# print(str3.isspace())? --false
14,列表
# 1.index返回數(shù)據(jù)的下標(biāo)索引? 列表.index(數(shù)據(jù),開始位置下標(biāo),結(jié)束位置下標(biāo))
# 2.count 數(shù)據(jù)出現(xiàn)的次數(shù)
# 3.len 列表的長度(列表有幾個數(shù)據(jù))
# 4.in 判斷是否在列表里
#? not in 判斷是否不在列表里
name_list=["lily","Tom","Jackson"]
# new_name=name_list.index("Tom")? --1
# new_name=name_list.count("Tom")? --1
# new_name=len(name_list)? --3
# new_name="lily" in name_list
# new_name="lily" not in name_list
# print(new_name)
# ---增加---
# 5.append 列表結(jié)尾追加數(shù)據(jù)
# 6.entend 列表結(jié)尾追加數(shù)據(jù),如果數(shù)據(jù)是一個序列,則拆開后加到原數(shù)列里
# 7.insert 指定位置添加? 列表.insert(索引位置,數(shù)據(jù))
# name_list.append("joseph")? --['lily', 'Tom', 'Jackson', 'joseph'] 追加到原列表,所以name_list是可變類型
# name_list.extend("haha")? ? --['lily', 'Tom', 'Jackson', 'h', 'a', 'h', 'a'] 單字符也是拆開添加
# name_list.extend(["haha","world"])? --['lily', 'Tom', 'Jackson', 'haha', 'world']? 如果是數(shù)列,拆開添加
# name_list.insert(0,"zhangsan")? ? ? --['zhangsan', 'lily', 'Tom', 'Jackson']
# print(name_list)
# ---刪除---
# 8.del刪除
# 9.pop刪除指定位置的數(shù)據(jù),默認(rèn)是最后一個? 列表.pop(索引下標(biāo))
# 10.remove()? 列表.remove(數(shù)據(jù))
# 11.clear? 清空列表
# del name_list[0]? ? ? --['Tom', 'Jackson']
# name_list.pop()? ? ? --['lily', 'Tom']
# name_list.pop(1)? ? ? --['lily', 'Jackson']
# name_list.remove("Tom") --只能刪除一個數(shù)據(jù)
# name_list.clear()? ? ? ? --[]
# print(name_list)
# ---修改---
# 12.reverse 順序反轉(zhuǎn)
# 13.sort? ? 排序? 數(shù)列.sort(key=None, reverse=False)? true降序,false升序
# 14.copy 復(fù)制
str=[1,5,6,8,7,2]
# str.reverse()? ? ? ? ? ? ? --[2, 7, 8, 6, 5, 1]
# str.sort(reverse=False)? ? --[1, 2, 5, 6, 7, 8]
# str2=str.copy()? ? ? ? ? ? --[1, 5, 6, 8, 7, 2]
# print(str2)
# ---循環(huán)---
# 15.while循環(huán)打印列表數(shù)據(jù)
# i=0
# while i<len(name_list):
#? ? print(name_list[i])
#? ? i+=1
# for i in name_list:
#? ? print(name_list[i])
name_list = [['xiaowu','xiaosi','xiaosan'], ['Tom','Lily','Rose'], ['zhangfei','lisi','wangwu']]
print(name_list[0][2])
#15.元組:元組使用小括號,且以逗號分割
t1=(10,20,30,40,50,50)? #多數(shù)據(jù)元組
t2=(10,)? ? ? ? ? ? ? #單數(shù)據(jù)元組
t3=(20)
# print(type(t3))? ? ? <class 'int'>單數(shù)據(jù)也得加逗號‘,’否則是數(shù)據(jù)本身的類型
# 1.按索引
# 2.知道數(shù)據(jù)查索引。元組.index()
# 3.統(tǒng)計某個數(shù)據(jù)在元組的出現(xiàn)的次數(shù)
# 4.統(tǒng)計元組里的數(shù)據(jù)長度
# print(t1[0])? ? ? ? ? ? 10? 元組不允許修改,只支持查詢
# print(t1.index(20))? ? 1
# print(t1.count(50))? ? 2
# print(len(t1))? ? ? ? ? 6
# 16.字典:大括號,數(shù)據(jù)為鍵值對,各個鍵值對逗號分割
dict1={"name":"Tom","age":20,"gender":"man"}
dict2={}? ? ? #空字典
# print(type(dict2))
# 1.修改字典? ? key存在則修改,key不存在則添加
# dict1["name"]="Rose"
# dict1["tel"]=1511696
# print(dict1)
# 2.刪除字典,或刪除字典里的指定鍵值對
# del dict1["age"]? ? 刪除指定的鍵值對
# print(dict1)
# print(dict1.clear())? None
# 3.查詢元組
# print(dict1["name"])? ? ? 利用key查找
# print(dict1.get("name"))? 利用get查找已存在的key
# print(dict1.get(id,110))? 利用get查找未存在的key,若不存在則返回給的值110,如果不給值則返回None
# 4.得到所有的keys,values,itmes
# print(dict1.keys())? ? ? ? dict_keys(['name', 'age', 'gender'])
# print(dict1.values())? ? ? dict_values(['Tom', 20, 'man'])
# print(dict1.items())? ? ? ? dict_items([('name', 'Tom'), ('age', 20), ('gender', 'man')])
# 5.遍歷字典的keys,values,itmes
# for keys in? dict1.keys():
#? ? print(keys)
# for values in dict1.values():
#? ? print(values)
# for itmes in dict1.items():
#? ? print(itmes)
# for key,value in dict1.items():
#? ? print(f'{key}={value}')
# 17.集合,創(chuàng)建集合用{},空集和用set(),因為{}是用來創(chuàng)建空字典的
s1={10,20,30,40,50,50}
s2=set()
s3={}
# print(s1)? ? ? ? ? {40, 10, 50, 20, 30}集合去重?zé)o序,故不支持索引查詢
# print(type(s2))? ? <class 'set'>
# print(type(s3))? ? <class 'dict'>
# 1.add,update,remove,discard,pop,in,not in
# s1.add(20)? ? ? ? ? ? 去重,所以加不進(jìn)去集合中已有的數(shù)據(jù)
# s1.update([60,70])? ? update(列表){70, 40, 10, 50, 20, 60, 30}
# s1.remove(50)? ? ? ? {40, 10, 20, 30}
# s1.remove(80)? ? ? ? 刪除指定元素,數(shù)據(jù)不存在則報錯
# s1.discard(50)? ? ? ? {40, 10, 20, 30}
# s1.discard(100)? ? ? 刪除指定元素,數(shù)據(jù)不存在不報錯
# print(s1.pop())? ? ? 隨機刪除某個數(shù)據(jù),并返回這個被刪數(shù)據(jù)
# print(100 in s1)? ? ? 判斷語句,false
# print(200 not in s1)? false
# print(s1)
str="abcdefg"
list1=[10,20,30,50]
# del str? ? ? ? ? ? 刪除整個字符串
# print(max(list1))? ? ? ? ? 50最大
# print(min(list1))? ? ? ? ? 10最小
# for i in range(1,10,2):? ? range生成序列,不包含結(jié)束值? range(開始值,結(jié)束值,步長)
#? ? print(i)
# enumerate(可遍歷對象,start=0)? ? ? (0, 10)(1, 20)(2, 30)(3, 50)
# for i in enumerate(list1):
#? ? print(i)
18.列表推導(dǎo)式
list1=[]
# for i in range(0,10,2):
#? ? list1.append(i)
# print(list1)
#
# list2=[i for i in range(0,10,2)]
# print(list2)
# i= 0
# while i < 10:
#? ? list1.append(i)
#? ? i += 2
# print(list1)
# list3=[i for i in range(0,10) if i%2==0]
# print(list3)
list4=[(i,j)for i in range(1,3) for j in range(2)]
print(list4)
19,字典推導(dǎo)式:快速合并列表為字典,或字典里的數(shù)據(jù)
list1=["name","age","gander"]
list2=["zhangsan",18,"man"]
dict={list1[i]:list2[i] for i in range(len(list1))}? ? ? ? ? {'name': 'zhangsan', 'age': 18, 'gander': 'man'}
print(dict)
counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
dict2={(key,value) for key,value in counts.items() if value>200}? ? ? {('DELL', 201), ('MBP', 268)}
print(dict2)
20,集合推導(dǎo)式
list3=[10,20,20]
set={i **2 for i in list3}
print(set)? ? ? ? ? ? ? ? {400, 100}
21,函數(shù)嵌套
# 函數(shù)調(diào)用
# def select_fun():
#? ? print("請選擇項目")
#? ? print("取錢")
#? ? print("查詢余額")
#
# input("請輸入密碼:")
# select_fun()
# 形參實參調(diào)用
# def add(a,b):
#? ? ? #這是求和
#? ? ? result=a+b
#? ? ? result2=result/2
#? ? ? print(result2)
#
# add(10,20)
# return返回函數(shù)的值? ? 作用:①返回數(shù)值,②推出函數(shù)
# def add(a, b):
#? ? # """求和"""
#? ? # return a + b
#? ? '''求積'''
#? ? return a*b
#
# result=add(10, 20)
# print(result)
# 函數(shù)嵌套
# def testA():
#? ? print("這是testA")
#
# def testB():
#? ? print("這是testB")
#? ? testA()? ? ? ? #testB里嵌套testA
#
# testB()
# 打印橫線--
# def line():
#? ? print('-'*20)
#
# def Mul_line():
#? ? i=0
#? ? while i < 5:
#? ? ? ? line()
#? ? ? ? i+=1
#
# Mul_line()
22,全局變量局部變量
# a=100
# def mun():
#? ? # print(a)? # a屬于全局變量
#? ? b=50? ? ? ? #b屬于局部變量
#? ? a=200? ? ? #修改全局變量
#? ? print(a)? ? #a修改后的局部變量
#? ? print(b)
# mun()
23,多函數(shù)調(diào)用
# glo_num = 0
# def test1():
#? ? global glo_num? #global告訴解析器glo_num是全局變量
#? ? glo_num = 100
#
# def test2():
#? ? print(glo_num)
#
# test1()? ? 調(diào)用test1只是將glo_num修改
# test2()? ? 調(diào)用test2才是輸出
24,函數(shù)參數(shù),
# 位置參數(shù):定義參數(shù)的順序跟個數(shù)必須一致
def userinfo(name,age,gander):
print(f'您的名字是{name},年齡是{age},性別是{gander}')
# userinfo("zhangsan",15,"man")
# 關(guān)鍵字參數(shù):關(guān)鍵字可以不安順序,但是當(dāng)有位置參數(shù)時,位置參數(shù)必須在關(guān)鍵字參數(shù)前面,不能在最后
# userinfo("lisi",age=15,gander="女")
#缺省參數(shù):也叫默認(rèn)參數(shù)
# def user_info(name,age,gander="男"):
#? ? print(f'您的名字是{name},年齡是{age},性別是{gander}')
# user_info("joseph",15)? ? 如果缺省參數(shù)未傳值則用默認(rèn)值
# user_info("Tom",25,"女")? ? 如果都傳值,就用傳的值
# 不定長參數(shù):無論是包裹位置參數(shù)還是包裹關(guān)鍵字參數(shù)都是組包的過程
# 包裹位置參數(shù):用于不確定參數(shù)個數(shù)的時候,
# def user_info(*args):
#? ? print(*args)
# user_info("tom")
# user_info("jack","男")
# user_info("tom",15,"女")
# 包裹關(guān)鍵字參數(shù)
# def user_info(**kwargs):
#? ? print(kwargs)
# user_info(name="tom",age=15,gender="女")
25,拆包
# 拆包元組
# def num():
#? ? return 100,200
# num1,num2=num()
# print(num1)
# print(num2)
# dict={"name":"zhangsan","age":15}
# name,age=dict
# print(name)? ? #字典拆包得到的是key
# print(age)
# print(dict[name])? #zhangsan