Other Data Types Primer

Jed Rembold & Fred Agbo

January 24, 2025

Announcements

  • Problem Set 1 is due on Monday!
  • I’ll introduce Pensieve AI Tutor in the class today
    • I’ll try to deploy Problem Set 2 using Pensieve. So complete the _practice exercises to get you set up for next week’s assignment
  • Don’t forget you can contact your section leaders to ask questions if you need help!
  • QUAD Center is a great place to seek for help too! Check their schedule here
  • If you have just added the course and not in section yet, see me immediately
  • Polling today! Use this link
    • Be consistent, use firstname

Review Question

What is the printed value of A in the code below?

>>> A = 10
>>> B = 5 % 3
>>> C = A * B ** B
>>> A -= B + A // 2
>>> A, B, C = C, A, B
>>> print(A)
??
  1. 3
  2. 12
  3. 30
  4. 40

Other Data Types

  • Numbers are great, but what about other types of data?
  • We will spend considerable time on the details of these data types later
  • For now, let us introduce:
    • strings!
    • lists!

A quick String primer

  • A string in Python represents textual data, in form of a sequence of individual characters
    • Domain: all possible sequences of characters
    • Operations: Many! But we’ll keep in quite simple initially
  • Denoted by placing the desired sequence of characters between two quotation marks
    • 'I am a string'
    • In Python, either single or double quotes can be used, but the ends must match
      • "I am also a string!"
      • "I'm sad you've gone"

Lists

  • A list in Python represents a sequence of any type of data
  • Denote by bordering with square brackets ([, ]) with commas separating each element of the sequence
    • Each element could be any data type (even mixing from element to element!)
    • ['This', 'is', 'a', 'list']
    • ['Great', 4, 'storing', 5 * 10]
  • There are many operations that we will see are possible on lists, but will start with only the basics

Sequences

  • Both strings and lists are examples of a more general type called a sequence
    • Strings are sequences of characters
    • Lists are sequences of anything
  • Sequences are ordered, so we can number off their elements, which we call their index
    • Counting in Python always starts with 0, so the first element of the sequence has index 0
  • Python defines operations that work on all sequences
    • Selecting an individual element out of a sequence
    • Concatenating two sequences together
    • Determing the number of elements in a sequence

Selection

  • You can select or “pluck out” just a single element from a sequence using square brackets [ ]
    • There are no commas between these square brackets, so they can’t be confused with a list
    • The square brackets come after the sequence (or variable name representing a sequence)
    • Inside the square brackets, you place the index number of the element you want to select
>>> A = [2, 4, 6, 8]
>>> print(A[1])
4
>>> B = "Spaghetti"
>>> print(B[6])
't'

Concatenation

  • Concatenation is the act of taking two separate objects and bringing them together to create a single object
  • For sequences, concatenation takes the contents of one sequence and add them to the end of another sequence
  • The + operator concatenates sequences
    • This is why it is important to keep track of your variable types! + will add two integers, but will concatenate two strings
    >>> 'fish' + 'sticks'
    'fishsticks'
    >>> A = [1, 'fish']
    >>> B = [2, 'fish']
    >>> print(A + B)
    [1, 'fish', 2, 'fish']

Lengths

  • The number of elements in a sequence is commonly called its length, and can be given by the len( ) function

  • Simply place the sequence you desire to know the length of between the parentheses:

    >>> len("spaghetti")
    9
  • You can have sequences of 0 length as well!

    >>> A = ""
    >>> B = [ ]
    >>> print( len(A) + len(B) )
    0

Understanding Check

What would be the printed output of the code to the right?

  1. 12
  2. 13
  3. 14
  4. 15
A = "hots"
B = ["fire", A + A]
C = A[3] + A[1]
B += C + C[0]
D = B[0] + B[1] + B[2]
print(len(D))

Running a Program

  • Python programs specify what part of the code is supposed to be when a program is run using a few special lines at the end of the program

    if __name__ == '__main__':
        function_to_run()
    • function_to_run is the name of whatever function you want to execute when the program is run
  • Patterns of this sort are commonly called boilerplate

    • Less important to fully understand all the pieces of it now
    • Is important to understand what it is doing and how to implement it correctly

Sample Program


NUM_ODDS = 100 # Constant, so using all caps

def print_odds():
    """
    Prints the first NUM_ODDS odd numbers 
    starting at 1.
    """
    value = 1
    for i in range(NUM_ODDS):
        print(value)
        value += 2

if __name__ == '__main__':
    print_odds()

An adding program

# File: AddTwoIntegers.py

"""
This program adds two integers entered by the user.
"""

def add_two_integers():
    print("This program adds two integers.")
    n1 = int(input("Enter n1? "))
    n2 = int(input("Enter n2? "))
    total = n1 + n2
    print("The sum is", total)

# Startup boilerplate
if __name__ == '__main__':
    add_two_integers()

Visiting the library(ies)

  • A huge strength of Python is that it offers a very large number of code collections called libraries
    • Can save you the effort from writing that code yourself!
  • Requires you to import that library, which can take several different forms
    • Most common is to use import to grab everything in a library

      import math
      • You must then access any function in that library using its fully qualified name, which includes the library name (var = math.sqrt(4))
    • Can also use from ... import to grab specific functions from the library

      from math import sqrt
      • You do not need to use the library name then when you call it (var = sqrt(4))

Useful math definitions

Code Description
math.pi The mathematical constant \(\pi\)
math.e The mathematical constant \(e\)
math.sqrt(x) The square root of x
math.log(x) The natural logarithm of x
math.log10(x) The base 10 logarithm of x
math.sin(x) The sine of x in radians
math.cos(x) The cosine of x in radians
math.asin(x) The arcsin of x
math.degrees(x) Converts from radians to degrees
math.radians(x) Converts from degrees to radians

Class Activity

  • I’m introducing Pensieve AI Tutor in this class to:
    • try out how an intelligent tool can better facilitate your understanding
    • give you more hands on experience through class engagement
Pensieve Tutor - CS151

Class Activity

  • Use this invited link to access your Pensieve Tutor student page
    • If prompted, login with your willamette.edu email
Pensieve Tutor - Activity Page
// reveal.js plugins