【Python】编程小白的第一本python(最基本的魔法函数)

Python官网中各个函数介绍的链接:https://docs.python.org/3/library/functions.html

几个常见的词:

  • def (即 define,定义)的含义是创建函数,也就是定义一个函数。
  • arg (即 argument,参数)有时还能看到:parameter这种写法
  • return 即返回结果

咒语: Define a function named 'function' which has two arguments : arg1 and atg2, returns the result——'Something'

注意:

  1) def 和 return 是关键词 (keyword) 

  2) 闭合括号后面的冒号必不可少,而且是英文

  3) 在IDE中冒号后回车,会自动得到一个缩进。函数缩进后面的语句被称作是语句块 (block),缩进是为了表明语句和逻辑的从属关系,是Python的显著特征之一。

    4) 一定要有return,如果我们把函数最后一句return去掉改成直接输出(以下用温度转换举例),会发现多出现了一个None。这是因为print函数是人为设计的函数,95.0°F实际上是调用函数后产生的数值,而None是变量C2F中被返回的数值。这就好比

def fahrenheit_converter(C):
    fahrenheit = C * 9/5 + 32
  # return fahrenheit print(str(fahrenheit) + '°F')

C2F = fahrenheit_converter(35)
print(C2F)

# 运行结果
# 95.0°F
# None

    不写return也可以顺利地定义一个函数并使用,只不过返回值是'None'罢了。

习题一:设计一个重量转换器,输入以"g"为单位地数字后返回换算成"kg"的结果。

def kilogram_converter(G):
    kilogram = G / 1000
    return kilogram

G2K =  kilogram_converter(500000)
print(G2K)

习题二:设计一个求直角三角形斜边长的函数(直角边为函数,求最长边)

import math

def calculate_bevel_edge(a, b):
    c = math.sqrt(a*a + b*b)
    return c

edge =  calculate_bevel_edge(3, 4)
print(edge)

(我发现我的代码出现淡淡的黄线,但不懂原因,PEP8)

| 传递参数与参数类型

传递参数的两种方式:位置参数、关键词参数

以上面求斜边为例,介绍输入方式的正确错误:

edge =  calculate_bevel_edge(3, 4)  // 第一种
edge =  calculate_bevel_edge(a=3, b=4)  // 第二种
edge = calculate_bevel_edge(a=3, 4)    // 第三种

edge =  calculate_bevel_edge(b=4, 3)  // 错误

设计一个建议的敏感词过滤器:

一、掌握 open 和 write 的基本用法

1、在桌面创建test.txt 文件

2、使用open打开。因为我的IDE在E盘,而我的test文件在桌面,所以我写了一个C盘表示位置。

file = open('C:/Users/asus/Desktop/test.txt','w')
file.write('Hello world')

二、设计函数

传入参数 name 与 msg 就可以控制在桌面写入的文件名称和内容的函数 test,这就是不需要return 也可以发挥作用的函数

def test_create(name, msg):
    desktop_path = 'C:/Users/asus/Desktop/'
    full_path = desktop_path + name + '.txt'
    file = open(full_path,'w')
    file.write(msg)
    file.close()
    print('Done')

test_create('hello','hello world')

三、敏感词过滤函数

def text_filter(word, cencored_word = 'lame', changed_word = 'Awesome'):
    return word.replace(cencored_word, changed_word)

text_filter('Python is lame!')

四、将以上两个函数合并

def text_filter(word, cencored_word = 'lame', changed_word = 'Awesome'):
    return word.replace(cencored_word, changed_word)

def test_create(name, msg):
    desktop_path = 'C:/Users/asus/Desktop/'
    full_path = desktop_path + name + '.txt'
    file = open(full_path,'w')
    file.write(text_filter(msg))
    file.close()
    print('Done')

test_create('hello','Python is lame!')

最后,Python解决数学问题可以用到的一些符号

猜你喜欢

转载自www.cnblogs.com/daijux/p/11901574.html