Day2

    科技2025-10-17  24

    Python基本数据类型和运算符

    数据类型和其他语言相同,有整型、浮点型、布尔型以及字符串型。

    基本运算符: 类型转换: int()、float()及str()。

    Python中时间的表示

    计算机中时间的表示是从“1970 年 1 月 1 日 00:00:00”开始,以毫秒(1/1000 秒) 进行计算。我们也把 1970 年这个时刻成为“unix 时间点”。

    python 中可以通过 time.time() 获得当前时刻,返回的值是以秒为单位,带微秒 (1/1000 毫秒)精度的浮点值。例如:1530167364.8566。

    小练习:求两点间的距离

    import turtle import random import math #随机生成X,Y坐标 num = range(0,100) x = random.sample(num,10) y = random.sample(num,10) turtle.penup() turtle.goto(x[0],y[0]) turtle.pendown() for i in range(1,10): turtle.goto(x[i],y[i]) #计算起始点到终点的距离 distance = math.sqrt((x[9]-x[0])**2 + (y[9] - y[9])**2) turtle.write(distance) turtle.done()

    运行过程:

    同一运算符

    is/is not :比较的是两个对象的id,即数据地址。

    基本运算符

    实际测试:

    字符串

    一、不换行打印

    mystr = "I'm Yuehai" print(mystr) print(mystr,end="") print(mystr,end="!")

    二、从控制台读取字符串

    MyName = input("Please input your name:") print("Your Name is "+MyName+"!")

    三、使用[ ]提取字符串以及replace替换字符串 四、字符串切片 slice 操作 五、split()分割和 join()合并

    split()可以基于指定分隔符将字符串分隔成多个子字符串(存储到列表中)。如果不指定分隔 符,则默认使用空白字符(换行符/空格/制表符)。

    join()的作用和 split()作用刚好相反,用于将一系列子字符串连接起来。

    六、format()基本用法

    MyName = "My name is {0},{1} years old." print(MyName.format("Yuehai",18)) MyName = "My name is {name},{old} years old." print(MyName.format(name="Yuehai",old=20))

    Processed: 0.013, SQL: 8