Python基础-全局变量、函数、函数参数、练习day04-2

2021/5/13 20:26:54

本文主要是介绍Python基础-全局变量、函数、函数参数、练习day04-2,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

全局变量
# a = 100#全局变量  少用全局变量 会一直占内存
# def test():
#     global a
#     a=1
#     print(a)

# test()
# print(a)
"""
def test():
    global a
    a=5

def test1():
    c=a+5
    return c

test()
res = test1()
print(res)  #如果未调用test() 会报错 因为a未定义"""

def test():
    L = []
    for i in range(50):
        if i % 2 ==0:
            L.append(i)
    return L

print(test())


函数
# 函数、方法
# 提高的代码复用性,简化代码
def hello():
    print('hello')
def welcome(name,country = '中国'):
    return name,country

def test():
    return

print('没有写return:',hello())
print('return多个值的时候:',welcome('hym'))
print("return后面啥都不写:",test())

# def op_file(filename,content =None):
#     with open(filename,"a+",encoding="utf-8") as f:
#         f.seek(0)
#         if content:
#             f.write(content)
#         else:
#             result = f.read()
#             return result
#
# print(op_file("student.txt"))

# 函数里面定义的变量都是局部变量,只能在函数内部生效
# 函数里面只要遇到return函数立即结束

函数参数
def send_sms(*args):  #可选参数(参数组)不定长参数 接收到的是一个元组
    print(args)


# send_sms() #返回空元组  不传参数时
# send_sms("130449484306") #传一个参数时
# send_sms(1304984306,13049484307) #传多个参数时

def send_sms2(**kwargs):  #关键字参数 接收到的是一个字典
    print(kwargs)

send_sms2(a=1,b=2,name="abc")
send_sms2()

# 必填参数(位置参数)
# 默认值参数
# 可选参数,参数组
# 关键字参数
 

函数练习
# def is_float(s):
#     s = str(s)
#     if s.count('.')==1:
#         left,right = s.split('.')
#         if left.isdigit() and right.isdigit():
#             return True
#         elif left.startswith('-') and left.count('-')==1 \
#                 and left[1:].isdigit() and right.isdigit():
#             return True
#         else:
#             return False
#     else:
#         return False
#
#
# price = input("请输入价格:").strip()  #去空
# result = is_float(price)
# if result:
#     print("价格合法")
# else:
#     print("价格不合法")

money = 500
def test(consume):
    return money - consume

def test1(money):
    return test(money) + money

money = test1(money)
print(money)
 


这篇关于Python基础-全局变量、函数、函数参数、练习day04-2的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程