创建函数
def 函数名(参数):
语句1
语句2
例 判断回文
#!/usr/bin/env python3
def palindrome(s): #定义函数
return s == s[::-1] #函数内容,缩进,返回是或否
if __name__ == '__main__':
s = input("Enter a string: ")
if palindrome(s):
print("Yay a palindrome")
else:
print("Oh no, not a palindrome")
局部变量全局变量
global a 在函数中声明全局变量a
当函数内部更改了a的值,整个代码的a都改变了
例
#!/usr/bin/env python3
def change():
global a #声明全局变量a
a = 90
print(a)
a = 9
print("Before the function call ", a)
print("inside change function", end=' ')#输出后不换行,加空格
change()
print("After the function call ", a)
默认参数
参数赋值规则和c++类似
可以给未赋值参数默认值
当有多个参数时,有默认值的参数,后面的参数也要有默认值
默认值只被赋值一次,如果多次调用函数,参数的值会往后顺延覆盖掉默认值,这一点可以用参数的相应关键字来对应
比如
>>> def func(a, b=5, c=10):
... print('a is', a, 'and b is', b, 'and c is', c)
...
>>> func(12, 24)
a is 12 and b is 24 and c is 10
>>> func(12, c = 24)#明确c的值是24,而不是顺延b
a is 12 and b is 5 and c is 24
>>> func(b=12, c = 24, a = -1)
a is -1 and b is 12 and c is 24
高阶函数
map()
接受一个函数一个序列作为输入
将序列的每个值调用函数
输出一个序列(调用函数后产生的)
例
>>> lst = [1, 2, 3, 4, 5]
>>> def square(num):
... "返回所给数字的平方."
... return num * num
...
>>> print(list(map(square, lst)))
[1, 4, 9, 16, 25]
其他高阶函数
sorted()、filter()、functools()
文件操作
例 读取文件内容并提取出字符串中的数字并打印
''' 从/tmp/String.txt中读取字符串,read()读取字符串,
for循环遍历i中是否有数字,如果有加入到res中'''
with open ('/tmp/String.txt') as f:
s = f.read()
res = ""
for i in s :
if i.isdigit():
res += i
print(res)