一. 整数、浮点数的运算规则
- 整数之间的加减乘运算,结果是整数,除法运算,结果是浮点数
- 有浮点数的运算都是浮点数
n = 1;
m = 2;
result=m/n;
print (result,type(result))
运行结果: 3. 浮点数计算会有误差,因为浮点数的尾数位数是有限的
二、字符串格式str
str的定义
str_test1 = "hhhh1"
str_test2 = 'hhhh2'
print("str_test1 is", type(str_test1),"\nstr_test1 is", type(str_test2))
运行结果:
str常用函数
str_test = " Mail LEe "
print("str.title=",str_test.title(),"END")
print("str.upper=",str_test.upper(),"END")
print("str.lower=",str_test.lower(),"END")
print("str.rstrip=",str_test.rstrip(),"END")
print("str.lstrip=",str_test.lstrip(),"END")
print("str.strip=",str_test.strip(),"END")
运行结果:
s1 = "120"
s2 = "3.1415926"
f = float(s2)
i = int(s1)
print("i+f", i+f)
print("s1+s2", s1+s2)
math模块
import math
print(math.floor(69.3))
print(math.ceil(69.3))
print(math.sqrt(9))
from math import sqrt
print(sqrt(16))
输入
格式化输出
sText = "%d个猫单价是%.2f元,%d只猫的价格是:%.1f元"%(1,100.53,2,201.06)
print(sText)
运行结果:
列表
"""
正序: 0 1 2 3 4
对应倒序: -5 -4 -3 -2 -1
"""
listTest = ["one","two", "three","four"]
print("original listTest is:",listTest)
listTest.append("five")
print("\nafter append(\"five\")",listTest)
listTest.insert(1,"TWO")
print("\nafter insert(1,TWO)",listTest)
del listTest[2]
print("\nafter del two",listTest)
listTest.pop()
print("\nafter pop()",listTest)
运行结果:
listTest = ["one", "two", "three", "four"]
listTest.sort(reverse = True)
print(listTest)
listTest_sorted = sorted(listTest)
print(listTest)
print(listTest_sorted)
listTest.reverse()
print("after reverse",listTest)
运行结果:
range(5) 相当于[0,1,2,3,4],但它是range()格式的,可以用list()可以将它转为列表
range(1,10,3)相当于[1,4,7],range(x,y,z)表示从x开始增加z,最后的结果必须小于y,不能等于y,
z可以是负数,但必须是整数
listTest = [1, 2, 4 , 8]
sum(listTest)
MaxElement = max(listTest)
cubes = [x**3 + 100 for x in range(1,5) ]
matrix = [[0,1]*3]*2
matrixFast = [[r+c for c in range(5)] for r in range(4)]
matrixFast1 = [x+y for x in "abc" for y in "123"]
language = ["c","c++","pascal"]
print(language + ["python", "Ruby"])
print([1,2] + [3,4])
print("la" in "language", "la" not in "language")
运行结果: ``
listTest = [4, 5, 5, 4, 5]
listCopy = listTest.copy()
listAssign = listTest
print(id(listTest), id(listAssign),id(listCopy) )
del listAssign[0]
print(listTest)
运行结果
列表切片
numbers = [x for x in range(10)]
print("numbers[3:9]", numbers[3:8])
print("numbers[3:]", numbers[3:])
print("numbers[3:9:2]", numbers[3:9:2])
numbers[3:5] = 12,13,14
print(numbers)
运行结果
常见符号
pass 占位语句,相当于C语言中的 ;空语句
control+[ 缩进快捷键
// 整除(向下取整)
+=、-=、/=、*= 同C语言
% 求模
>= 、!=、and 、or、not
** 幂 同pow()函数
pow(a,b) a的b次幂
abs()绝对值
round()四舍五入
以0x开头 十六进制,hex()十六进制函数,%x 十六进制的占位符
0b二进制,bin()二进制函数
|