
1def
def代表了定义一个函数(function),以冒号结尾。
def thing():
print('Hello')
print('Fun')
thing()
Hello
Fun

max min
max和min也是python内置的函数,比如我们需要找出一个字幕中的最大或者最小值,通过max和min函数就会得到一个返回的值。
>>>big = max('Hello world')
>>>print(big)
w
>>>tiny = min('Hello world')
>>>print(tiny)
最小值中,输出的是空格,并非没有输出。
整数和浮点数转换
>>> i = 42
>>> type(i)
<class 'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> h = int(f)
>>> print(h)
42
字符串转换
>>> sva1 = '123'
>>> type(sva1)
<class 'str'>
>>> print(sva1 + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> iva1 = int(sva1)
>>> type(iva1)
<class 'int'>
>>> print(iva1 + 1)
124
创建函数
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
x = x + 2
print(x)
Hello
Yo
7
虽然建立了函数并储存,但是函数没有被唤起,所以必须要唤起建立的函数
x = 5
print('Hello')
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
print_lyrics()
x = x + 2
print(x)
Hello
Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
定义参数
选择一个参数比如这里的l,l就像一个变量
>>> def a(l):
... if l == 'es':
... print('Hola')
... elif l == 'fr':
... print('Bob')
... else:
... print('hello')
>>> a('es')
Hola
>>>a('fr')
Bob
>>>a('ff')
hello
残值(return value)
return做两件事,停止函数,跳到下一行;决定残值(结果)
>>> def a(x):
... if x == 'es':
... return 'Hola'
... elif x == 'fr':
... return 'Bonjour'
... else:
... return 'Hello'
>>> print(a('en'),'Glenn')
Hello Glenn
>>> print(a('es'),'Sally')
Hola Sally
>>> print(a('fr'),'Michael')
Bonjour Michael
网友评论