python快速入门笔记

python快速入门note

变量以及运算符

主要变量类型:

整数和浮点数
import math #导入数学库 https://docs.python.org/3/library/math.html
print(10//3) #整除
print(10%3) #mod求余
print(10**3) # 次方
print(round(2.9)) #四舍五入
print(abs(-2.9)) #绝对值
print (math.ceil(2.2)) #向上取整
bool值

ture 和false用来表示真假

例如

m1="yuan"
print("yu" in m1)  #返回值为true

# “”

# 0

# None

表示永假

而入1可以表示永真

运算

# and 同真则真

# or 一假则假

# not 就是非

字符型
message="""
jdsafiojslk;adffjdskl
dsfafdsakl
"""
message1= "jdsafiojslk;adffjdskldsfafdsakl"

用"“包含字符串,”’’" 可以包含多行字符串

打印字符串例:

print(message) #直接打印
print(len(message)) #len内置函数用来计算字符串的长度
print(message1[0]) # 用【】来message1中提取出第几个字符,从0开始计算
print(message1[-1])# 相当于在message1中向左移动1位,即最后一个字符
print(message1[0:3]) #相当于输出第一到第三个字符 
print(message1[0:])  #输出全部字符串

输出示例

34
j
l
jds
jdsafiojslk;adffjdskldsfafdsakl  #`
常用的字符串函数

#.可以用变量名.函数名的方式进行运用

upper()将所有字母大写

lower()将所有字母小写

title()首字母大写

strip()删去空格

find()寻找字符,返回值为整型

replace(“p”,“j”) 替换函数

格式化输出字符串

m1="yuan"
m2="pei"
m3= f"{m1} {m2}"  用f表示格式化输出,用{}包含要输出的变量
print(m3)
转义字符

例如"\n"为转义字符表示换行

gang="\""
print(gang)

输出" 号

如果一个字符串包含多个需要转义的字符, 我们可以在字符串前面加个前缀 r ,表示这是一个 raw 字符串,里面的字符就不需要转义了

print (r'\(~_~)/ \(~_~)/')

x= input("x: ")
y=int(x)+1
print(f"x: {x},y:{y}")

强制类型转化

# int(x)

# float(x)

# bool(x)

# str(x)

# type(x)

彩蛋

在终端输入import this 得到

 The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

循环和判断

条件语句

if

如果后面表达式真则执行冒号后缩进语句

elif

多条件同理,elseif的简写

else

如果为假则执行

tem=15
if tem>30:
    print("it is it")
    print("ok")
elif tem>90:
    print("okk")
else:
    print("yes") 
print("done")

循环

for
for number in range(1,10,2): # 步长为2,左闭右开
    print("yes", number,(number)*".")
for x in range(5): #二重循环,从0开始,遍历0,1,2,同理
    for y in range(3):
        print(f"({x},{y})")

in 后面可以是其他数据类型如list,string,你所定以的循环变量也就是那个类型

for x in "python":
    print(x)
# complex type list
for x in [1, 2, 3, 4]:
    print(x)
while
number = 100
while number > 0:
    print(number)
    number = number//2

常用while(true)来循环,break打断循环,

continue 不退出循环,不执行接下来的语句

num=0
while num <10:
    num+=1
    if num%2==0:
        continue
    
    print (num)
command=""
while  command.lower() != "quit" :
# while command != "quit" and command != "QUIT":# command.lower()
    command = input(">")
    print("ECHO",command)
#suojing 
# or
while True:
    command= input(">")
    print("ECHO",command)
    if command.lower() == "quit" :
        break
kong=[]
bukong=['a','b','c']
while bukong:
    huan=bukong.pop()
    kong.append(huan)

for kongs in kong:
    print(kongs)

while 和列表使用

函数

python中用def来定义一个函数,作用就是完成一个任务,或者计算一个结果 ,分别无返回值和有返回值

无参

就是调用函数时不传递参数

def greet():
    print("hello")
    print("ok")

greet()
有参

需要传递参数

def multiply(*numbers):
    total=1
    for number in numbers:
        total = number*total
    return total
print(multiply(2,3,4,5))
def save_user(**user): #the type dic
    print(user["id"])
save_user(id=1,name="yuan",age=22)
默认参数
def greet1(frist_name,last_name="yuanyuan"):# 默认参数从左往右
    print(f"hello {frist_name} {last_name}")
    print("ok")
    return f"hi {frist_name} {last_name}"
greet1("yuan","yuan")
print(greet1("yuan"))

在vscode中调试python程序

调试的基本步骤

  • 发现程序错误的存在。
  • 以隔离、消除的方式对错误进行定位。
  • 确定错误产生的原因。
  • 提出纠正错误的解决办法。
  • 对程序错误予以改正或重构,重新测试。

实际操作

def multiply(*numbers):
    total=1
    for number in numbers:
        total = number*total
        return total

print("Start")
print(multiply(1,2,3))

例如这一段python程序中,我们直接运行程序得到的结果为1与我们预期结果不一样,那么我们就可以手动对这段程序进行调试

  • 首先在程序输出之前打上一个断点(如代码第七行位置)可使用快捷键f9
  • 第二步按快捷键f5启动调试
  • 接着按f10使光标移到第8行
  • 接着按f11进入函数内部
  • 然后我们此时可以观察到左边变量窗口的变化如图
  • image-20210127173809097
  • 接着继续按f10运行程序发现整个循环只运行了一次
  • 那么可以推断出是return语句终止了循环,检查发现return的缩进不对,将return语句前移4格后重新调试程序正确。

总结

F5:启动调试

F10:执行下一行语句

F11:进入调用的函数

shift +f11 可以跳出函数

vscode快捷键

ctrl+/ 注释

home 行首

end 行尾

ctrl+ home 回到开头

ctrl+ end 回到末尾

ctrl+shift+p 打开控制面板

alt+上下左右 移动所选行

ctrl +alt+n run codes

字典以及列表

列表
letter= ["a","b","c"]
matrix=[[0,1],[2,3]] #二维矩阵 列表的嵌套
zeros = [0] *10 #✳可以重复列表中的参数
com=zeros+letter #+用来合并列表
print(com)

输出:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'a', 'b', 'c']

numbers=list(range(20))
str=list("hello" )
print(numbers[::2])
print(str)
print(str[-1]) # 索引方式访问列表元素

输出:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] ['h', 'e', 'l', 'l', 'o'] o

number=[1,2,3,4,5]
frist,second,*other = number #相当于把345压缩到了other里 同之前的一样
print(frist)

输出:1

letters ={"a","b","c"}
for letter in enumerate(letters):# 这个函数会返回一个枚举对象,它是可迭代的
    #print(letter) #得到的结果第一个参数是索引,第二个是列表的值
    print(letter[0],letter[1]) 

输出:0 c 1 a 2 b

修改

利用索引方式来修改

添加

.append()

插入

letters.insert(0,“1”)

删除
# remove 
letters =["a","b","c"]
letters.pop(0)# 默认弹出栈顶元素,还可以继续使用弹出的元素
letters.remove("b")
del letters[0:3]
letters.clear()
print(letters)
排序
letters=["d","b","c"]
print(letters.index("b")) #返回的是索引
print (letters.count("b")) # 返回这个列表中有多少匹配的对象
numbers=["1","2","3"]
numbers.sort() # 默认升序排列 
letters.sort(reverse=True) 降序
print(numbers)
print(letters)
print(sorted(numbers,reverse=True))# sort 会改变原先列表的值,但sorted不会能保留原来列表的顺序,他是返回一个新的列表

输出

1
1
['1', '2', '3']
['d', 'c', 'b']
['3', '2', '1']
# 复杂的排序
items =[
    ("product1",10),
    ("product1",7),
    ("product1",8),

]
def sort_item(item):
    return item[1]

items.sort(key=sort_item)
print(items)
列表的访问
letters=["a","b","c"]
for letter in letters :
    print(letter)
print("it is ok")

for number in range(1,5):
    print(number)

for number in range(10):
    print(number)
列表解析
list1=[value**2 for value in range(1,11)]
print(list1)
列表切片遍历
letters=["a","b","c"]
for letter in letters[0:2] :
    print(letter)
切片复制
letters=["a","b","c"]
new_letter=letters[:]
print (new_letter)

切片复制相当于创立了一个新的列表

元组

不可改的列表

yuanyuan =(200,300)
print(yuanyuan)
yuanyuan=(300,400)
print(yuanyuan)
字典

存储特定信息

gps={'x':2,'y':5,'z':2}
print(gps['x'])
for key,value in gps.items():
    print("key\n:",key)
    print("value\n",value)
for name in gps.keys():#key方法
    print(name)
for name in gps.values():#value方法
    print(name)
for name in set(gps.values()):
    print(name)
del gps['y'] #删除键
print(gps)
输出:
2
key
: x
value
2
key
: y
value
5
key
: z
value
2
x
y
z
2
5
2
2
5
{'x': 2, 'z': 2}
列表字典(字典作为列表元素)
a=[]
for num in range(20):
    dic={'x':2,'y':3}
    a.append(dic)
for a1 in a[:5]:
    print(a1)
字典列表

在字典里存储列表

dic1={
    'x':['a','b'],
    'y':['c']
}
for key ,values in dic1.items():
    print(key)
    for value in values:
        print(value)

输出:

x
a
b
y
c

字典嵌套
num=0
while num <10:
    num+=1
    if num%2==0:
        continue
    
    print (num)

类与对象:

文件操作:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值