python判断小数示例&写入文件内容示例

时间:2025-03-22 16:04:07
#需求分析:
#1、判断小数点个数是否为1
#2、按照小数点分隔,取到小数点左边和右边的值
#3、判断正小数,小数点左边为整数,小数点右边为整数
#4、判断负小数,小数点左边以负号开头,并且只有一个负号,负号后面为整数,小数点右边为整数 def is_float(s):
print(s)
s=str(s)
if s.count('.')==1:
left,right = s.split('.')
if left.isdigit() and right.isdigit():
print('正小数')
return True
elif left.startswith('-') and left.count('-')==1 and \
left[1:].isdigit() and right.isdigit():
print('负小数')
return True
print('不合法')
return False is_float('-s.1') #不合法
is_float('--9s8.9s2') #不合法
is_float(--00.6) #负负得正,所以判断结果是正小数
#定义一个函数:如果传了内容参数,就写入文件中
def op_file(filename,content=None):
with open(filename,'a+',encoding='utf-8') as fw:
fw.seek(0)
if content:
fw.write(content)
else:
return fw.read() res=op_file('hh.txt','test')
print(res)