Data Type & Functions?

Jed Rembold & Fred Agbo

January 29, 2024

Announcements

  • Problem Set 1 due tonight!
    • A new problem set will be posted later today or tomorrow
    • I’ll be trying to get feedback to you by early next week
  • If you recently added the course, ensure you fill out the section form here
  • Also use this link to join the Discord Server.
  • The last day you can add/drop a class without issue is tomorrow
  • Moving back into the book today, catching information and details from Ch 1 that we haven’t yet talked about
    • Text is posted here and also linked on the main course webpage
  • Polling: https://www.polleverywhere.com/agbofred203
    • Reminder: include enough of your name that I can uniquely identify you!

Review Question

Karel starts in the empty world shown at one of the marked positions and runs the below code. One of the starting positions will result in an error before the code finishes. Which one?

for i in range(3):
    move()
    turn_left()
    for i in range(2):
        if front_is_blocked():
            turn_around()
        move()
    turn_right()

Data Types

  • Generally, the data processed by computers can take on many forms
  • A data type defines the common characteristics of some data values that have a certain form or purpose.
    • Ex: a whole number or integer has certain characteristics common to all integers
  • A data type has a domain, which is the set of all potential values that would belong to that type.
    • Ex: 0,1,2,3,4,5,6,7,…
  • A data type has a set of operations that define how those values can be manipulated
    • Ex: You can add two whole numbers (5+2)

Numeric Types

  • Initially, we’ll focus on the numeric types
  • Python has 3 data types for representing numbers:
    • int for integers and whole numbers

      1, 2, 3, 10, 1001010101, -231
    • float for numbers containing a decimal point

      1.23, 3.14, 10.001, 0.0, -8.23
    • complex for numbers with an imaginary component (which we won’t deal with)

Expressions

  • Python describes computation using arithmetic expressions, which consist of terms joined by operators
    • Very similar to how a logical English sentence has nouns connected by verbs
  • A term in an expression can be:
    • an explicit numeric value (called a literal) like 1 or 3.14
    • a variable name serving as a placeholder to a value (more on those in a moment!)
    • a value resulting from the output of a function call (more on those on Monday!)
    • another expression enclosed in parentheses


[term] [term] [operator]

Integer and Float Operations

  • i + j  the sum of i and j
  • i - j  the difference between i and j
  • i * j  the product of i and j
  • i // j  the floor division of i by j
  • i / j  the division of i by j
  • i % j  the remainder when i is divided by j
  • i ** ji to the power of j
  • -j  the negation of j

– Returns int if both i and j are integers, float otherwise

– Returns float always

Order of Operations

  • Basic order of operations applies just like in math!
  • Operations in parentheses done first
  • Without parentheses, order of operations proceeds as:
    • ** (exponents, executed right to left)
    • -n (negative numbers)
    • *, /, //, %, executed from left to right
    • + and -, executed from left to right

Understanding Check

What is the value of the below expression?

1 * 2 * 3 + (4 + 5) % 6 + (7 * 8) // 9

  1. 15
  2. 18.22
  3. 42
  4. 83

Tis Variable

  • One of the terms that can appear in expressions is what we term a variable
  • A variable is a placeholder or nametag for a value that can be updated as the program progresses
  • Envision as a named box capable of storing a value

    'Will this work?

  • Each variable has the following attributes:
    • A name: which enables you to tell variables apart
    • A value: which represents the current contents of the variable
  • A variable’s name is fixed, but the value can change whenever you assign a new value to the variable

Making Assignments

  • You create a variable by assigning it a value with Python’s assignment statement =:

    variable_name = expression
  • The variable name must appear on the left of the =

  • Python first computes the value of the righthand side of the equals and then assigns to the name on the left

    • The same variable name can seem to appear on both sides of the equals!

      total = total + value
      • The total on the right represents some existing value
      • The total on the left is the new label of whatever the right summed to

Ephemeral Variables

  • When you assign a new value to a variable, the old value is lost

    >>> A = 10
    >>> print(A)
    10
    >>> B = A + 5
    >>> print(B)
    15
    >>> A = B
    >>> print(A)
    15
  • Variables defined in terms of others do not get automatically updated

    >>> A = 10
    >>> B = A + 2
    >>> A = 8
    >>> print(B)
    12

The Power of Names

  • Names for variables, functions, and classes are called identifiers
  • Composed of letters, numbers and underscores, but can not start with a number
  • A variety of different conventions to mark word boundaries:
    • Snake case uses underscores: this_is_amazing
    • Camel case uses uppercase: thisIsAmazing
  • We will aim to follow the following conventions:
    • Variable and function names will use snake case
    • Constant variables will use all uppercase and underscores: MAX_WIDTH
    • Class names will use camel case and begin with a capital letter
  • Capitalization matters! radius and Radius are different variable names!
  • Pick meaningful variable names!

Shorthand and Multiple

  • It is very common to want to adjust an existing variable

    balance = balance + deposit
  • Python gives you a shorter expression to describe this relationship:

    balance += deposit
  • You can do this with any operation (op) following the general form:

    variable op= expression
  • You can name multiple variables at once by separating with commas

    A, B, C = 1, 2, 3
    • All the expressions on the right are computed before being assigned to the left variables
    • This can give you a very concise way of swapping variable values

What is your Function?

  • As discussed in the context of Karel, a function is a sequence of commands that have been collected together and given a name.
  • Unlike in Karel though, functions typically go beyond that and can have inputs and outputs

Writing your own functions

  • The general form of a function definition looks like:

    def name(parameter_list):
        #statements in function body
    • name is your chosen name for the function
    • parameter_list is a comma-separated list of variable names that will hold each input value
  • You can return or output a value from the function by including a return statement

    return expression
    • expression is the value you want to return or output
    • If no return statement is included, Python will by default return None

A Functional Diagram

output input function def def cool(a,b): c = a + b return c + a cool(4,5) a 4 b 5

Simple function examples

  • Convert Fahrenheit temperatures to their Celsius equivalent

    def f_to_c(f):
        return 5 / 9 * (f - 32)
    • Using the function:

      print(f_to_c(45))
  • Computes the volume of a cylinder of height h and radius r

    def cylinder_volume(r, h):
        return 3.14159 * r**2 * h
    • Using the function:

      print(cylinder_volume(2,10))

Built-ins

  • All modern languages include a collection of pre-defined functions for convenience
  • In Python, common build-in functions that operate on numbers include:
Function Description
abs(x) The absolute value of x
max(x,y,...) The largest of all the arguments
min(x,y,...) The smallest of all the arguments
round(x) The value of x rounded to the nearest integer
int(x) The value of x truncated to an integer
float(x) The value of x as a decimal

Python Applications

  • In Python, application programs are generally stored in files whose names end with .py. Such files are called modules.
  • Most interesting applications interact with the user
    • In modern applications, this often happens through a graphical user interface or GUI
      • We’ll be constructing some GUIs later this semester!
    • For now, all interaction will happen through the terminal
      • Requires we know how to output information to the terminal and how to input information into the terminal

Output: print

  • We’ve already seen examples of how to output information to the terminal
  • Python’s built-in print() command will display whatever is between the () to the screen
  • If you want to display several things, you have options:
    • Separate each thing by a comma inside the print statement. This will insert a space between each when printed.

      print(1,2,'blue')
    • Concatenate what you want together with +, converting to strings as needed python print('2000' + ' - ' + '2023')

      print(str(1) + ' ' + str(2) + ' blue')

Boolean Expressions

  • Python defines two types of operators that work with Boolean data: relational operators and logical operators

  • Relational operators compare values of other types and produce a True/False result:

    == Equals != Not equals
    < Less than <= Less than or equal too
    > Greater than >= Greater than or equal to
  • Be careful! == compares two booleans. A single = assigns a variable. The odds are high you’ll use one when you meant the other at least once this semester!

The Vulcan Way

  • Logical operators act on Boolean pairings

    Operator Description
    A and B True if both terms True, False otherwise
    A or B True if any term is True, False otherwise
    not A True if A False, False if A True (opposite)
  • Order of operations follows parentheses and then proceeds left to right
  • Careful that or is still True if both options are True
  • Similarly, careful with combining not with and and or
    • “Not A or B” in common English is not the same as not A or B

Understanding Check

What value is printed when the code to the right runs?

  1. True
  2. False
  3. "4Quiz"
  4. This would give an error
A = 10
B = 4
C = "Quiz"
A *= B
if A > 40 and C != "C":
    print(str(B)+C)
else:
    print(A < B or not (C == "C"))

Shorting the Circuit

  • Python evaluates and and or operators using a strategy called short-circuit mode
  • Only evaluates the right operand if it actually needs to
    • Example: if n=0, then the x % n == 0 is never actually checked in the statement

      n != 0 and x % n == 0

      since n != 0 already is False and False and anything is always False

  • Can use short-circuit to prevent errors: the above x % n == 0 statement would have erred out if n=0

Input: input

  • To retrieve data from a user, we can use Python’s built-in input() function

  • The form will generally look like:

    variable = input(prompt_text)
    • variable is the variable name you want to assign the user’s typed input to
    • prompt_text is the string that will be displayed on the screen to communicate to the user what they should be doing
  • The input() function always returns a string

    • If you want to get an integer from the user, you will need to convert it yourself after retrieving it

      num = int(input('Pick a number between 1 and 10: '))
// reveal.js plugins