python语法基础(一)

常量与字符串

a = 10
print(a)

a = 'string'
print(a)

print((32 + 24 + 12) / 3)

10

string

22.666666666666668

变量和类型

a = 3
b = 4
c = a + b
total = a ** b + c

print(total)

88

定义变量

a = 3
b = 4

a = b

print(a)
print(b)

4

4

变量类型

a = 3
print(type(a))

b = 3.0
print(type(b))

c = 'hellp python'
print(type(c))

# 计算c的长度
print(len(c))

d = True
print(d)

# 使用 + 可以连接字符串
e = 'hello'
f = ' world'
print(e + f)

12

True

hello world

动态类型

a = 4
print(type(a))

a = 'hello'
print(type(a))

通过控制台输出

a = 3
print(a)

# 混合字符串和变量输出
print(f'num = {a}')

# 使用f作为前缀的字符串,称为f-string
# {}里可以嵌套其他变量和字符串

3

num = 3

通过控制台输入

num = 0
num = input('输入num的值')

print(f'num = {num}')

# input返回值为字符串
a = 0
b = 0
a = input('输入a的值') 
b = input('输入b的值')

# 强制类型转换
a = int(a)
b = int(b)

print(f'a + b = {a + b}')

num = 32

a + b = 35


a = '12345'
a = int(a)

print(a)

12345


# python中int的范围理论上是没有上限的
a = 123111111111111111111111111
print(a)

123111111111111111111111111


# 不能做除0操作
# error
print(10 / 0)

a = 10 / 3
print(a)

# 向下取整
a = 10 // 3
print(a)

a = 10 % 3
print(a)

a = 4 ** 2
print(a)

3.3333333333333335

3

1

16

关系运算符

a = 10
b = 20

print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)

True

True

False

False

False

True


# python中,关系运算符不光针对整数/浮点数进行比较, 还能针对字符串进行比较.
a = 'hello'
b = 'world'

print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)

True

True

False

False

False

True


# 对浮点数来说,不要用 == 判定相等
a = 3.0
b = 3.0

print(a == b)

c = 1.0
d = 2.0
print(a == c + d)
print(a)
print(c + d)

print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)
print(0.3)

# 正确的做法,不再严格比较相等,而是判定差值小于允许的误差范围
a = 0.1 + 0.2
b = 0.3
print(-0.000001 < (a - b) < 0.000001)

True

True

3.0

3.0

False

0.30000000000000004

0.3

True

逻辑运算符


a = 10
b = 20 
c = 30 

print(a < b and b < c)
print(a < b and b > c)

print(a > b or b > c)
print(a < b or b > c)

print(not a + b or c)
print(not c or a)
print(a and b)
print(a or b)
print(not a)

print(a < b < c)

False

True

False

False

True

30

10

20

10

False

True

赋值运算符

# 链式赋值
a = 10
b = 20

# 多元赋值
c, d = 10, 20
print(c,d)
print(f'c,d = {c, d}')  

10 20

c,d = (10, 20)


# 交换两个变量

# 方法一
a = 5
b = 10

temp = a
a = b
b = temp
print(a,b)

# 方法二: 基于多元赋值
c = 5
d = 10

c, d = d, c
print(c, d)

10 5

10 5

复合赋值运算符

a = 10
b = 30

a += 3
print(a)
a -= 4
print(a)
b /= a
print(b)
b *= 2
print(b)

13

9

3.3333333333333335

6.666666666666667


# 整型可以和布尔型混合运算
a = 3
b = True
c = a + b
print(c)

4

你可能感兴趣的:(Python(语法,爬虫,数据分析),python,开发语言)