1,註釋(ctrl+/)
單行註釋用#
多行註釋用""" """
2,變量定義(遵循標識符規則,駝峯命名)
變量名=值
3,數據類型
#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,格式化輸出
格式化符號格式數據
%s 字符串
%d 帶符號的整數型
%f 浮點型
name='joseph'
age=26
whight=75.2
stu_id=2
stu_id2=102
# 我的名字是joseph
print("我的名字是%s" % name)
#我的年齡是
print("我的年齡是%d" % age)
#我的體重是
print("我的體重是%f" % whight) --默認是保存6爲小數
print("我的體重是%.2f" % whight) --保留兩位小數
#我的學號是
print("我的學號是%03d" % stu_id) --比如要輸出002,%03d是輸出3位數,不夠的用0補齊
print("我的學號是%02d" % stu_id2) --102 要輸出2位數,超過的保持原狀
#我的名字是x,年齡是x,體重是x,學號是x
print("我的名字是%s,年齡是%d,體重是%.2f,學號是%02d" % (name,age,whight,stu_id))
print("我的名字是%s,年齡是%s,體重是%s,學號是%s" % (name,age,whight,stu_id)) --所有類型強制轉換爲string
print(f"我的名字是發{name},年齡是%{age},體重是{whight},學號是{stu_id}") --f{}形式比較高效
4,換行符\n,製表符\t(四個空格)
5,輸入
input:1.當用戶執行到input時,等待用戶全部輸入完纔開始執行
2.接收到數據後一般存儲到變量,並以字符串形式處理
password=input("請您輸入密碼:")
print(f"您輸入的密碼是{password}")
print(type(password))
6,數據類型轉換(跟java的強制轉換一樣)
int,float,str,list,tuple,eval
#string轉int/float
age="15"
print(type(int(age)))
print(int(age))
print(type(float(age)))
print(float(age))
#List轉tuple
b=[15.65,85]
print(type(tuple(b)))
print(tuple(b))
#tuple轉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表達式(原來是什麼轉換後還是什麼)
print(type(eval(d)))
7,運算符
算數運算符(+,-,*,/,//(整除9//4=2),%(取餘),**(指數2**3=8),()括號) --()優先級依次** * / // % + -
賦值運算符
a,b,c=15,(10,15),"hello" --多變量賦不同值
print(a)
print(b)
print(c)
a=b=c=15 --多變量賦相同值
print(a)
print(b)
print(c)
複合賦值運算符(+=,-=,*=,/=,//=,%=,**=)
a=10
a+=1+2 #結果是13,是先執行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,否則返回結果爲最後一個非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 --條件成立執行的語句 if 條件 else 條件不成立執行的語句
print(c)
10,while嵌套循環及break跟continue的應用
i=1
while i<=5:
if i==3:
print(f"媳婦,這是我第{i}次錯了")
i += 1 #內循環+1,是爲了不會再遇到i==3
continue #如果是continue,則表示跳出本次循環,接着循環,若是break,則直接終止循環
print("媳婦我接着錯了")
i+=1 #外循環+1,是爲了接着循環
#嵌套,各自的條件應放在各自的代碼塊區域,例如:i放在內部自己的代碼塊
j=1
while j<=3:
i=1
while i<=5:
print("媳婦,我錯了")
i+=1
print("我錯了,今晚我刷碗") #這種形式是循環結束打印這句
j+=1
print("這是循環三遍")
#九九乘法表
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循環(類似java的增強for循環)
str="joseph"
for i in str: #類似於增強for循環
if i=="p":
break #遇到break循環結束,不會打印“哈哈”,如果是contine,不打印'p',接着循環打印'哈哈'
print(i)
else:
print("哈哈")
12,字符串下標及切片
# 序列名[開始位置的下標:結束位置的下標:步長] --不包含結束下標位置的值
str1 = '012345678'
# print(str1[2:5:1]) # 234
# print(str1[2:5:2]) # 24
# print(str1[2:5]) # 234 --默認步長是1
# print(str1[:5]) # 01234 -- 如果不寫開始,默認從0開始選取
# print(str1[2:]) # 2345678 -- 如果不寫結束,表示選取到最後
# print(str1[:]) # 012345678 -- 如果不寫開始和結束,表示選取所有
# 負數測試
# print(str1[::-1]) # 876543210 -- 如果步長爲負數,表示倒敘選取
# print(str1[-4:-1]) # 567 -- 下標-1表示最後一個數據,依次向前類推
# 終極測試
# print(str1[-4:-1:1]) # 567
print(str1[-4:-1:-1]) # 不能選取出數據:從-4開始到-1結束,選取方向爲從左到右,但是-1步長:從右向左選取
# **** 如果選取方向(下標開始到結束的方向) 和 步長的方向衝突,則無法選取數據
print(str1[-1:-4:-1]) # 876
13,字符串常用操作
#1.find查找數據 字符串.find("字串",開始位置,結束位置)
str="hello python and hello java and hello scala"
# new_str=str.find("and") #13 不加位置,全盤查找
# new_str=str.find("and",15,35) #28 加位置,在開始結束位置裏查找
# 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) #加位置,在開始結束位置裏查找
# new_str=str.index("ands") #如果沒有報錯
# new_str=str.rindex("and") #從右側開始查找and,然後從左算索引位置
# print(new_str)
#3.count,字串出現的次數
# new_str=str.count("and")
# new_str=str.count("hello")
# new_str=str.count("hello",10,60) #當結束位置超過索引值時,按全局查
# print(new_str)
#4.replace替換字串 字符串.replace("舊字串","新字串","次數")
# new_str=str.replace("and","he",1) #替換一次
#new_str=str.replace("and","he",8) #超過的,就全部替換
# print(new_str)
# 5.split切割,字符串.split(“分割字符”,次數)
#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 將字符串中大寫轉小寫
#str2="Hello Java,How Are You"
#new_str=str2.lower() --hello java,how are you
#print(new_str)
#10.upper 字符串所有小寫轉大寫
#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刪除字符串右側空白
# str="Hello MoTo "
# new_str=str.rstrip() --Hello MoTo
# print(new_str)
# 13.strip 刪除字符串兩側空白
# str=" Hello Joseph "
# new_str=str.strip() Hello Joseph
# print(new_str)
# 14.ljust 返回原字符串,左對齊,並使用指定字符,填充至對應長度的新字符串
# 字符串.ljust(長度,填充字符)
# str="wufan"
# new_str=str.ljust(10,"*") --wufan*****
# new_str=str.ljust(10) --wufan 不寫默認是空格
# print(new_str)
# 15.rjust 返回原字符串,右對齊,並使用指定字符,填充至對應長度的新字符串
# str="wufan"
# new_str=str.rjust(10,"#") #####wufan
# print(new_str)
# 16.center 返回原字符串,中心對齊,並使用指定字符,填充至對應長度的新字符串
# str="wufan"
# new_str=str.center(10,"*") **wufan***
# print(new_str)
# 17.startswith 是否以指定字串開始,真返回ture,假返回false,如果寫位置,則再指定範圍內查找
# 18.endswith 是否以指定字串結束,真返回ture,假返回false,如果寫位置,則再指定範圍內查找
# 字符串.startswith("字串/字母",開始位置,結束位置)
# new_str=str.startswith("hel")
# new_str=str.startswith("hel",10,20)
# new_str=str.endswith("scala")
# print(new_str)
# 19.isalpha,字符串中全是字母
# 20.isalnum 字母或數字
# 21.isspace 只包含空格
# str="abc"
# str2="abc12"
# str3="java haha"
# print(str.isalpha())
# print(str2.isalnum())
# print(str3.isspace()) --false
14,列表
# 1.index返回數據的下標索引 列表.index(數據,開始位置下標,結束位置下標)
# 2.count 數據出現的次數
# 3.len 列表的長度(列表有幾個數據)
# 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 列表結尾追加數據
# 6.entend 列表結尾追加數據,如果數據是一個序列,則拆開後加到原數列裏
# 7.insert 指定位置添加 列表.insert(索引位置,數據)
# 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'] 如果是數列,拆開添加
# name_list.insert(0,"zhangsan") --['zhangsan', 'lily', 'Tom', 'Jackson']
# print(name_list)
# ---刪除---
# 8.del刪除
# 9.pop刪除指定位置的數據,默認是最後一個 列表.pop(索引下標)
# 10.remove() 列表.remove(數據)
# 11.clear 清空列表
# del name_list[0] --['Tom', 'Jackson']
# name_list.pop() --['lily', 'Tom']
# name_list.pop(1) --['lily', 'Jackson']
# name_list.remove("Tom") --只能刪除一個數據
# name_list.clear() --[]
# print(name_list)
# ---修改---
# 12.reverse 順序反轉
# 13.sort 排序 數列.sort(key=None, reverse=False) true降序,false升序
# 14.copy 複製
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)
# ---循環---
# 15.while循環打印列表數據
# 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) #多數據元組
t2=(10,) #單數據元組
t3=(20)
# print(type(t3)) <class 'int'>單數據也得加逗號‘,’否則是數據本身的類型
# 1.按索引
# 2.知道數據查索引。元組.index()
# 3.統計某個數據在元組的出現的次數
# 4.統計元組裏的數據長度
# print(t1[0]) 10 元組不允許修改,只支持查詢
# print(t1.index(20)) 1
# print(t1.count(50)) 2
# print(len(t1)) 6
# 16.字典:大括號,數據爲鍵值對,各個鍵值對逗號分割
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.集合,創建集合用{},空集和用set(),因爲{}是用來創建空字典的
s1={10,20,30,40,50,50}
s2=set()
s3={}
# print(s1) {40, 10, 50, 20, 30}集合去重無序,故不支持索引查詢
# print(type(s2)) <class 'set'>
# print(type(s3)) <class 'dict'>
# 1.add,update,remove,discard,pop,in,not in
# s1.add(20) 去重,所以加不進去集合中已有的數據
# s1.update([60,70]) update(列表){70, 40, 10, 50, 20, 60, 30}
# s1.remove(50) {40, 10, 20, 30}
# s1.remove(80) 刪除指定元素,數據不存在則報錯
# s1.discard(50) {40, 10, 20, 30}
# s1.discard(100) 刪除指定元素,數據不存在不報錯
# print(s1.pop()) 隨機刪除某個數據,並返回這個被刪數據
# 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生成序列,不包含結束值 range(開始值,結束值,步長)
# print(i)
# enumerate(可遍歷對象,start=0) (0, 10)(1, 20)(2, 30)(3, 50)
# for i in enumerate(list1):
# print(i)
18.列表推導式
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,字典推導式:快速合併列表爲字典,或字典裏的數據
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,集合推導式
list3=[10,20,20]
set={i **2 for i in list3}
print(set) {400, 100}
21,函數嵌套
# 函數調用
# def select_fun():
# print("請選擇項目")
# print("取錢")
# print("查詢餘額")
#
# input("請輸入密碼:")
# select_fun()
# 形參實參調用
# def add(a,b):
# #這是求和
# result=a+b
# result2=result/2
# print(result2)
#
# add(10,20)
# return返回函數的值 作用:①返回數值,②推出函數
# def add(a, b):
# # """求和"""
# # return a + b
# '''求積'''
# return a*b
#
# result=add(10, 20)
# print(result)
# 函數嵌套
# 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,多函數調用
# glo_num = 0
# def test1():
# global glo_num #global告訴解析器glo_num是全局變量
# glo_num = 100
#
# def test2():
# print(glo_num)
#
# test1() 調用test1只是將glo_num修改
# test2() 調用test2纔是輸出
24,函數參數,
# 位置參數:定義參數的順序跟個數必須一致
def userinfo(name,age,gander):
print(f'您的名字是{name},年齡是{age},性別是{gander}')
# userinfo("zhangsan",15,"man")
# 關鍵字參數:關鍵字可以不安順序,但是當有位置參數時,位置參數必須在關鍵字參數前面,不能在最後
# userinfo("lisi",age=15,gander="女")
#缺省參數:也叫默認參數
# def user_info(name,age,gander="男"):
# print(f'您的名字是{name},年齡是{age},性別是{gander}')
# user_info("joseph",15) 如果缺省參數未傳值則用默認值
# user_info("Tom",25,"女") 如果都傳值,就用傳的值
# 不定長參數:無論是包裹位置參數還是包裹關鍵字參數都是組包的過程
# 包裹位置參數:用於不確定參數個數的時候,
# def user_info(*args):
# print(*args)
# user_info("tom")
# user_info("jack","男")
# user_info("tom",15,"女")
# 包裹關鍵字參數
# 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