FUNCTION笔记 - Floria289/CS-5001 Wiki



Function Definition:

It is a recipe for what to do (the algorithm), it does not work until we cook (invoke) it.


def divide(x,y):
    'Function: divide, takes 2 numbers x, y, returns the result of x/y '
    result = x / y
    return result

上面是一个自定义的divide函数 显示了用几个变量,做出什么运算。此函数完成后就储存在上面,直到被调用。 definition这一part写好全部的操作,之后call出这个function基本只做变量替换


  • return is optional

  • function should do one thing and be short (<12 lines)

  • NOT print() or input() unless designed to do user input/output -- this allows further use in other documents

  • function name should be meaningful

  • variables: to memorize values; the name should be ALL CAPITALIZED when it is a constant value

  • parameters in the function will generate a local variable and can't be shared

Exercise -- lecture and lab

max 3 numbers

create a menu

get middle number


(Input, process, output, expected value)


def test_divide(x, y, expected_value):

    answer = x/y #此处有之前写过的可以用from import调用

    print(f"Input: {x} {y}")
    print(f"Expect: {expected_value} Actual: {answer}")


It is simple graphic programming.

using turtle

import turtle.  # 调取turtle函数
t = turtle.Turtle()   # window pump-out
t.forward(100)   #向前100单位
t.right(90)   #右转90度
t.forward(50)   #向前50单位
t.position()   #显示位置坐标