小白自用笔记如有错误还请见谅
首先将自己的python设置中文版、调整字号、设置背景等等
【1】常用快捷键
运行: Shift+Ctrl+F10
重新运行: Ctrl+F5
返回上一步:Ctrl+z
重构: Shift+F6 可将所有名字为name1的换成name2
光标移动到最左/右: Fn+左/右
光标向左/右移动一位:Ctrl+左/右
光标向左/右选中一格单词:Ctrl+Shift+左/右
光标选中一行:Ctrl+Alt+T
调出表情符: Win + ;
删除单个单词: Ctrl + 删除
光标不动实现换行: Ctrl + 换行
查看某函数源码: Ctrl+B
(在pycharm中把鼠标定位到这个函数,然后用快捷键去查看)
更多参考
https://blog.csdn.net/yuanqimiao/article/details/106308121(https://blog.csdn.net/cuomer/article/details/81534140)
【2】引号
'''
(1)三个单引号有多行注释的作用
(2)#是单行注释
(3)' 和 "灵活使用能让句子中的’s更清晰
(4)在字符串赋值时可以多行赋值
'''
message = '''Hello World:
What a wonderful day!
Dosen't it?'''
'''输出为:
Hello World:
What a wonderful day!
Dosen't it?
'''
message = 'Hello'\
' world'
#输出为Hello world
【3】变量+字符串
变量
python 3 math module见下链接
https://docs.python.org/3/library/math.html
message = ' Liu yuhang ' # 也可使用" "
# \t \n、强行转换、+ - * / +=、> < >= <= ==等与c相同 **为幂(** > * = / > +=- )
# 10//3 = 3
# 10/3 =3.333333
#数字相关的函数
import math
print(round(2.9)) #四舍五入函数
print(abs(-2.9)) #绝对值函数
print(math.ceil(2.7)) #取大
print(math.floor(2.7)) #取小etc
字符串
replace使用时
【1】原有字符串调用修改后原有字符串没有修改,而是返回值进行了修改,需要设置变量进行储存,体现了字符串是不可变类型数据(列表或者字典就是可变类型)
【2】替换次数省略后默认是所有都替换
【3】替换次数大于存在次数,是将所有都替换
length = len(message) #获取message的长度
print(message.capitalize()) #字符串的第一个字母大写
print(message.title()) #开头字母大写
print(message.upper()) #所有字母大写
print(message.lower()) #所有字母小写
print(message.strip()) #首尾去掉空格
print(message.lstrip()) #去掉左空格
print(message.rstrip()) #去掉右空格
new_str = message.ljust(10,'*') #共10位,左对齐,*补空
new_str = message.rjust(10,'*') #共10位,右对齐,*补空
new_str = message.center(10,'*') #共10位,中间对齐,*补空
position = message.find('y')
#返回第一次出现y的位置
# position = message.find('yuhang') 返回yuhang首字母出现的位置
print('Liu' in message)
#若Liu存在返回message则返回True,否则返回False
print(message.replace('i','aa')) #用aa替换i,message.replace('i','aa',1)再打印message则无变化
first = 'jonhn'
second = 'smith'
name = f'{first} [{second}] is a coder'
print(name)# ==> jonhn [smith] is a coder
判断真假
【1】是否以特定字符串开头/结尾,stratswith() / endswith() 是返回True,否则返回False
str = 'hello, my dear'
print(str.startswith('hello'))
print(str.endswith('dear'))
【2】isalpha():如果字符串至少一个字符并且所有字符都是字母则返回True,否则False
【3】isdigit():如果字符串至少一个字符并且所有字符都是数字则返回True,否则False
【4】isalnum():如果字符串至少一个字符并且所有字符都是字母或数字则返回True,否则False
(即【3】和【4】的并集)
str = 'hello my dear'
print(str.isalpha())#返回False
str = 'hellomydear'
print(str.isalpha())#返回True
str = 'hello my dear1'
print(str.isdigit()) #返回False
str = '12345'
print(str.isdigit())#返回True
str = 'hello1my3dear*'
print(str.isalnum()) #返回False
str = 'hello1my3dear'
print(str.isalnum()) #返回True
【5】isspace():如果字符串中只包括空白,则返回True否则返回False
str = ' ** '
print(str.isspace()) #返回False
str = ' '
print(str.isspace()) #返回True
【4】if语句
is_hot = True
is_cold = False
if is_hot:
print("It's a hot day")
print("Drink plenty of water")
elif is_cold:
print("It's a cold day")
print("Wear warm clothes")
else:
print("It's alovely day")
print("Enjoy your day")
#小习题,实现将英镑和千克的转化
weight =int(input("weight: ")) #input 返回str类型
choice = input("(L)bs or (K)g:")
if choice.title() == 'L':
last = weight * 0.45
print(f'you are {last} kilos')
elif choice.title() == 'K':
last = weight / 0.45
print(f'you are {last} pounds')
【5】逻辑运算符
has_high_income = True
has_good_credit = False
if has_good_credit and has_high_income:
print("逻辑与")
elif has_good_credit or has_high_income:
print("逻辑或")
elif has_good_credit and not has_high_income:
print("逻辑非")
【6】while循环
#习题:三次以内猜数
import random
correct_num = random.randint(0,9)
guess_count = 1
guess_max = 3
while guess_count <= guess_max:
x = int(input("Guess:"))
if x == correct_num:
print("You Win!")
break
else:
if guess_count >= 3:
print("You Lose")
break
guess_count += 1
#习题:打印九九乘法表
x = y = 1
while x<10:
y = 1
while y <= x:
print(f'{y}*{x}={x*y}',end=" ")
y+=1
print()#print('')会多一行空行
x+=1
while-else语句
示例1:
i=1
while i<=3 :
print("* ")
i+=1
else:
print("while-else 结束")
#while循环结束后执行else部分与直接print("while-else 结束")作用一样
示例2:
如果while中有break则不会执行else后的语句,但如为else则会执行else后的语句
i=1
while i<=3 :
print("* ")
i+=1
if i==2:
print("while-else 提前结束")
break
else:
print("while-else 结束")
【7】字符列表
访问
根据下标访问或者遍历
lovely_day = ['WakeUp','reading','breakfast','studying','etc']
#访问
print(lovely_day[0]) #打印下标为0的元素
print(lovely_day[-2]) #打印倒数第二个元素
for x in lovely_day:
print(x)
查找
in,find,count,index同样适用于字符串
lovely_day = ['WakeUp','reading','breakfast','studying','etc']
n = len(lovely_day) #求列表元素个数
print('etc' in lovely_day)
#检查etc是否在列表里,在返回True否则False
print('etc' not in lovely_day)
#检查etc是否不在列表里,不在返回True否则False
n = lovely_day.count('reading')
#查列表中reading出现的次数,不存在为0
print(lovely_day.index('studying'))
#从左找studying 的首字母的下标,不存在报错
#rindex() : 与index一致,从右向左查找 不存在报错
str = 'Hello my dear'
print(str.find("my", 0, len(str)))
#从左找到my的第一个字母的下标
#rfind():与find一样区别是这个从右侧开始查找
添加
【1】末尾添加,或者通过下标插入一个
lovely_day = ['WakeUp','reading','breakfast','studying','etc']
lovely_day.append('sleep')
#在列表末尾加上元素sleep
lovely_day.insert(4,'sleep')
#在下标为4的前面加上sleep
【2】添加n个元素的方法
lovely_day = ['WakeUp','reading','breakfast','studying','etc']
n = int(input('请输入添加元素数量:'))
i = 1
str =''
while i<=n:
str = input(f'请输入添加的第{i}个元素:')
i+=1
lovely_day.append(str)
print(lovely_day)
【3】添加一个序列的方法:extend()
lovely_day = ['WakeUp','reading','breakfast','studying','etc']
#把['a','bb','ccc']添加到列表后面
lovely_day.extend(['a','bb','ccc'])
print(lovely_day)
#把[ '1', '2', '3', '4']添加到列表后面
lovely_day.extend('1234')
print(lovely_day)
【3】复制列表:copy()
day2 = lovely_day[ : ]
#将lovely_day的元素全部复制到day2,可以前后加范围
day2 = lovely_day.copy()
#将lovely_day的元素全部复制到day2
day2.append('sleep')
删除
del(lovely_day[1])
#删除元素
disapper = lovely_day.pop(2)
#将lovely_day[2] 删除的同时将其赋给disapper,不加数字默认删除最后一个
lovely_day.remove('breakfast')
#将第一个为breakfast的元素移除
lovely_day.clear() #清空列表
排序
lovely_day.sort()
#按照字典排序 或用 lovely_day.sort(reverse=False)
lovely_day.sort(reverse=True)
#按照反字典排序
print(sorted(lovely_day))
#临时排序
lovely_day.reverse()
#列表元素前后倒置
分割+合并
【1】分割split(分割字符串如‘my’,num):
将my两边分割开,num表示分割my的次数。如括号内不加变量,则将字符串的每个单词分割成列表中的元素
str = 'hello my dear, my name is lyh'
new_str = str.split('my',2)
print(new_str)
【2】合并join(str):
将列表中的元素合并。合并后用‘ ’隔开
str = ['hello','my','dear']
new_str = ' '.join(str)
print(new_str)
【8】数字列表
(1)一维
number = [1,2,3,7,1,2]
x = min(number)
x = max(number)
x = sum(number)
for integer in range(0,11,2):
print(integer)#打印1-10的偶数
squares = [value**2 for value in range(1,10) ]
#squares = [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(number[:3]) #打印number[0]到number[2]
print(number[-2:]) #打印倒数第二个到number[0]
for x in number[:3]:
print(x)
(2)元组:即不可对元素修改的列表
多数据元组: unchange = (200,50)
单个数据元组:unchange = (200,)
元组不支持修改,支持查找如:index,count,len
unchange = ('a','bb','ccc','a')
print(unchange.index('ccc'))
print(unchange.count('a'))
print(len(unchange))
but 可以利用变量名进行修改
unchange = (200,50)
unchange =(200,2,1,50)
print(unchange)
(3)解压(同样适用于列表)
必须左边的变量数=元素数
#解压(同样适用于列表)必须左边的变量数=元素数
a,b,c,d = number
print(f'{a} {b} {c} {d}')
(4)二维(列表中的列表)
与C语言中的二维数组类似:第一个下标取行,第二个下标取列
number = [
[1,2,3],
[4,5,6],
[7,8,9]
]
for row in number: #遍历二维列表
for y in row:
print(y)
【9】字典
(1)创建字典
customer ={
"name" : "lyh",
"age" : 30,
"sign_or_not" :True
}
#空字典
customer={}
customer=dict()
(2)字典基本操作
1.查
print(customer['name'])
#输出lyh
print(customer.keys())
#输出:dict_keys(['name', 'age', 'sign_or_not'])
#返回可迭代的对象
print(customer.values())
#输出:dict_values(['lyh', 30, True])
#查找字典中所有的value,返回可迭代的对象
print(customer.items())
#输出:dict_items([('name', 'lyh'), ('age', 30), ('sign_or_not', True)])
#
'''找字典中所有键值对,返回所有可迭代对象
里面的数据全是元组,元组数据1是字典的key
元组数据2是字典key对应的值
'''
2.增
print(customer.get("age"))
print(customer.get("birdate","Jan 8 2001"))
#如果原来没有birthdate则增加birthdate,并赋值为Jan 8 2001
customer["birthdate"] = "Jan 8 2001"
#增加
print(customer["birthdate"])
3.修
customer["name"] = 'liu yuhang'
print(customer["name"])
4.删
del(customer["name"]) #删除键值对
customer.clear() #清空
5.遍历
遍历key
customer ={
"name" : "lyh",
"age" : 30,
"sign_or_not" :True
}
for key in customer:
print(key,end=' ')
遍历values
for key in customer:
print(customer[key],end=' ')
#或
for value in customer.values():
print(value,end=' ')
#lyh 30 True
遍历元素
for iterm in customer.items():
print(iterm,end=' ')
#('name', 'lyh') ('age', 30) ('sign_or_not', True)
遍历字典的键值对(拆包)
字典序列.items():返回可迭代对象,内部是元组,元组是两个数据,数据1是key,数据2是value
customer ={
"name" : "lyh",
"age" : 30,
"sign_or_not" :True
}
for key,value in customer.items():
print(f'key={key} value={value}',end=' ')
#key=name value=lyh key=age value=30 key=sign_or_not value=True
(2)习题:
1.将1234变为One Two Three Four
phone = input("Phone :")
change ={
"1" : 'One',
"2" : 'Two',
"3" : 'Three',
"4" : 'Four'
}
output = '' #一定要定义
for ch in phone:
output += change.get(ch ,'!') +' '
#如果get后面的ch不属于字典则将!保存到output
print(output)
2.实现以下效果
输入:>I am sad :(
输出:I am sad (╬▔皿▔)╯
代码
message = input(">")
word = message.split(' ')
#可产生 word = ['I', 'am', 'sad',':(']的效果
emojs = {
":)" : 'o(*^@^*)o',
":(" : '(╬▔皿▔)╯'
}
out = ""
for x in word:
out += emojs.get(x,x) + ' '
#入果找到对应则替换否则不变
print(out)