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)
 
上一篇:(day04)剑指 Offer 10- II. 青蛙跳台阶问题


下一篇:JAVA基础day04循环+数组入门