资讯专栏INFORMATION COLUMN

Python基础-函数

goji / 2665人阅读

摘要:函数也称方法,是用于实现特定功能的一段代码函数用于提高代码的复用性函数必须要调用才会执行函数里面定义的变量,为局部变量,局部变量只在函数里面可以使用,出了函数外面之后就不能使用一个函数只做一件事情形参入参传入一个文件名返回文件内容转成字典并

函数也称方法,是用于实现特定功能的一段代码
函数用于提高代码的复用性
函数必须要调用才会执行
函数里面定义的变量,为局部变量,局部变量只在函数里面可以使用,出了函数外面之后就不能使用
一个函数只做一件事情

import json
def get_file_content(file_name): #形参
    #入参:传入一个文件名
    #返回:文件内容转成字典并返回
    with open(file_name, encoding="utf-8") as f:
        res = json.load(f)
        return res
abc = get_file_content("stus.json") #函数调用才执行,此处传入实参,函数有返回,需要用变量接收
print(abc)
def write_file(filename,content):
    with open(filename,"w", encoding="utf-8") as f:
        #f.write(json.dumps(content))
        json.dump(content,f,ensure_ascii=False,indent=4)
dict = {"name":"wrp","age":"18"}
write_file("wrp.json",dict)
"""
作业:
    1、实现一个商品管理的程序。
        #输出1,添加商品 2、删除商品 3、查看商品
        添加商品:
            商品的名称:xxx  商品如果已经存在的话,提示商品商品已经存在
            商品的价格:xxxx 数量只能为大于0的整数
            商品的数量:xxx,数量只能为大于0的整数
        2、删除商品:
            输入商品名称:
                iphone 如果输入的商品名称不存在,要提示不存在
        3、查看商品信息:
             输入商品名称:
                iphone:
                    价格:xxx
                    数量是:xxx
                all:
                    print出所有的商品信息 
"""


FILENAME = "products.json"

import json
def get_file_content():
    with open(FILENAME, encoding="utf-8") as f:
        content = f.read()
        if len(content) > 0:
            res = json.loads(content)
        else:
            res = {}
    return res

def write_file_content(dict):
    with open(FILENAME,"w",encoding="utf-8") as fw:
        json.dump(dict, fw, indent=4, ensure_ascii=False)

def check_digit(st:str):
    if st.isdigit():
        st = int(st)
        if st > 0:
            return st
        else:
            return 0
    else:
        return 0
def add_product():
    product_name = input("请输入商品名称:").strip()
    count = input("请输入商品数量:").strip()
    price = input("请输入商品价格:").strip()
    all_products = get_file_content()
    if check_digit(count) == 0:
        print("数量输入不合法")
    elif check_digit(price) == 0:
        print("价格输入不合法")
    elif product_name in all_products:
        print("商品已经存在")
    else:
        all_products[product_name] = {"count":int(count),"price":int(price)}
        write_file_content(all_products)
        print("添加成功")

def del_product():
    product_name = input("请输入要删除的商品名称:").strip()
    all_products = get_file_content()
    if product_name in all_products:
        all_products.pop(product_name)
        print("删除成功")
        write_file_content(all_products)
    else:
        print("商品不存在")

def show_product():
    product_name = input("请输入要查询的商品名称:").strip()
    all_products = get_file_content()
    if product_name == "all":
        print(all_products)
    elif product_name not in all_products:
        print("商品不存在")
    else:
        print(all_products.get(product_name))
拷贝

浅拷贝,内存地址不变,把两个对象指向同一份内容,
深拷贝,会重新在内存中生成相同内容的变量

l = [1,1,1,2,3,4,5]
l2 = l #浅拷贝
#l2 = l.copy() #浅拷贝 
for i in l2:
    if i % 2 != 0:
        l.remove(i)
print(l)
#在此程序中,如果对同一个list进行遍历并删除,会发现结果和预期不一致,结果为[1,2,4],使用深拷贝就没问题
import copy
l = [1,1,1,2,3,4,5]
l2 = copy.deepcopy(l) # 深拷贝
for i in l2:
    if i % 2 != 0:
        l.remove(i)
print(l)

非空即真,非零即真

name = input("请输入名称:").strip()
name = int(name) #输入0时为假
if name:
    print("输入正确")
else:
    print("name不能为空")
默认参数
import json
def op_file_tojson(filename, dict=None):
    if dict: #如果dict传参,将json写入文件
        with open(filename,"w",encoding="utf-8") as fw:
            json.dump(dict,fw)
    else: #如果没传参,将json从文件读出
        f = open(filename, encoding="utf-8")
        content = f.read()
        if content:
            res = json.loads(content)
        else:
            res ={}
        f.close()
        return res

校验小数类型

def check_float(s):
    s = str(s)
    if s.count(".") == 1:
        s_split = s.split(".")
        left, right = s_split
        if left.isdigit() and right.isdigit():
            return True
        elif left.startswith("-") and left[1:].isdigit and right.isdigit():
            return True
        else:
            return False
    else:
        return  False

print(check_float("1.1"))
全局变量
def te():
    global a
    a = 5
    
def te1():
    c = a + 5
    return c

res = te1()
print(res) #代码会报错,te()中定义的a在函数没被调用前不能使用
money = 500
def t(consume):
    return money - consume
def t1(money):
    return  t(money) + money

money = t1(money)
print(money) #结果为500
name = "wangcai"
def get_name():
    global name
    name = "hailong"
    print("1,函数里面的name", name)
def get_name2():
    print("2,get_name2", name)

get_name2() #wangcai
get_name() #hailong
print("3,函数外面的name", name) #hailong
递归

递归的意思是函数自己调用自己
递归最多递归999次

def te1():
    num = int(input("please enter a number:"))
    if num%2==0: #判断输入的数字是不是偶数
        return True #如果是偶数的话,程序就退出,返回True
    print("不是偶数,请重新输入")
    return  te1()#如果不是的话继续调用自己,输入值
print(te1()) #调用test1
参数

位置参数

def db_connect(ip, user, password, db, port):
    print(ip)
    print(user)
    print(password)
    print(db)
    print(port)

db_connect(user="abc", port=3306, db=1, ip="192.168.1.1", password="abcde")
db_connect("192.168.1.1","root", db=2, password="123456", port=123)
#db_connect(password="123456", user="abc", 2, "192.168.1.1", 3306) #方式不对,位置参数的必须写在前面,且一一对应,key=value方式必须写在后面

可变参数

def my(name, sex="女"):
    #name,必填参数,位置参数
    #sex,默认参数
    #可变参数
    #关键字参数
    pass
def send_sms(*args):
    #可变参数,参数组
    #1.不是必传的
    #2.把传入的多个元素放到了元组中
    #3.不限制参数个数
    #4.用在参数比较多的情况下
    for p in args:
        print(p)


send_sms()
send_sms(123456)
send_sms("123456","45678")

关键字参数

def send_sms2(**kwargs):
    #1.不是必传
    #2.不限制参数个数
    #3.key=value格式存储
    print(kwargs)

send_sms2()
send_sms2(name="xioahei",sex="nan")
send_sms2(addr="北京",county="中国",c="abc",f="kkk")
集合

集合,天生可以去重
集合无序,list有序

l = [1,1,2,2,3,3,3]
res = set(l) #将list转为set
l = list(res) #set去重后转为list
print(res)
print(l)
set = {1,2,3} #set格式

jihe = set() #定义一个空的集合

xn=["tan","yang","liu","hei"]
zdh=["tan","yang","liu","jun","long"]

xn = set(xn)
zdh = set(zdh)
# res = xn.intersection(zdh) #取交集
# res = xn & zdh #取交集

res = xn.union(zdh) #取并集
res = xn | zdh #取并集
res = xn.difference(zdh) #取差集,在A中有,在B中无的
res = xn - zdh #取差集

res = xn.symmetric_difference(zdh) #对称差集,取两个中不重合的数据
res = xn ^ zdh
print(res)
import string
l1 = set(string.ascii_lowercase)
l2 = {"a","b","c"}
print(l2.issubset(l1)) #l2是不是l2的子集
print(l2.issuperset(l1)) #l2是不是l2的父集
print(l2.isdisjoint(l1)) #是否有交集,有则Flase,无则True

l2.add("s") #添加元素
print(l2)
print(l2.pop()) #随机删除一个元素
l2.remove("a") #删除指定元素
for l in l2:
    print(l)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43682.html

相关文章

  • Python爬虫学习路线

    摘要:以下这些项目,你拿来学习学习练练手。当你每个步骤都能做到很优秀的时候,你应该考虑如何组合这四个步骤,使你的爬虫达到效率最高,也就是所谓的爬虫策略问题,爬虫策略学习不是一朝一夕的事情,建议多看看一些比较优秀的爬虫的设计方案,比如说。 (一)如何学习Python 学习Python大致可以分为以下几个阶段: 1.刚上手的时候肯定是先过一遍Python最基本的知识,比如说:变量、数据结构、语法...

    liaoyg8023 评论0 收藏0
  • 从能做什么到如何去做,一文带你快速掌握Python编程基础与实战

    摘要:本文的分享主要围绕以下几个方面能做什么常见应用场景介绍如何学习语法基础实战面向对象编程实战练熟基础小游戏项目的实现与实战一能做什么一种编程语言往往可以应用于多方面,有些方面比较常用,有些方面极为常用。比如表示是一个空列表。 摘要:Python语言的教程虽然随处可见,但是忙于日常业务/学习的你或许:一直想要找个时间学一点,但是又不知道该从何下手?本文将从Python能做什么,如何学习Py...

    BLUE 评论0 收藏0
  • Python 基础概览

    摘要:通过函数名作为其的参数就能得到相应地帮助信息。类是面向对象编程的核心,它扮演相关数据及逻辑的容器的角色。之后是可选的文档字符串,静态成员定义,及方法定义。 Python 源文件通常用.py 扩展名。当源文件被解释器加载或显式地进行字节码编译的时候会被编译成字节码。由于调用解释器的方式不同,源文件会被编译成带有.pyc或.pyo扩展名的文件,你可以在第十二章模块学到更多的关于扩展名的知识...

    zhongmeizhi 评论0 收藏0
  • [零基础python]重回函数

    摘要:函数的基本结构中的函数基本结构函数名参数列表语句几点说明函数名的命名规则要符合中的命名要求。在中,将这种依赖关系,称之为多态。不要期待在原处修改的函数会返回结果比如一定要之用括号调用函数不要在导入和重载中使用扩展名或路径。 在本教程的开始部分,就已经引入了函数的概念:《永远强大的函数》,之所以那时候就提到函数,是因为我觉得函数之重要,远远超过一般。这里,重回函数,一是复习,二是要在已经...

    dmlllll 评论0 收藏0
  • 第7期 Datawhale 组队学习计划

    马上就要开始啦这次共组织15个组队学习 涵盖了AI领域从理论知识到动手实践的内容 按照下面给出的最完备学习路线分类 难度系数分为低、中、高三档 可以按照需要参加 - 学习路线 - showImg(https://segmentfault.com/img/remote/1460000019082128); showImg(https://segmentfault.com/img/remote/...

    dinfer 评论0 收藏0

发表评论

0条评论

goji

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<