# 一旦遇到第一个return,函数执行就会停止
def three():
print(1)
return 2
print(3)
return 22
three()
print(4)
----------------------
for i in range(10):
line = ""
for j in range(10):
if i == j:
break
line += "{} ".format(j)
print(line)
-----------------------
魔法函数
__init__ :初始化类的新实例 Initialize a new instance of the class
__new__ :创建该类的新实例 Create a new instance of the class
__repr__ :定义实例表示进行调试 Define an instance representation for debugging
__str__ :定义实例的用户友好表示 Define user-friendly representation of an instance
class Song:
def __init__(self, artist, name, year):
self.artist = artist
self.name = name
self.year = year
def __repr__(self):
rep = "Artist: {}. Name: {}. Year: {}".format(self.artist, self.name,
self.year)
return rep
def __str__(self):
return "{} — {} ({})".format(self.artist, self.name, self.year)
dsmn = Song("Queen", "Don't stop me now", 1979)
print(dsmn)
----------
# 如果不使用global关键字,则无法在函数内部更改全局变量的值
x = "global"
def outer():
x = "outer local"
def inner():
x = "inner local"
def func():
x = "func local"
print(x)
func()
inner()
# nonlocal 关键字可让我们将变量分配给外部(而非全局)范围
def func():
x = 1
def inner():
x = 2
print("inner:", x)
inner()
print("outer:", x)
def nonlocal_func():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
func() # inner: 2
# outer: 1
nonlocal_func() # inner: 2
# outer: 2
outer()
---------------------------------
def func(positional_args, args_with_default, *args, **kwargs):
pass
print(*"fun") # f u n
print(*[5, 10, 15]) # 5 10 15
def add(*args):
total = 0
for n in args:
total += n
return total
small_numbers = [1, 2, 3]
large_numbers = [9999999, 1111111]
print(add(*small_numbers)) # 6
print(add(*large_numbers)) # 11111110
def say_bye(**names):
for name in names:
print("Au revoir,", name)
for key, value in names.items():
print(f"{key}:{value}")
humans = {"Laura": {"age": 34, "fave_color": "purple"},
"Robin": {"age": 28, "fave_color": "turquoise"}}
say_bye(**humans)
# Au revoir, Laura
# Au revoir, Robin
# Laura:{'age': 34, 'fave_color': 'purple'}
# Robin:{'age': 28, 'fave_color': 'turquoise'}
def concat(*args):
return "".join(args)
print(concat("python")) # python
print(concat("cat", "dog")) # catdog
def create_function(n):
return lambda x: n * x
# Creating a function that doubles its argument
doubler = create_function(2)
# This function will triple its argument
tripler = create_function(3)
doubler(2)
# Outputs 4
tripler(2)
# Outputs 6
-------------------------------
def func(x):
if x % 2 == 0:
return 'even'
else:
return 'odd'
func = (lambda x: 'even' if x % 2 == 0 else 'odd')
---------------------------
评论
发表评论