Python基础知识(day8)

day8

今日内容

  • 三元运算

  • 函数

内容详细

  1. 三元运算

    v = 前面 if 条件 else 后面
    
# 请让用户输入值,如果值是整数,则转换成整数,否则赋值为空
data = input('>>>')
value = int(data) if data.isdecimal() else None

注意:先实现功能,后考虑简化

  1. 函数

    对于函数编程

    • 本质: 将N行代码拿到别处并给他起个名字,以后通过名字就可以找到这段代码并执行
    • 场景:
      • 代码重复执行
      • 代码量大超过一屏,可以选择通过函数进行代码的分割
  • 函数的基本结构

    # 函数的定义
    def 函数名():
      # 函数内容
        pass
    
    # 函数执行
    函数名()
    
# 函数如果不被调用,则内部代码永远不会被执行
# 函数定义
def get_list_first_data():
    v = [11, 2, 3, 4, 5]
    print(v[0])

# 函数调用
get_list_first_data()
  • 函数的参数

    # 定义带参数函数
    def get_list_first_data(aaa): # 形参
        v = [11,22,33,445,5]
        print(v[aaa])
    # 带参函数调用   
    get_list_first_data(1)  # 实参
    get_list_first_data(2)
    # 实例1
    info = [1, 2, 3, 4, 5]
    sum = 0
    for i in range(0, 5):
        sum = sum + info[i]
        i = i + 1
    print (sum)
    # 实例2
    def get_num(a1):
        data = 0
        for item in a1:
            data = data + item
        print(data)
    get_num([1,2,33,4]
    # 实例3
     # 计算一个列表的长度
    def my_len(arg):
        count = 0
        for item in arg:
            count += 1
        print(count)
    v = [11,22,33,44]
    my_len(v)
  • 函数的返回值

    # 返回值
    def func():
        return  9 # 返回值为9 默认:renturn None
    """
    让用户输入一个字符串,判断字符串中有多少字符A,有多少个就在a.txt中打印多少次llk
    
    """
    # 定义函数获取字符串A个数
    def get_char_count(data):
        sum_count = 0
        for i in data:
            if i == 'A':
                sum_count += 1
        return sum_count
    
    # 定义函数写入文件
    def write_data(line):
        if len(line) == 0:
            return False
        with open('a.txt', mode= 'w', encoding= 'utf-8') as f:
            f.write(line)
            return True
    # 输入字符串并调用函数
    content = input("请输入字符串: ")
    # 调用get_char_count
    counter = get_char_count(content)
    write_data1 = 'llk' * counter
    status = write_data(write_data1)
    if status:
        print("写入成功!")
    else:
        print("写入失败!")
    

猜你喜欢

转载自www.cnblogs.com/lilangkui/p/12514308.html