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
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
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 # 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)) # 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)) # print(type(s3)) # 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