8.1.4、Python__选择循环结构,if,while等循环,文件的读写open使用,函数使用,参数类型,位置参数,默认参数,可变参数,关键字参数,命名关键字参数

1、选择结构

if结构:四个空格(python对空格要求很高)

age = int(input("请输入一个年龄:"))	#输入框
if age>18:
    print("成年!")
elif age>0:
    print("未成年!")
else:
    print("输入有误")

2、循环结构

(1)for循环结构:一般遍历

#列表,元组,集合一样
list1 = [1,2,3,4,5,6,7]
for i in list1:
    print(i)
#遍历字典,只能得到k,得不到v
dict1 = {
    
    "k1":"v1","k2":"v2","k3":"v3"}
for key in dict1:
    print(key,dict1[key])
#使用方法进行遍历字典 item
for i,j in dict1.items():
    print(i,j)

(2)while循环结构

#1-100的和
count = 1;
sum = 0;
while count<=100:
    sum+=count
    count+=1
print(sum)

3、文件的读写open

(1)读取文件

f1 = open("data/open_file")
#读取几个字符
print(f1.read(10))
#读取一行数据
print(f1.readline())
#读取所有的行,并构成list
print(f1.readlines())
#用完关闭
f1.close()

(2)写入文件,mode=w就可以了

f2 = open("data/write_file",mode='w')	#a追....很多参数
f2.write("你好呀!!!\n")
f2.write('123\n')
f2.writelines(["2","6"])
f2.close()
引入with,不需要关闭
with open("data/open_file") as f1:
    with open("data/write_file",mode='w') as f2:
        f2.writelines(f1.readlines())

4、函数–代码的抽象

#定义一个函数
def area_cicle(r):  #将参数传入
    print(3.14 * r * r)

area_cicle(2)   #调用函数

(1)位置参数,默认参数

def power(x, n=2):
    # x:位置参数 n:默认参数
    return x ** n

(2)可变参数

--在参数前加*
def sum_as(*a): #可变形参,在参数前加一个*
    sum = 0
    for i in a:
        sum += i
    print(sum)
    
list2 = [1,2,3]
sum_as(list2[0],list2[1],list2[2])  #调用麻烦
#等价于
sum_as(*list2)

(3)关键字参数
—在参数前加2个 (eg:kw)
相对于可变参数来说,区别就是可以获取传入的参数名称
在调用时会将参数的名称作为key,参数的值作为value,构建k-v字典

def register(name, age, address, phone, **kw):
    dict1 = {
    
    
        "name": name,
        "age": age,
        "address": address,
        "phone": phone,
        "other": kw
    }
    print(dict1)


register("张三", 18, "蜀山区", "188")
register("张三", 18, "蜀山区", "188", year="10")
register("张三", 18, "蜀山区", "188", year="10",month="10")

(4)命名关键字参数
—检查传入的参数是否有year,month(eg: …)
#限定 传入的参数 必须有year,month…
#必须以year=… month=…传入参数
#如果是可变参数args 那么可以省略
*

def register(name, age, address, phone, *, year, month):
    dict1 = {
    
    
        "name": name,
        "age": age,
        "address": address,
        "phone": phone,
        "year": year,
        "month": month
    }
    print(dict1)
#register("张三", 18, "蜀山区", "188")
register("张三", 18, "蜀山区", "188", year="10", month="10")

(5)匿名函数

---lambda表达式
def func(x):
    return x * x

list3 = [1, 2, 3, 4]
#对list中每个元素*3
print(list(map(func,list3)))
#匿名函数,使用lambda表示:参数->执行逻辑
print(list(map(lambda x:x*x,list3)))

f1 = lambda x:x*x
print(list(map(f1,list3)))

猜你喜欢

转载自blog.csdn.net/nerer/article/details/121193000
今日推荐