Skip to content

Sep 16: Variable Scope, Docstrings, Objects and Types

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.
  • Explain the difference between a variable and an object.
  • Name and describe three examples of a container type.

Announcements

  • Due tomorrow
  • Practice Quiz 2 on Thursday
    • Based on HW 3 and HW 4
    • Two functions and __main__
  • Upcoming events
    • Tuesday 9/16 at 5:30 in King 159: First-Year Kickoff
    • Friday 9/19 at 11:30 in King 259: What is Research?

Quick facts

formatting and lists   [5 min]

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
# 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)


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   [40 min]

📝 Note: This lab includes topics from later weeks, such as lists and random numbers. We will walk through the lab as a class rather than work individually. If you are absent, please go to TA hours to get help with this lab.

Highlights:

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

Reading Week 5 Preview

Slides   [20 min]

  • Variables and objects are two different concepts
Example Variable (Name) Object (Value)
x = 5 x the integer 5
y = 1.2 y the float 1.2
z = 'A' z the string 'A'
p = True p the boolean True
q = None q the None object
import math math the math module
def hi() hi the hi function
  • Every object has a value, a type, and an identity
    • type() and id() functions
    • is keyword compares object id's
  • A container is an object that contains (references) other objects
    • list: [1, 2, 3] in brackets
    • tuple: (1, 2, 3) in parentheses
    • set: {1, 2, 3} in braces
    • dict: {"one": 1, "two": 2, "three": 3} braces + colons
  • Every variable references exactly one object