python学习第七天

习题21 函数可以返回某些东西

def add(a, b):                                    #构造四则运算函数,
    print(f"ADDING {a} + {b}")
    return a + b

def subtract(a, b):
    print(f"SUBTRACTING {a} - {b}")
    return a - b

def mutiply(a, b):
    print(f"MUTIPLYING {a} * {b}")
    return a * b

def divide(a, b):
    print(f"DIVIDING {a} / {b}")
    return a / b

print("let's do some math with just functions!")

age = add(30, 5)                                 #调用四则运算函数
height = subtract(78, 4)
weight = mutiply(90, 2)
iq = divide(100, 2)

print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")

print("here is a puzzle")

what = add(age, subtract(height, mutiply(weight, divide(iq, 2))))  #调用函数由内而外的调用

print("that becomes:", what, "can you do it by hand?")

此习题是对函数构造和调用的进一步提高和掌握,以及return 返回值的意义

习题23 字符串字节串和字符编码

import sys
script, encoding, error = sys.argv


def main(language_file, encoding, errors):
    line = language_file.readline()

    if line:                                                 #if部分通过调用主函数来进行循环,当line为空时跳出循环
        print_line(line, encoding, errors)                   #调用print——line函数
        return main(language_file, encoding, errors)         #递归调用

def print_line(line, encoding, errors):
    next_lang = line.strip()   #删掉尾行的空格
    raw_bytes = next_lang.encode(encoding, errors = errors)#DBES  解码字节串,编码字符串
    cooked_string = raw_bytes.decode(encoding, errors = errors)

    print(raw_bytes, "<===>", cooked_string)

languages = open("languages.txt", encoding = "utf-8") #强制编码转换

main(languages, encoding, error)

解码字节串,编码字符串,编码的学习,要注意utf-8是标准码

习题24 更多的练习

此习题是对前面所学知识内容的一个练习,要注意进行各种破坏代码的尝试,以及这里面*的用法

print("let's practice everything")
print('you\'d need to know \'bout escapes with \\ that do:')
print('\n newline and \t tabs')

poem = """
\tthe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none
"""

print("-" * 10)
print(poem)
print("-" * 10)

five = 10 - 2 + 3 - 6
print(f"this shuold be five: {five}")

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

start_point = 10000
beans, jars, crates = secret_formula(start_point)

print("with a starting point of: {}".format(start_point))

print(f"we'd have {beans} beans, {jars} jars, and {crates} crates")

start_point /= 10

print("we can also do that this:")
formula = secret_formula(start_point)

print("we'd have {} beans, {} jars, {} crates.". format(*formula))#*接受任意多个参数并将其放在一个元组中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值