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

Posted 小柠檬YM

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Python 基础 2022 最新第五课 函数

Python 基础 2022 最新第五课 函数

Python 基础 2022 最新第五课 函数

Go语言基础:map|函数

Go语言基础:map|函数

python函数基础