Skip to content

Sep 18: Variable Scope, Docstrings

Learning Objectives

After today's class, you should be able to:

  • Explain the difference between global and local variables.
  • Write a docstring for a function (following Google's Style).
  • Use help() to explore modules and functions in a shell.

Reminders

Return Examples

returns.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Example 1: No return statement

def greeting():
    print("Have a nice day!\n")


# Example 2: One return statement

def time_str(hour, minute):
    if hour < 12:
        ampm = "AM"
    else:
        ampm = "PM"
        hour -= 12
    if hour == 0:
        hour = 12
    return f"{hour}:{minute:02d} {ampm}"


# Example 3: Multiple return statements

def analyze(number):
    if number == 0:
        return "Zero!"
    if number > 0:
        return "Positive"
    return "Negative"


# Example 4: Multiple return values

def stats(grades):
    avg = sum(grades) / len(grades)
    return min(grades), avg, max(grades)


if __name__ == "__main__":
    print("1:", greeting())
    print("2:", time_str(12, 5))
    print("3:", analyze(-1))
    print("4:", stats([95, 71, 100, 88]))

Bank of JMU Lab

Slides   Code

Highlights:

  • Thonny debugger's with functions
  • Functions that modify parameters
  • Writing docstrings for functions
  • Using the built-in help() function