1.三元运算(三目运算)
v = x if condition1 else y # if...else...语句的简单写法
if condition1:
v = x
else:
v = y
# 让用户输入值,如果值是整数,则转换成整数,否则赋值为None
data = input('>>>')
value = int(data) if data.isdecimal() else None
2.函数
- 2.1 溯源
- 截至目前,写过的所有程序均为【面向过程编程】,代码可读性较差、可重用性也较差
- 函数式编程的本质:将N行代码抽取出来并给予一个“名称”,以后通过“名称”就可以找到这段代码并执行
- 函数式编程的适用场景:代码重复执行;代码量特别多,超过一屏,可以选择通过函数进行代码的分割
- 2.2 基本结构
# 函数的定义
def 函数名():
# 函数内容
pass
# 函数的执行
函数名()
def get_list_first_data():
v = [11, 22, 33, 44]
print(v[0])
get_list_first_data()
# 注意:函数如果不被调用,则内部代码永远不会被执行。
- 2.3 参数
def func(n1,n2):
print(n1, n2)
func(1,2)
func(1,[22,33,43])
func({'k1': 'k'}, [11,22,3])
# 严格按照顺序传递参数:位置方式传参。
# 实际参数可以是任意类型
def func(a1,a2,a3):
print(a1,a2,a3)
func(1,"hello",True)
def get_list_first_data(aaa): # aaa叫形式参数(形参)
v = [11, 22, 33, 44]
print(v[aaa])
get_list_first_data(1)
get_list_first_data(2)
# 练习题
# 1. 请写一个函数,用于计算列表 info = [11,22,33,44,55] 中所有元素的和。
def calc_info():
info = [11, 22, 33, 44, 55]
sum = 0
for i in info:
sum += i
print(sum)
calc_info()
# 2.请写一个函数,用于计算列表中所有元素的和。
def get_list_sum(a1):
data = 0
for item in a1:
data += item
print(data)
get_list_sum([11, 22, 33])
get_list_sum([99, 77, 66])
v1 = [1, 2, 3]
get_list_sum(v1)
# 3.请写一个函数,用于计算两个列表拼接并打印。
def join_list(a1, a2):
result = []
result.extend(a1)
result.extend(a2)
print(result)
join_list([1, 2, 3], [4, 5, 6])
# 4.计算一个列表的长度
def my_len(arg):
count = 0
for item in arg:
count += 1
print(count)
my_len(["hello", 1, True, None])
- 2.位置传参 调用函数时传入的参数【面向的是函数执行时】
def func(a1,a2):
print(a1,a2)
func(1,3)
- 3.关键字传参 调用函数时传入的参数【面向的是函数执行时】
def func(a1, a2):
print(a1,a2)
func(a2=99,a1=2)
# 关键字传参和位置传参可以混合使用,但要求位置传参在前,关键字传参在后,两者个数相加就是总参数个数
def func(a1, a2, a3):
print(a1, a2, a3)
func(1, 2, a3=9)
func(1, a2=2, a3=9)
func(a1=1, a2=2, a3=9)
def func(a1, a2, a3=9, a4=10):
print(a1, a2, a3, a4)
func(11, 22)
func(11,22,10)
func(11,22,10,100)
func(11,22,10,a4=100)
func(11,22,a3=10,a4=100)
func(11,a2=22,a3=10,a4=100)
func(a1=11,a2=22,a3=10,a4=100)
- 5.万能参数【参数打散】
- *args:可以接受任意个数的位置参数,并将参数转换成元组
def func(*args): # 适用于不确定接收参数个数的情况 写成args显得更专业一些
print(args)
func(1,2,3,4) # (1,2,3,4)
# 调用函数无*
func((11, 2, 54, 666)) # 整体放到元组中作为元组的第1个元素
def func(*args):
print(args)
func(*(1,2,3,4)) # 将元组内容打散后放到元组中
func(*[1,2,3,4]) # 将列表内容打散后放到元组中
func(1, 2, k1=3) # 不支持关键字传参 只支持位置传参
def func(*args):
print(args)
# func(1)
# func(1,2)
func(1,2) # args=(1, 2)
func((11,22,33,44,55)) # args=((11,22,33,44,55),)
func(*(11,22,33,44,55)) # args=(11,22,33,44,55)
- **kwargs:可以接受任意个数的关键字参数,并将参数转换成字典
def func(**kwargs): # 接收任意个关键字参数后将其转换为字典
print(kwargs)
func(k1=1, k2="alex") # {'k1': 1, 'k2': 'alex'}
func(k1={'k1': 'v1', 'k2': 'v2'}, k2="alex") # {'k1': {'k1': 'v1', 'k2': 'v2'}, 'k2': 'alex'}
func(**{'k1': 'v1', 'k2': 'v2'}) # {'k1': 'v1', 'k2': 'v2'}
- 综合应用:*args + **kwargs
def func(*args, **kwargs):
print(args, kwargs)
func(1, 2, 3, 4, 5, k1=2, k5=9, k19=999) # (1, 2, 3, 4, 5) {'k1': 2, 'k5': 9, 'k19': 999}
func(*[1, 2, 3],k1=2, k5=9, k19=999) # (1, 2, 3) {'k1': 2, 'k5': 9, 'k19': 999}
func(*[1,2,3],**{'name':'zhangsan', 'age':27}) # (1, 2, 3) {'name': 'zhangsan', 'age': 27}
func(111, 222, *[1, 2, 3], **{'k1': 'v1', 'k2': 'v2'}) # (111, 222, 1, 2, 3) {'k1': 'v1', 'k2': 'v2'}
- 2.4 返回值
- 函数没有返回值,默认返回None
- 函数内部执行过程中遇到return就终止执行
- return可以返回任意类型
def func(arg):
# ....
return 9 # 返回值为9 默认:return None
val = func('helloworld')
print(val)
# 特殊情况 返回元组
def func():
return (1,2,3)
v = func()
print(v)
def func():
return 5, 8, "hello"
v = func()
print(v) # (5, 8, 'hello')
# 练习题:让用户输入一段字符串,计算字符串中A字符的个数。有多少个就在文件a.txt中写多少个“张三”。
def get_char_count(a):
sum_counter = 0
for i in a:
if i == "A":
sum_counter += 1
return sum_counter
content = input("请输入字符串"):
counter = get_char_count(content)
def write_file(line):
if len(line) == 0:
return False # 函数执行得过程中一旦遇到return,则停止函数的执行
with open("./a.txt", mode="w", encoding="utf-8") as f:
f.write(line)
return True
write_data = "张三" * counter
statues = write_file(write_data)
if statues == True:
print("写入成功")
else:
print("写入失败")
# 1.写函数,计算一个列表中有多少个数字,打印: 列表中有%s个数字。
# 提示:type('x') == int 判断是否是数字。
def count_num(a):
count = 0
for item in a:
if type(item) == int:
count += 1
template = "列表中有%s个数字" %(count,)
print(template)
count_num(["hello", "1", True, False, 0, None, 666])
def count_num(a):
count = 0
for item in a:
if type(item) == int:
count += 1
return count
li = ["hello", "1", True, False, 0, None, 666]
count = count_num(li)
template = "列表中有{0}个数字".format(count,)
print(template)
# 2.写函数,将列表中偶数索引位置的数据构造成另外一个列表,并返回。
def new_list(a):
li = []
for i in range(0, len(a)):
if i%2 == 0:
li.append(a[i])
return li
new_li = new_list([1, 0, -7, 66, 91, -56])
print(new_li)
def get_data_list(arg):
v = arg[::2]
return v
result = get_data_list([1, 0, -7, 66, 91, -56])
print(result)
# 3. 读取文件,将文件的内容构造成指定格式的数据,并返回。
"""
a.log文件
zhangsan|123|18
eric|uiuf|19
...
b. [['zhangsan','123','18'],['eric','uiuf','19']]
c. [
{'name':'zhangsan','pwd':'123','age':'18'},
{'name':'zhangsan','pwd':'uiuf','age':'19'},
]
"""
# 结构1: ["zhangsan|123|18","eric|uiuf|19"] 并返回。
def read_file(file_name):
with open(file_name, mode="r", encoding="utf-8") as f:
data = f.read()
return data
def get_list(data):
return data.split("\n")[:-1]
content = read_file("./file/a.log")
v1 = get_list(content)
print(v1)
# 结构2:[['zhangsan','123','18'],['eric','uiuf','19']]
def read_file(file_name):
with open(file_name, mode="r", encoding="utf-8") as f:
data = f.read()
return data
def get_list(data):
result = []
new_data = data.split("\n")[:-1]
for i in new_data:
data_list = []
name, pwd, age = i.split("|")
data_list.append(name)
data_list.append(pwd)
data_list.append(age)
result.append(data_list)
return result
content = read_file("./file/a.log")
v1 = get_list(content)
print(v1)
# 结构3: [ {'name':'alex','pwd':'123','age':'18'}, {'name':'eric','pwd':'uiuf','age':'19'},]
def read_file(file_name):
with open(file_name, mode="r", encoding="utf-8") as f:
data = f.read()
return data
def get_list(data):
result = []
new_data = data.split("\n")[:-1]
for i in new_data:
data_dict = {}
name, pwd, age = i.split("|")
data_dict["name"] = name
data_dict["pwd"] = pwd
data_dict["age"] = age
result.append(data_dict)
return result
content = read_file("./file/a.log")
v1 = get_list(content)
print(v1)
3.作用域
- 3.1 分类
a = 1
def s1():
x1 = 666
print(x1)
print(a)
print(b)
b = 2
print(a)
s1()
a = 8888
def s2():
print(a, b)
s1()
s2()
1
666
1
2
8888 2
666
8888
2
- 3.2 特征
- 1.一个函数就是一个作用域,java等代码中以代码段作为作用域
def func():
x = 9
print(x)
func()
print(x)
- 2.作用域中查找数据的规则:优先在本作用域找数据,找不到的话去“父级”作用域,直到找到全局。全局没有就报错。
x = 10
def func():
x = 9
print(x)
func()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# x = 10
# def func():
# x = 9
# print(x)
# def x1():
# x = 999
# print(x)
#
# func()
# x = 10
# def func():
# x = 9
# print(x)
# def x1():
# x = 999
# print(x)
# x1()
#
# func()
# x = 10
# def func():
# x = 9
# print(x)
# def x1():
# x = 999
# print(x)
# print(x)
# x1()
#
# func()
# x = 10
# def func():
# x = 8
# print(x)
# def x1():
# x = 999
# print(x)
# x1()
# print(x)
#
# func()
# x = 10
# def func():
# x = 8
# print(x)
# def x1():
# print(x)
# x1()
# print(x)
#
# func()
# x = 10
# def func():
# x = 8
# print(x)
# def x1():
# print(x)
# x = 9
# x1()
# x = 10
# print(x)
#
# func()
#
# x = 10
# def func():
# x = 8
# print(x)
# def x1():
# print(x)
#
# x1()
# x = 9
# x1()
# x = 10
# print(x)
#
# func()
- 注意:父级作用域中的值到底是什么?
- 3.在子作用域中只能找到父级中的值,默认无法重新为父级的变量进行赋值,但可以通过关键字global、nonlocal强行修改
# #####################
name = 'oldboy'
def func():
name = 'alex' # 在自己作用域再创建一个这样的值。
print(name)
func()
print(name)
# #####################
name = [1,2,43]
def func():
name.append(999)
print(name)
func()
print(name)
# ###################### 如果非要对全局的变量进行赋值
# 示例一
name = ["老男孩",'alex']
def func():
global name
name = '我'
func()
print(name)
# 示例一
name = "老男孩"
def func():
name = 'alex'
def inner():
global name
name = 999
inner()
print(name)
func()
print(name)
name = "老男孩"
def func():
name = 'alex'
def inner():
global name
name = 999
inner()
print(name)
func()
print(name)
# ############################## nonlocal
name = "老男孩"
def func():
name = 'alex'
def inner():
nonlocal name # 找到上一级的name
name = 999
inner()
print(name)
func()
print(name)
- 4.一般情况下不会修改全局变量,容易导致代码可读性差,而且容易出错
- 5.全局变量在定义时必须全部是大写
USER_LIST = [11,22,3]
def func():
name = 'asdf'
USER_LIST.append(12)
USER_LIST.append(name)
func()
print(USER_LIST)
4.总结
- 4.1 函数定义与传参
# 情况1 无参数无返回值
def f1():
pass
f1()
# 情况2 有参数无返回值
def f2(a1):
pass
f2(123)
# 情况3 无参数有返回值
def f3():
return 1
v1 = f3()
# 情况4 有参数有返回值
def f4(a1, a2):
# ....
return 999
v2 = f4(1, 7)
# 情况5 指定默认参数
def f5(a1, a2=None):
pass
# 情况6 指定万能参数
def f6(*args, **kwargs):
pass
- 4.2 参数
- 调用(执行)函数时,传参顺序为:位置参数 关键字参数
- 定义函数
- def func(a)
- def func(a, b=None) # 对于默认值,如果是不可变类型随便写;如果是可变类型有一个坑
- def func(*args, **kwargs)
- 4.3 作用域
- 函数为作用域
- 先找自己的,然后找父级的,一级一级往上,直到全局【读/修改,修改只针对可变的数据类型】
- 重新赋值