Python基础(1)
print("hello")hello#常见的值和类型
count=10 #int:整数
voltage=3.3 #float:浮点数
name="sensor" #str: 字符串
enabled=True #bool:布尔值,主要首字母大写
result=None #表示当前没有值可以使用type()查看对象的类型:
print(type(count)) #<class 'int'>
print(type(name)) #<class 'str'><class 'int'>
<class 'str'>Python允许同一个便变量名先后绑定不同类型的值: 在实际开发中,保持同一个变量的含义和类型稳定,通常更容易读懂代码
value=10
value="hello"练习给定设备运行时间 total_seconds=3671 要求: 1.计算它包含多少个完整的分钟,以及剩余多少秒 2.输出分钟数和剩余秒数 3.如果允许时间达到3600秒,输出“已运行至少一个小时”:否则输出“运行不足一小时”
total_seconds=3671
minute=3671//60
minute_remiander=3671%60
hour=minute/60
print("分钟:",minute)
print("剩余秒数:",minute_remiander)
if hour>1:
print("已允许至少一个小时")
else:
print("运行不足一小时")
分钟: 61
剩余秒数: 11
已允许至少一个小时在C中,常用用char[]或char*处理字符串;Python使用str,无需自己管理缓冲去和结尾的\0.
device="SENSOR-001"
print(device[0]) #S:第一个字符
print(device[1]) #E:第二个字符
print(device[-1]) #1:最后一个字符
print(len(device)) #10:字符串长度
S
E
1
10索引从0开始,负数索引从末尾开始,Python没有独立的char类型,device[0]得到的仍然是一个字符串,只是长度为1.
print(device[0:6]) #SENSOR
print(device[:6]) #SENSOR:省略起点,默认从头开始
print(device[7:]) #001:省略终点,默认到末尾
print(device[-3:]) #001:取最后三个字符SENSOR
SENSOR
001
001字符串[起点:终点] 包含起点,不包含终点。所以[0:6]取得是索引0~5,共6个字符 另外,Python的字符串不能通过下标直接修改,例如device[0]='s'会报错。 printf用法的工具:f-string
temperature=28.56
print(f"当前温度:{temperature}C")
print(f"当前温度:{temperature:.1f}C")当前温度:28.56C
当前温度:28.6C字符串前面的f允许在{}中放变量或表达式;:.1f表示保留一位小数,类似C的%.1f
问题: device_id="DEV-007" voltage=3.276 使用切片和f-string,输出: 设备类型:DEV 设备编号:007 设备 DEV-007的电压为3.28V 最后一行需要保留两位小数
device_id="DEV-007"
voltage=3.276
print("设备类型:",device_id[0:3])
print("设备编号:",device_id[-3:])
print(f"设备{device_id[0:3]}的电压为{device_id[-3:]}V")设备类型: DEV
设备编号: 007
设备DEV的电压为007Vraw="DEV-007,28.56,on"
clean=raw.strip()
fields=clean.split(",")
print(clean)
print(fields)DEV-007,28.56,on
['DEV-007', '28.56', 'on']filed是一个列表,可以用下标取出其中的元素
device_id=fields[0]
temperature=float(fields[1])
status=fields[2].upper()
print(f"设备:{device_id}")
print(f"温度:{temperature:.1f}C")
print(f"状态:{status}")
设备:DEV-007
温度:28.6C
状态:ON这里拆分出来的每一项都是字符串 flaot()负责把数字字符串转换成浮点数,int()则可以把“123”这样的整数字符串转换成整数。类似C中的数值转换函数,Python转换失败时会抛出异常,
new_id=device_id.replace("DEV-","SENSOR-")
print(device_id)
print(new_id)DEV-007
SENSOR-007字符串方法返回处理后的结果,原字符串不会被直接修改,所以需要接收返回值 问题:raw="DEV-015,3.276,off" 要求去掉首尾空格,拆分字段,把电压转换成浮点数,把状态转成大写,最终输出 设备:DEV-015 电压:3.28V 状态:OFF
raw="DEV-015,3.276,off"
#去掉首尾空格,再按逗号拆分
fields=raw.strip().split(",")
#提前字段并转换
device_id=fields[0]
voltage=float(fields[1])
status=fields[2].upper()
#格式化输出
print(f"设备:{device_id}")
print(f"电压:{voltage:.2f}V")
print(f"状态:{status}")
设备:DEV-015
电压:3.28V
状态:OFF