Python tutorial: function to determine negative decimals

One, function

def hello(file_name,content):  #形参file_name content
    f=open(file_name,'a+')
    f.seek(0)
    f.write(content)
    f.close()<br><br>#调用函数<br><br>hello('123.txt','hahhahha')

Second, the type of participation

#默认值参数:不是必填的
def hello2(file_name,content=''):
    f=open(file_name,'a+')
    if content:
        f.seek(0)
        f.write(content)
    else:
        f.seek(0)
        res=f.read()
        return res
    f.close() 
 
hello2('123.txt')   #content 默认为空
hello2('123.txt',content='12345') 
 
#可变参数
#不常用
def test3(a,b=1,*args): #可变参数 *args
    print('a',a)
    print('b',b)
    print('args',args)
 
test3(2,3,'ahahha','hahhaha3','hahhaha4') 
 
#关键字参数
def test4(**kwargs):
    print(kwargs)
test4(name='suki',sex='man')   #传参是dic形式

Three, return

#函数返回值return
#需要获取结果必须return,可以没有返回值
#return:立即结束函数

Four, global variables and local variables

The variables inside the function are all local variables

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
a=100 #全局变量
def test():
    a=5
    print('里面的',a)
test()
print('外面的',a)
 
 
a=100 #全局变量
def test2():
    global a   #声明全局变量 才能修改a的值
    a=5
    print('里面的',a)
test()
print('外面的',a)

Five, write a function to check whether a string is a negative decimal

#写一个校验字符串是否为合法小数的函数
#1.判断小数点个数
#2.按照小数点分割
#3.有负小数的时候,按照负号分割
def check_float(s):
    s=str(s)
    if s.count('.')==1:
        s_list=s.split('.')
        left=s_list[0]
        right=s_list[1]
        if left.isdigit()  and right.isdigit():  #正小数
            return True
        elif left.startswith('-') and left.count('-')==1:  #负小数
            if left.split('-')[-1].isdigit()  and right.isdigit():
                return  True
        return False

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/109028415