Python学习笔记1

在B站看网课重新学一下Python,方便以后写盲注脚本或者一些有意思的脚本,比如爬虫、讲课抢票等等。

注释符

1.#单行注释

2.多行注释

1
2
3
'''
三个单引号包裹的是多行注释
'''

多行注释也可以先选中多行然后按Ctrl+/来实现

另外,三个单引号包裹赋值给变量的话表示多行字符串,例如:

1
2
3
a='''hello
world'''
print(a)

输出

print()函数打印输出

1
2
3
4
print("hello world") #end不写默认为\n,即默认自动换行
print("hello world",end='') #不换行输出,end里面也可以写其他的东西
print("aaa","bbb","ccc") #,输出空格来分隔字符串
print("www","baidu","com",sep=".") #sep是分隔符,输出www.baidu.com

格式化输出

{}:等等

f-str

1
2
3
4
import math
name=Tianze
print(f'my nickname is {name}') #f也可以大写
print(f'the value of pi is approximately {math.pi:.3f}')

str.format()

1
2
3
4
5
6
print("{} {}".format("hello","world"))
#花括号里不加数字则顺序,加数字可以指定位置,第一个为0
print("{1} {0}".format("hello","world")) #输出world hello
print("{0} {1} {0}".format("hello","world")) #输出hello world hello
#话括号里也可以设置参数
print("my name is {name}".format(name="Tianze"))

str%value

1
2
print("my name is %s"%"Tianze")
print("my age is %d"%20)

输入

input()函数用于输入,输入的值为str类型,若想得到整数类型,要使用int()强制类型转换

1
2
3
4
5
6
password=input("请输入你的密码")
print(type(password)) #type()函数输出变量类型,这里为str
print("你的密码为",password)

a=int(input()) #这里int()把输入值强制类型转换为int
print(a+100)

运算符

算术运算符(加减乘除等)、比较运算符(== !=等)、位运算符(& |等)、逻辑运算符(and or等)都和其他语言差不多。但python还有成员运算符(in、not in)和身份运算符(is、not is)

条件判断语句

非0和非空值为True,0或者None为False,需要注意的是True和False必须首字母大写才有意义。

python中else if要写成elif,并且不用{},而用:

python的缩进很重要,尤其是嵌套很多的时候

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if True:
print("True")
else:
print("False")

score=89
if score>=90 and score<=100: #这里也可以写成90<=score<=100
print("A")
elif score>=80:
print("B")
elif score>=70:
print("C")
elif score>=60:
print("D")
else:
print("E")

import和from import

python用import或者from...import来导入模块,相当于用别人写好的一些功能,我们也可以自己写一个py文件,然后导入。

整个模块导入:import module

从某个模块中导入某个函数:from module import function

从某个模块中导入多个函数:from module import func1,func2

导入模块中的所有函数:from module import *

as起别名:import module as xxx或者from module import function as xxx

random随机库

1
2
x=random.randint(0,2) #随机生成[0,2]的数字
print(x)

小练习

综合使用if语句,实现剪刀石头布游戏效果,显示如下提示信息:

1
请输入:剪刀(0)、石头(1)、布(2):

用户输入数字0-2中的一个,与系统随机生成的数字比较后给出结果信息。

例如:输入0后,显示如下:

1
2
3
你的输入为:剪刀(0)
随机生成数字为:1
哈哈,你输了:)

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import random
a=int(input("请输入:剪刀(0)、石头(1)、布(2):"))
b=random.randint(0,2)
print("随机生成数字为:{}".format(b))
if a==0:
if b==0:
print("平局")
elif b==1:
print("哈哈,你输了:)")
else:
print("哈哈,你赢了:)")
elif a==1:
if b==0:
print("哈哈,你赢了:)")
elif b==1:
print("平局")
else:
print("哈哈,你输了:)")
else:
if b==0:
print("哈哈,你输了:)")
elif b==1:
print("哈哈,你赢了:)")
else:
print("平局")

运气真好,第一次运行结果就和示例一样

image-20210418164205888

参考

https://www.bilibili.com/video/BV12E411A7ZQ

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码
  • Copyrights © 2020-2021 Blog of Tianze

请我喝杯咖啡吧~

支付宝
微信