Skip to content

Lesson 3

Funcion

We have known the syntax of a function definition is:

def function_name(parameter_list...):
    STATEMENTS

Parameters and Argument

Most functions require arguments, values that could control how the function works. We have been used to call the print function with arguments:

>>> print("Hello, world") # We call print() function ,and pass an argument "Hello, world"
"Hello, world"
>>> print(1, 2, 3) # We call print() function, and pass three arguments: 1, 2, 3
1 2 3

Here are some examples from built-in function in Python:

>>>  abs(-5)   # abs function is for computing the absolute value of one argument

>> max(2, 5, 1, 6) # max function is for finding the maximum number among arguments.
6

Now we can define function which accepts one argument:

def print_twice(something):
    print(something, something)

Inside the function, the values that are passed get assigned to variables called parameters . So in our user-defined function print_lines above, we have one parameter called something, and the function print it twice on the screen.

The return statement

We can use a return statement to terminate the execution of a function. Also, it could return values after you reach the end of the function.

def add(x, y):
    return x + y

def half(x):
    return x/2

Control Flow Statements

if statement

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

if x > 0:
    print("X is positive")

The boolean expression after the if statement is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.

The syntax for an if statement looks like this:

    if BOOLEAN EXPRESSION:
        STATEMENTS

A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

if x % 2 == 0:
    print (x, "is even")
    else:
        print (x, "is odd")

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution.

As an aside, if you need to check the parity (evenness or oddness) of numbers often, you might wrap this code in a function:

def print_parity(x):
    if x % 2 == 0:
        print (x, "is even")
    else:
        print (x, "is odd")

For any value of x, print_parity displays an appropriate message. When you call it, you can provide any integer expression as an argument.

>>> print_parity(17)
17 is odd.
>>> y = 41
>>> print_parity(y+1)
42 is even.

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

if x < y:
    print (x, "is less than", y)
elif x > y:
    print (x, "is greater than", y)
else:
    print (x, "and", y, "are equal")

elif is an abbreviation of else if . Again, exactly one branch will be executed. There is no limit of the number of elif statements but only a single (and optional) else statement is allowed and it must be the last branch in the statement:

if choice == 'a':
    function_a()
elif choice == 'b':
    function_b()
elif choice == 'c':
    function_c()
else:
    print("Invalid choice.")

Exercises

  1. Enter the following expressions into the Python shell:

    在Python Shell中输入以下表达式:

    True or False
    True and False
    not(False) and True
    True or 7
    False or 7
    True and 0
    False or 8
    "happy" and "sad"
    "happy" or "sad"
    "" and "sad"
    "happy" and ""
    

    Analyze these results. What observations can you make about values of different types and logical operators? Can you write these observations in the form of simple rules about and and or expressions?

    分析表达式的结果。不同类型的数值进行逻辑运算,你发现了什么? 你能把你对 andor 运算的观察结果用简单的方式写下来吗?

  2. Wrap this code in a function called compare(x, y) . Call compare three times: one each where the first argument is less than, greater than, and equal to the second argument.

    将这段代码封装到函数 compare(x, y) 中。调用该函数三次: 第一个参数小于、大于和等于第三个参数的三种情况。

    if x < y:
        print(x, "is less than", y)
    elif x > y:
        print(x, "is greater than", y)
    else:
        print(x, "and", y, "are equal")
    
  3. Write a function named is_divisible_by_3 that takes a single integer as an argument and prints "This number is divisible by three." if the argument is evenly divisible by 3 and "This number is not divisible by three." otherwise.

    编写一个叫 is_divisible_by_3 的函数,这个函数接收一个整型参数, 然后如果这个数能被3整除,在屏幕上打出:“This number is divisible by three.”, 否则打印出"This number is not divisible by three."