python 函数

1. 函数
  函数是对功能的封装
  语法:
  def 函数名(形参列表):
  函数体(代码块, return)
  调用:
  函数名(实参列表)

  

def yue():
    print("打开手机")
    print("打开陌陌")
    # 可以终止一个函数执行
    return "大妈", "阿姨", "嫂子","姑娘"
    print("搜索一下你心仪的对象")
    print("走吧. 出去玩啊")
    print("出发!")
ret = yue()
print(ret)
yue()
def sum():
    a = int(input("请输入一个a:"))
    b = int(input("请输入一个b:"))
    c = a + b
    return c
ret = sum()
print(ret)


2. 返回值
  return : 在函数执行的时候. 如果遇到return. 直接返回
  1.如果函数什么都不写, 不写return, 没有返回值. 得到的是None
  2.在函数中间或者末尾写return, 返回的是None
  3.在函数中写return 值. 返回一个值.
  4.在函数中可以返回多个返回值, return 值1, 值2, 值3...., 接收的是元组


3. 参数
  函数执行的时候给函数传递信息.
  *形参:函数声明的位置的变量
  实参:函数调用的时候给的具体的值
  传参:把实参交给形参的过程

1. 实参:
  1. 位置参数, 按照形参的参数位置, 给形参传值
  2. 关键字参数, 按照形参的名字给形参传值
  3. 混合参数. 即用位置参数, 也用关键参数
2. 形参:
  1. 位置参数
  2. 默认值参数 先位置后默认值

作业:

1,整理函数相关知识点,写博客。

 

2,写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

 

3,写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

 

4,写函数,检查传入列表的长度,如果大于2,将列表的前两项内容返回给调用者。

 

5,写函数,计算传入函数的字符串中, 数字、字母、空格 以及 其他内容的个数,并返回结果。

 

6,写函数,接收两个数字参数,返回比较大的那个数字。

 

7,写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

    dic = {"k1": "v1v1", "k2": [11,22,33,44]}

    PS:字典中的value只能是字符串或列表

 

8,写函数,此函数只接收一个参数且此参数必须是列表数据类型,此函数完成的功能是返回给调用者一个字典,此字典的键值对为此列表的索引及对应的元素。例如传入的列表为:[11,22,33] 返回的字典为 {0:11,1:22,2:33}。

 

9,写函数,函数接收四个参数分别是:姓名,性别,年龄,学历。用户通过输入这四个内容,然后将这四个内容传入到函数中,此函数接收到这四个内容,将内容追加到一个student_msg文件中。

 

10,对第9题升级:支持用户持续输入,Q或者q退出,性别默认为男,如果遇到女学生,则把性别输入女。

 

11,写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作。

 

12,写一个函数完成三次登陆功能,再写一个函数完成注册功能

 

# 2
def ind(lst):
    li = []
    for i in range(len(lst)):
        if i % 2 == 0:
            pass
        else:
            li.append(lst[i])
    return li
a = ind([1,2,3,4,5,6,7,8,9,10])
print(a)

# 3
def compare5(content):
    if len(content) > 5:
        a = print("长度大于5")
    else:
        a =print("长度不大于5")
    return a
compare5([1,2,3])

# 4
def compare2(content):
    if len(content) > 2:
        return content[0:2]
    else:
        return print("列表长度小于2")
b = compare2([1,2,3,4,5])
print(b)

# 5
def count(content):
    a = 0
    b = 0
    c = 0
    d = 0
    for i in content:
        if i.isdigit():
            a += 1
        elif i.isupper() or i.islower():
            b += 1
        elif i == " ":
            c += 1
        else:
            d += 1
    ret = print("输入的字符串中有%s个数字,%s个字母,%s个空格,%s个其他内容" % (a,b,c,d))
    return ret
count("123asdASD!@#$   ")

# 6
def compare(a,b):
    if a > b:
        return a
    elif a < b:
        return b
result = compare(123,159)
print(result)

# 7
def diclen(dic):
    li = []
    for i in dic.values():
        if len(i) > 2:
            li.append(i[0:2])
    return li
a = diclen({"k1": "v1v1", "k2": [11,22,33,44]})
print(a)

# 8
def convert(li):
    num = 0
    dic = {}
    for i in li:
        dic[num] = i
        num += 1
    return dic
a = convert([11,22,33])
print(a)

# 9
def enter(name,sex,age,education):
    with open("student_msg",mode="w",encoding="utf-8") as f:
        f.write("姓名:%s 性别:%s 年龄:%s 学历:%s" % (name,sex,age,education))
        return
enter(name="裴杰",sex="",age="6",education="小学")

# 10
def enter(name,age,education,sex=""):
    with open("student_msg",mode="a",encoding="utf-8") as f:
        f.write("姓名:%s 年龄:%s 学历:%s 性别:%s
" % (name,age,education,sex))
        return

while 1:
    content = input("是否进行录入学生信息(输入Q/q退出录入)")
    if content.upper() == "Q":
        break
    my_name = input("请输入姓名:")
    my_age = input("请输入年龄:")
    my_education = input("请输入学历:")
    my_sex = input("请输入性别:")
    if my_sex != "":
        enter(name=my_name,age=my_age,education=my_education,sex=my_sex)
    else:
        enter(my_name,my_age,my_education)

# 11
import os
def document(name,content,content_1):
    with open(name,mode="r",encoding="utf-8") as f,
        open("副本.txt",mode="w",encoding="utf-8") as f1:
        for i in f:
            s = i.replace(content,content_1)
            f1.write(s)
    os.remove(name)
    os.rename("副本.txt",name)
doc_name = input("请输入要修改的文件名:")
doc_content = input("请输入要修改的内容:")
doc_content_1 = input("请输入修改后的内容:")
document(doc_name,doc_content,doc_content_1)

# 12
dic = {"name": None, "password": None}
def register():
    my_name = input("请输入账号:").replace(" ","")
    my_password = input("请输入密码:").replace(" ","")
    dic["name"] = my_name
    dic["password"] = my_password
    return print("注册成功!
账号:%s
密码:%s" % (my_name,my_password))
def entry():
    cishu = 3
    while cishu > 0:
        name = input("请输入账号:")
        password = input("请输入密码:")
        if name == dic["name"] and password == dic["password"]:
            return print("登陆成功!")
        else:
            cishu -= 1
            print("你的账号或密码出现错误!(剩余次数%s" % (cishu))

register()
entry()
#12(延伸版)
from random import randint
li = []
def register():
    dic = {}
    while 1:
        my_name = input("请输入账号:").replace(" ","")
        my_password = input("请输入密码:").replace(" ","")
        my_password_1 = input("请确认密码:").replace(" ","")
        if my_password == my_password_1:
            dic['name'] = my_name
            dic['password'] = my_password
            li.append(dic)
            print("注册成功!
您的账号为:%s
您的密码为:%s
" % (dic['name'],dic['password']))
            break
        else:
            print("两次密码输入不一致,请重新注册!")
            continue

def enter():
    cishu = 3
    while cishu > 0:
        T = True
        name = input("请输入账号:")
        password = input("请输入密码:")
        for i in li:
            if name == i['name'] and password == i['password']:
                print('登陆成功')
                cishu -= 3
                break
        else:
            cishu -= 1
            print("密码或账号输入错误!请重新尝试(剩余次数%s)" % (cishu))
            if cishu == 0:
                break
            while T:
                a = randint(1000, 9999)
                yanzheng = input("请输入验证码(%s):" % (a))
                if int(yanzheng) == a:
                    T = False
                    break
                else:
                    continue
register()
enter()



 
# 12(存入文件)
from random import randint
def register():
    with open("student.txt",mode="a",encoding="utf-8") as f:
        dic = {}
        while 1:
            my_name = input("请输入账号:").replace(" ","")
            my_password = input("请输入密码:").replace(" ","")
            my_password_1 = input("请确认密码:").replace(" ","")
            if my_password == my_password_1:
                dic['name'] = my_name
                dic['password'] = my_password
                f.write(my_name+"_"+my_password+"
")
                print("注册成功!
您的账号为:%s
您的密码为:%s
" % (dic['name'],dic['password']))
                break
            else:
                print("两次密码输入不一致,请重新注册!")
                continue

def enter():
    cishu = 3
    while cishu > 0:
        with open("student.txt", mode="r", encoding="utf-8") as f:
            T = True
            name = input("请输入账号:")
            password = input("请输入密码:")
            for i in f:
                a,b = i.strip().split("_")
                if name == a and password == b:
                    print('登陆成功')
                    cishu -= 3
                    break
            else:
                cishu -= 1
                print("密码或账号输入错误!请重新尝试(剩余次数%s)" % (cishu))
                if cishu == 0:
                    break
                while T:
                    a = randint(1000, 9999)
                    yanzheng = input("请输入验证码(%s):" % (a))
                    if int(yanzheng) == a:
                        T = False
                        break
                    else:
                        continue
register()
enter()
 
原文地址:https://www.cnblogs.com/zbw582922417/p/9445125.html