Python 基本数据类型基础实战【常量、变量、数字、分数、高精度、字符串、字节串、函数】

实战源码参考自《Python 程序设计基础(第2版)》(董付国,清华大学出版社)

PS:Irish_Moonshine 正在测试一种自学方法,该方法目前用于Python基础学习和Python数据分析学习。测试结果将于测试完毕后与大家分享!!!

import math 与 from math import sin 与 from math import *的区别
import math引入了所有的库,并且所有的方法都必须使用math.()
from math import *同样引入了所有的库,但所有的方法不需要是用math.()
from math import sin引入了math中的sin模块,方法不需要使用math

如同double一样,应该避免两个实数直接等价的表示方法,而应该采用绝对值的方法。

Fraction分数对象

from math import *
import random
from fractions import Fraction #分数
from fractions import Decimal #高精度实数(高精度浮点数)

x = type('Hello World!') #输出字符串类型
y = type(b'Hello World') #b表示字节串
z = 'Hello world'.encode('utf-8') #使用utf-8编码格式进行编码
w = 'Hello world'.encode('gbk') #使用gbk编码格式进行编码
o = '爱尔兰月光'.encode('utf-8') #对中文进行编码
q = '爱尔兰月光'.encode('gbk') #对bytes字节串进行编码

#m = _.decode('gbk') #该指令无法使用

print(x)
print(y)
print(z)
print(w)
print(o)
print(q)
#print(m) #同上无法使用,所以无法打印

x = 'Hello Wolrd!'
y = "Python is a great language."
z = '''Irish_Moonshine's programming.'''
print(x)
print(y)
print(z)
z = x + y
print(z)#类似于C++ String
x = 'good''morning'#可以实现连接
print(x)
x = 'good'+'morning'
print(x) #与上一语句等价

tem = Decimal(1/9)
print(tem);
tem = Decimal(1/3)
print(tem);
tem = Decimal(1/9)+Decimal(1/3)
print(tem);


x=Fraction(3,5)
y=Fraction(3,7)
z=Fraction(3.5)#小数转换成实数
print(x);
print(y);
print(z);
print(x.numerator);#查看分子
print(x.denominator);#查看分母
print(Fraction(x+y))#四则运算自动通分






a = sin(0.5)
r = random.random()
rr = random.randint(1,100)
rrr = random.randrange(1,100000);
print(r)
print(rr)
print(rrr)
print(a)
print(pi)
print(e)
print(radians(180)) #角度转弧度


def main():
        if __name__=='__main__':
            print("This program is run directly.")
        elif __name__=='hello':
            print('This program is used as a module.')
        #fi



main()

猜你喜欢

转载自blog.csdn.net/Irish_Moonshine/article/details/91831872
今日推荐