2.4. Lecture 3: Python 1

Before this class you should:

  • Read Think Python:

    • Preface;

    • Chapter 1: The way of the program;

    • Chapter 2: Variables, expressions and statements; and

    • Chapter 3: Functions

Before next class you should:

  • Read Think Python:

    • Chapter 5: Conditionals and recursion;

    • Chapter 6: Fruitful functions; and

    • Chapter 7: Iteration

Note taker: Harman Singh

Today’s class introduced Jupyter Notebook and the Python programming language, covering the following:

  • Accessing Jupyter Hub and setting up your environment.

  • Understanding the Jupyter Notebook interface and cell types.

  • Basic Python syntax, data types, and operators.

  • Working with strings and using comments.

  • Defining and calling functions, including math functions.

2.4.1. Accessing Jupyter Hub

To access the Jupyter Hub for this course, you have two options:

  1. Connect to the University VPN: This is required to access the Hub remotely.

  2. Local Installation: Download and install Python and Jupyter Notebook on your own machine.

The Jupyter Hub can be accessed at: https://engg3130.soe.uoguelph.ca/

2.4.2. Jupyter Notebook Cells

Jupyter Notebook provides two main types of cells:

  • Markdown Cells: These cells allow you to write and format text using Markdown. Use Ctrl + Enter to render the Markdown into HTML.

  • Code Cells: These cells are for writing and executing Python code.
    • Shift + Enter: Runs the current cell and moves to the next cell.

    • Ctrl + Enter: Runs the current cell and stays in the same cell.

    • Enter: Creates a new line within the current code block.

    • The output of any code you run is displayed below the code block.

2.4.3. Python Basics

This section introduced the core elements of Python:

  • Operators: Python supports common mathematical operators:

    • + (addition): 2 + 3 results in 5

    • - (subtraction): 5 - 2 results in 3

    • * (multiplication): 2 * 3 results in 6

    • / (division): 6 / 2 results in 3.0

    • ** (exponentiation): 2 ** 3 results in 8

    Important Note: Division (/) in Python always results in a float (e.g., 84 / 2 results in 42.0).

  • Data Types: Python has several fundamental data types:
    • String: Used to represent text (e.g., “hello”, “This is a string”).

    • Integer: Represents whole numbers (e.g., 10, -5, 1000).

    • Float: Represents numbers with decimal points (e.g., 3.14, -2.5).

  • Variables: Variables are used to store data. Here are the rules for naming variables:
    • Variable names cannot start with a number (e.g., 1variable is invalid).

    • Variable names cannot be Python keywords (e.g., class, def, if).

  • Expressions and Statements:
    • Expressions: These are combinations of values, variables, and operators that produce a result (e.g., 6 * 7, x + 5).

    • Statements: These are complete units of code that perform an action (e.g., assigning a value to a variable: x = 10).

  • Script vs. Interactive Mode:
    • Interactive Mode: (Like in Jupyter Notebook) Expressions are evaluated and their results are printed immediately.

    • Script Mode: When you run a Python script (a .py file), expressions are evaluated, but their results are not printed unless you explicitly use the print() function.

2.4.4. Strings

We looked at how to work with text in Python:

  • String Operations: Strings can be manipulated in various ways:
    • Concatenation: Joining strings together using the + operator (e.g., "hello" + " world" results in "hello world").

    • Slicing: Extracting portions of a string (e.g., "hello"[1:4] results in "ell"`, `"hello"[-4:-1] results in "ell").

    • Indexing: Accessing individual characters within a string.

2.4.5. Comments

Comments are essential for explaining your code:

  • Using Comments: Use the # symbol to create a comment. Anything after # on a line is ignored by Python.

    # This is a comment to explain the code below
    x = 10  # This comment explains what the variable x is for
    

2.4.6. Functions

We learned about functions, which are reusable blocks of code:

  • Function Calls: To use a function, you “call” it by its name followed by parentheses. Values you pass to the function inside the parentheses are called “arguments”.

    print("Hello, world!")  # "print" is the function, "Hello, world!" is the argument
    
  • Math Functions: The math module provides access to many mathematical functions. To use it, you first need to import it:

    import math
    
    result = math.log10(300)  # Calculates the log base 10 of 300
    pi_value = math.pi  # A constant representing the value of pi
    
  • Composition: You can combine function calls (nesting):

    x = math.exp(math.log(x + 1))  # The inner function (math.log) is calculated first
    
  • Defining Functions: You can create your own functions using the def keyword:

    def greet(name):
        """This function greets the person passed in as a parameter."""
        print("Hello, " + name + "!")
    
  • Parameters: Parameters are variables that you define within the parentheses of a function definition. They allow you to pass values into your function.

    def add_numbers(x, y):  # x and y are parameters
        """This function adds two numbers together."""
        result = x + y
        return result
    
  • Multiple Arguments: You can pass multiple arguments to a function by separating them with commas. The order in which you pass the arguments matters.

    def multiply_numbers(a, b, c):  # a, b, and c are parameters
        """This function multiplies three numbers together."""
        result = a * b * c
        return result
    
    # Example usage:
    result = multiply_numbers(2, 3, 4)  # result will be 24
    
  • Scope: Variables defined inside a function are only accessible within that function (local scope). Variables defined outside any function are accessible throughout the entire script (global scope).

    • Local Scope: Variables defined inside a function.

      def my_function():
          local_var = "I am local"
          print(local_var)  # This will print "I am local"
      
      my_function()
      # print(local_var)  # This will raise a NameError because local_var is not accessible outside the function
      
    • Global Scope: Variables defined outside any function.

      global_var = "I am global"
      
      def my_function():
          print(global_var)  # This will print "I am global"
      
      my_function()
      print(global_var)  # This will also print "I am global"
      
  • Fruitful Functions: Functions that return a value are called “fruitful functions”. Functions that don’t return a value (they might just print something) are called “void functions” and implicitly return None.