Skip to content

Week 2 - Variables and Statements

Variables and Statements

Introduction

  • Previous chapter: Operators and arithmetic expressions
  • This chapter: Variables, statements, import statement, print function
  • New vocabulary: “argument” and “module”

Variables

Definition

  • A name that refers to a value or a storage location for a value.

Creating variables (Assignment statements)

  1. Syntax: variable_name = expression
  2. Examples:
    1
    2
    3
    n = 17
    pi = 3.141592653589793
    message = 'And now for something completely different'
    
  3. No visible output when running assignment statements in the Python interpreter or Jupyter Notebook (i.e. Google Colab).

Using variables

  1. As expressions
    1
    2
    message
    # Output: 'And now for something completely different'
    
  2. In arithmetic expressions
    1
    2
    3
    4
    n + 25
    # Output: 42
    2 * pi
    # Output: 6.283185307179586
    
  3. In function calls
    1
    2
    3
    4
    round(pi, 2)
    # Output: 3
    len(message)
    # Output: 42
    

State diagrams

  • Graphical representation of variables and their values
  • Used throughout the book to model Python’s variable storage, but you can generate better ones on Python Tutor
  • Python Tutor or your IDE Debugger can be used (and we will later) to give you a better understanding of how the internals of Python work (i.e. stack/frames, heap/objects)

Python Variable naming rules (Other languages have slightly different rules)

  1. Can be any length (Though choose to be reasonable!)
  2. Can contain letters and numbers
  3. Cannot start with a number
  4. Conventionally lowercase (PEP Standards)
  5. Underscore (_) is the only allowed punctuation
    • Used for multi-word names: your_name, airspeed_of_unladen_swallow
    • snake_case_it_is
  6. Cannot use keywords as variable names
    • They are reserved in the Python grammar to designate features supported by python like class, import, etc.

Illegal variable names (examples)

1
2
3
million! = 1000000                          # SyntaxError: invalid syntax
76trombones = 'big parade'                  # SyntaxError: invalid decimal literal
class = 'Self-Defence Against Fresh Fruit'  # SyntaxError: invalid syntax

Keywords in Python

  • There currently exist 36 keywords in Python 3.12
  • They will get highlighted in your PyCharm IDE
Keyword Description
and Logical AND operator.
as Used in import statements to alias modules or packages.
assert Used for debugging, raises an AssertionError if a condition is false.
async Indicates an asynchronous function or expression.
await Used within asynchronous functions to wait for a coroutine to complete.
break Terminates the innermost loop.
class Defines a new class.
continue Skips the current iteration of a loop and starts the next.
def Defines a function.
del Deletes an object or variable.
elif Used in if statements for alternative conditions.
else Used in if and try statements for a default block.
except Used in try statements to handle exceptions.
False Boolean value representing false.
finally Used in try statements to execute code regardless of exceptions.
for Used for creating loops that iterate over a sequence.
from Used in import statements to import specific objects from a module.
global Declares a variable as global.
if Used for conditional statements.
import Used to import modules or packages.
in Used to check membership in a sequence.
is Compares the identity of two objects.
lambda Used to create anonymous functions.
None Represents the absence of a value.
nonlocal Declares a variable as nonlocal within a nested function.
not Logical NOT operator.
or Logical OR operator.
pass Used as a placeholder for a statement.
raise Raises an exception.
return Returns a value from a function.
True Boolean value representing true.
try Used for exception handling.
while Used for creating loops that continue as long as a condition is true.
with Used for context management, often with file handling or resource management.
yield Used in generator functions to return values one at a time.

The import Statement

  • Purpose: Importing Python features
  • Syntax or Usage: import module_name

Modules

  • Collections of variables and functions
  • Example We’ve seen: math module

    1
    2
    import math
    print(math.pi)  # Output: 3.141592653589793
    

  • Accessing module contents, like functions stored in the module.

  • Use the dot operator (.)
  • Examples:
    1
    2
    math.sqrt(25)  # Output: 5.0
    math.pow(5, 2)  # Output: 25.0
    

Expressions and Statements

Types of expressions - These are Evaluated

Evaluating an expression means Computing its value

  1. Single values (integer, float, string)
  2. Collections of values and operators (i.e. x + y)
  3. Variable names
  4. Function calls

Complex expression example

1
19 + n + round(math.pi) * 2

Statements - These are Executed

  • Executing a statement: Running it and performing its action
  • Definition: Units of code with an effect but no value
  • Examples: Assignment statements, import statements import math or x = 5

The print Function

Purpose: Displaying multiple values

Basic usage

1
2
print(n+2)
print(n+3)

Working with different data types

1
2
print('The value of pi is approximately')
print(math.pi)

Multiple arguments

1
2
3
4
5
6
7
8
9
- (Yes, we will learn how to make our own functions that can take multiple arguments, both named and unnamed)
    ```python
    print('The value of pi is approximately', math.pi)
    ```
- Note: print function ALWAYS adds a space between values when passing multiple arguments to the function.
    - BUT you can change it:
        ```python
        print("Hello", "world!", sep="---")
        ```

Printing Formmatted Strings and Format Specifiers

  • Using variables in format string
    1
    print(f"{variable_name}")
    
  • Using variables and utilizing data-type specific formatting
    1
    2
    print(f"{math.pi:.2f}")  # 2 decimal spots
    print(f"{my_int:05d}")   # 5 spaces padded with 0
    
  • Using variables and aligning in formatting
    1
    2
    3
    print(f"Hi {math.pi:>10.2f}")  # 2 decimal spaces with 10 padded spaces aligned right
    print(f"Hi {math.pi:<10.2f}")  # 2 decimal spaces with 10 padded spaces aligned left
    print(f"Hi {math.pi:^10.2f}")  # 2 decimal spaces with 10 padded spaces aligned center
    

Arguments

  • Definition: Expressions in parentheses when calling a function

Functions with different numbers of arguments

  1. Single argument: int('101')
  2. Two arguments: math.pow(5, 2)
  3. Optional arguments: int('101', 2), round(math.pi, 3)
    • We will learn how to write functions and methods that take optional arguments, just not yet.
  4. Variable number of arguments: print('Any', 'number', 'of', 'arguments')
    • We will learn how to write functions and methods that take a variable number of arguments and allow for packing and unpacking them, but not yet.

Argument errors

  1. Too many arguments: TypeError
    • This implies the function does not allow variable arguments.
  2. Too few arguments: TypeError
    • This implies the function has required arguments (i.e. non-optional) and you are missing one or more.
  3. Incorrect argument type: TypeError
    • This implies there could be a datatype mismatch among other posibilities.
    • Type Hints/Annotation were introduced in Python 3.5 to abet in addressing common TypeError issues in Python, but they are used by IDEs because the Python Interpreter does not enforce them.
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      def add_numbers(a: int, b: int) -> int:
          """Add two numbers and return the result."""
          return a + b
      
      def concatenate_strings(strings: List[str]) -> str:
          """Concatenate a list of strings and return the result."""
          return "".join(strings)
      
      age: int = 76
      first_name: str = "Alice"
      last_name: str = "Cooper"
      concatenate_strings(first_name, last_name)
      add_numbers(age, 24)
      

Comments

  • Purpose: Adding notes to explain code
  • Syntax/Usage: # symbol

Types of comments

  1. Full-line comments
    1
    2
    # number of seconds in 42:42
    seconds = 42 * 60 + 42
    
  2. End-of-line comments
    • The standard says 2 spaces befor the comment # in end of line comments.
      1
      miles = 10 / 1.61  # 10 kilometers in miles
      

Best practices

  • Document non-obvious features
  • Explain WHY, not what
  • Avoid redundant comments
  • Use good variable names to reduce need for comments

Debugging

Types of errors

  1. Syntax errors
    • Related to program structure
    • Prevent program from running
    • Example: Illegal variable names
  2. Runtime errors (exceptions)
    • Occur during program execution
    • Example: Using unsupported operators
  3. Semantic errors AKA Logic errors
    • Program runs but doesn’t do what’s intended
    • Example: Incorrect order of operations

Additional Notes on Variables and Statements not Covered by the Book

  1. Type Hints/Annotations (introduced in Python 3.5) were already mentioned above in Argument Errors section.
  2. F-strings or Format Strings (introduced in Python 3.6) were already mentioned above in the Variable Printing section.
  3. Walrus operator := (introduced in Python 3.8)

    • Allows assignment within expressions
      1
      2
      if (n := len(data)) > 10:
          print(f"List is too long ({n} elements, expected <= 10)")
      
    1
    2
    3
    name = "Alice"
    age = 30
    print(f"{name} is {age} years old")
    
  4. Underscores in numeric literals (introduced in Python 3.6) just to make large numbers simpler to read.

    1
    million = 1_000_000