数字类型

整数类型

$$
pow(x,y)用来计算x^y
$$

可以嵌套使用

浮点数类型

$$
e=a*10^b
$$

复数类型

设z=a+bj

对于复数z,用 z.real 和 z.imag 表示它的 实数 和 虚数 部分

内置操作符

​ + - * /

操作符 意义
x//y x与y的整数商
x%y 取余
-x x的负数
+x x本身
x**y x的y次幂

内置函数

函数 意义
abs(x) 绝对值
divmod(x,y) (x//y,x%y)输出为元组类型
pow(x,y[,z]) (x**y)%z
pow(x,y) x**y
round(x[,ndigits]) 对x四舍五入,保留ndigits位小数
round(x) 返回四舍五入的整数值
max(x1,x2,…,xn) 最大值
min(x1,x2,…,xn) 最小值

内置转换函数

函数 意义
int(x) 将x转换为整数
float(x) 返回浮点数x或者字符串x所对应的整数类型
complex(re[,im]) 生成复数,re为实部,im为虚部

math库

需要使用保留字import引用库

Method 1:

1
2
import math
math.<b>()

Method 2:

1
from math import <函数名>

字符串类型

字符串操作符

操作符 意义
x+y 连接字符串
x * n 或者 n * x 复制n次字符串x
x in s 如果x是s的子串,返回True,否则返回False
str[i] 索引,返回第i个字符
str[N:M] 切片,返回索引第N到第M的子串,其中不包含M

字符串类型的格式化

format()方法的基本使用格式:

1
<模板字符串>.format(<逗号分隔的参数>)

Tips

n%2的取值为0或1,可以判断整数n的奇偶

Exercises

3.1

1
2
3
4
5
6
#重量计算
weight = 50
for i in range(10):
weight=weight*(1+0.5/weight)
print("{:.0f}年后在地球上的体重为:{:.2f}kg".format(i+1,weight))
print("在月球上的体重为:{:.2f}kg".format(0.165*weight))

3.1

3.2

1
2
3
4
5
6
7
8
#天天向上续
dayup,dayfactor=1.0,0.01
for i in range(365):
if i%7 not in [0,1,2]:
dayup=dayup*(1+dayfactor)
else:
dayup=dayup
print("连续学习365天后能力值为:{:.2f}".format(dayup))

3.3

1
2


3.4

1
2
3
4
5
6
7
#回文判断
a=input("Input 5 numbers:")
b=a[::-1]
if a==b:
print("是回文")
else:
print("不是回文")

3.5

1
2
3
4
5
6
#田字格的输出
for i in range(11):
if i in [0,5,10]:
print("+ - - - -+- - - - +")
else:
print("| | |")

3.6

1
2