Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
dsc-courses
GitHub Repository: dsc-courses/dsc10-2022-fa
Path: blob/main/lectures/lec03/lec03.ipynb
3058 views
Kernel: Python 3 (ipykernel)
# Don't worry about what this code does, but make sure to run it if you're following along. from IPython.display import IFrame def show_nested_eval(): src = 'https://docs.google.com/presentation/d/e/2PACX-1vQpW0NzwT3LjZsIIDAgtSMRM1cl41Gp_Lf8k9GT-gm5sGAIynw4rsgiEFbIybClD6QtxarKaVKLbR9U/embed?start=false&loop=false&delayms=60000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"' width = 960 height = 569 return IFrame(src, width, height)

Lecture 3 – Expressions and Data Types

DSC 10, Fall 2022

Announcements

Agenda

  • What is code? What are Jupyter Notebooks?

  • Expressions.

  • Variables.

  • Call expressions.

  • Data types.

Lots of programming – follow along in the notebook by clicking the "Expressions and Data Types" link on the course website.

What is code? What are Jupyter Notebooks? πŸ’»

What is code?

  • Instructions for computers are written in programming languages, and are referred to as code.

  • β€œComputer programs” are nothing more than recipes: we write programs that tell the computer exactly what to do, and it does exactly that – nothing more, and nothing less.

Why Python?

  • Popular.

  • Variety of uses.

    • Web development.

    • Data science and machine learning.

    • Not really used for developing applications.

  • Easy to dive right in!

Jupyter Notebooks πŸ““

  • Often, but not in this class, code is written in a text editor and then run in a command-line interface.

  • Jupyter Notebooks allow us to write and run code within a single document. They also allow us to embed text and code. We will be using Jupyter Notebooks throughout the quarter.

  • DataHub is a server that allows you to run Jupyter Notebooks from your web browser without having to install any software locally.

Aside: lecture slides

  • The lecture slides you're viewing right now are also in the form of a Jupyter Notebook – we're just using an extension (called RISE) to make them look like slides.

  • When you click a "lecture" link on the course website, you'll see the lecture notebook in regular notebook form.

  • To view it in slides form, click the bar chart button in the toolbar.

This button!

Expressions

Python as a calculator

  • An expression is a combination of values, operators, and functions that evaluates to some value.

  • For now, let's think of Python like a calculator – it takes expressions and evaluates them.

  • We will enter our expressions in code cells. To run a code cell, either:

    • Hit shift + enter (or shift + return) on your keyboard (strongly preferred), or

    • Press the "β–Ά Run" button in the toolbar.

17
-1 + 3.14
2 ** 3
(17 - 14) / 2
# Only one value is displayed. Why? 3 * 4 5

Arithmetic operations

| Operation | Operator | Example | Value | | --- | --- | --- | --- | | Addition | + | 2 + 3 | 5 | | Subtraction | - | 2 - 3 | -1 | | Multiplication | * | 2 * 3 | 6 | | Division | / | 7 / 3 | 2.66667 | | Remainder | % | 7 % 3 | 1 | | Exponentiation | ** | 2 ** 0.5 | 1.41421 |

Python uses the typical order of operations – PEMDAS (BEDMAS?)

3 * 2 ** 2
(3 * 2) ** 2

Activity

In the cell below, replace the ellipses with an expression that's equivalent to

(19+6β‹…3)βˆ’15β‹…(100β‹…130)β‹…35+4223+(6βˆ’23)β‹…12(19 + 6 \cdot 3) - 15 \cdot \left(\sqrt{100} \cdot \frac{1}{30}\right) \cdot \frac{3}{5} + \frac{4^2}{2^3} + \left( 6 - \frac{2}{3} \right) \cdot 12

Try to use parentheses only when necessary.

...

Variables

Motivation

Below, we compute the number of seconds in a year.

60 * 60 * 24 * 365

If we want to use the above value later in our notebook to find, say, the number of seconds in 12 years, we'd have to copy-and-paste the expression. This is inconvenient, and prone to introducing problems.

60 * 60 * 24 * 365 * 12

It would be great if we could store the initial value and refer to it later on!

Variables and assignment statements

  • A variable is a place to store a value so that it can be referred to later in our code. To define a variable, we use an assignment statement.

myvariable⏞name=2 + 3⏞any expression\overbrace{\texttt{myvariable}}^{\text{name}} = \overbrace{\texttt{2 + 3}}^{\text{any expression}}
  • An assignment statement changes the meaning of the name to the left of the = symbol.

  • The expression on the right-hand side of the = symbol is evaluated before being assigned to the name on the left-hand side.

    • e.g. myvariable is bound to 5 (value) not 2 + 3 (expression).

Note that before we use it in an assignment statement, more_than_1 has no meaning.

more_than_1

After using it in an assignment statement, we can ask Python for its value.

# Note that an assignment statement doesn't output anything! more_than_1 = 15 - 5
more_than_1

Anytime we use more_than_1 in an expression, 10 is substituted for it.

more_than_1 * 2

Note that the above expression did not change the value of more_than_1, because we did not re-assign more_than_1!

more_than_1

Naming variables

  • Generally, give your variables helpful names so that you know what they refer to.

  • Variable names can contain uppercase and lowercase characters, the digits 0-9, and underscores.

    • They cannot start with a number.

    • They are case sensitive!

The following assignment statements are valid, but use poor variable names πŸ˜•.

six = 15
i_45love_chocolate_9999 = 60 * 60 * 24 * 365

The following assignment statements are valid, and use good variable names βœ….

seconds_per_hour = 60 * 60 hours_per_year = 24 * 365 seconds_per_year = seconds_per_hour * hours_per_year

The following "assignment statements" are invalid ❌.

6 = 15
3 = 2 + 1

Assignment statements are not mathematical equations!

  • Unlike in math, where x=3x = 3 means the same thing as 3=x3 = x, assignment statements are not "symmetric".

  • An assignment statement assigns (or "binds") the name on the left of = to the value to the right of =, nothing more.

x = 3 x
4 = x

A variable's value is set at the time of assignment

uc = 2 sd = 3 + uc

Assignment statements are not promises – the value of a variable can change!

uc = 7

Note that even after changing uc, we did not change sd, so it is still the same as before.

sd

A helpful analogy

  • A common metaphor is that variables are like boxes or containers (source).

  • Another analogy: an assignment statement is like placing a sticker on a value.

Concept Check βœ… – Answer at cc.dsc10.com

Assume you have run the following three lines of code:

side_length = 5 area = side_length ** 2 side_length = side_length + 2

What are the values of side_length and area after execution?

A. side_length = 5, area = 25

B. side_length = 5, area = 49

C. side_length = 7, area = 25

D. side_length = 7, area = 49

E. None of the above

Aside: hit tab to autocomplete a set name

...

Call expressions πŸ“ž

Algebraic functions

  • In math, functions take in some input and return some output.

f(x,y)=2x2+3xyβˆ’1f(x, y) = 2x^2 + 3xy - 1
  • We can determine the output of a function even if we pass in complicated things.

f(1+23+4,(βˆ’1)15)f\left(\frac{1+2}{3+4}, (-1)^{15}\right)

Call expressions

  • Call expressions in Python invoke functions – they tell a function to "run its recipe".

  • Functions in Python work the same way functions in math do.

  • The inputs to functions are called arguments.

abs(-12)

Some functions can take a variable number of arguments

max(3, -4)
max(2, -3, -6, 10, -4)
# Only two arguments! max(4 + 5, 5 - 4)

Use the ? after a function to see the documentation for a function

Or, use the help function, e.g. help(max).

max?

Example: round

my_number = 1.22 round(my_number)
round?
round(1.22222, 3)

Nested evaluation

We can nest many function calls to evaluate sophisticated expressions.

min(abs(max(-1, -2, -3, min(4, -2))), max(5, 100))

...how did that work?

show_nested_eval()

Import statements

  • Python doesn't have everything we need built in.

  • In order to gain additional functionality, we import modules via import statements.

  • Modules can be thought of as collections of Python functions and values.

  • Call these functions using the syntax module.function(), called "dot notation".

Example: import math

sqrt, log, pow, etc.

import math
math.sqrt(9)
math.pow(3, 2)
# What base is log? math.log?
# Tab completion for browsing math.

It also has constants built-in!

math.pi

Concept Check βœ… – Answer at cc.dsc10.com

Assume you have run the following statements:

x = 3 y = -2

Which of these examples results in an error?

A. abs(x, y)

B. math.pow(x, abs(y))

C. round(x, max(abs(y ** 2)))

D. math.pow(x, math.pow(y, x))

E. More than one of the above

Data types

What's the difference? 🧐

4 / 2
5 - 3

To us, 2.0 and 2 are the same number, 22. But to Python, these appear to be different! 😱

Data types

  • Every value in Python has a type.

    • Use the type function to check a value's type.

  • It's important to understand how different types work with different operations, as the results may not always be what we expect.

Two numeric data types: int and float

  • int : An integer of any size.

  • float: A number with a decimal point.

int

  • If you use these operations between ints (+, -, *, **), the result will be another int.

  • ints have arbitrary precision in Python, meaning that your calculations will always be exact.

3 + 5
type(3 + 5)
2 ** 300
2 ** 3000

float

  • A float is specified using a decimal point.

  • A float might be printed using scientific notation.

2.0 + 3.2
type(2.0 + 3.2)
2.0 ** 300

The pitfalls of float

  • floats have limited size (but the limit is huge).

  • floats have limited precision of 15-16 decimal places.

  • After arithmetic, the final few decimal places can be wrong in unexpected ways (limited precision!).

1 + 0.2
1 + 0.1 + 0.1
2.0 ** 3000

Type coercion between int and float

  • By default, Python changes an int to a float in a mixed expression involving both types.

    • Note that the division of two ints automatically returns a float value.

  • A value can be explicity coerced (i.e. converted) using the int and float functions.

2.0 + 3
2 / 1
# Want an integer back int(2 / 1)
# int chops off the decimal point, effectively rounding DOWN int(3.9)

Aside: Jupyter memory model

Our notebook still remembers all of the variables we defined earlier in the lecture.

more_than_1
  • However, if you come back to your notebook after a few hours, it will usually "forget" all of the variables it once knew about.

  • When this happens, you will need to run the cells in your notebook again.

  • See Navigating DataHub and Jupyter Notebooks for more.

Summary, next time

Summary

  • Expressions evaluate to values. Python will display the value of the last expression in a cell by default.

  • Python knows about all of the standard mathematical operators and follows PEMDAS.

  • Assignment statements allow us to bind values with variables.

  • We can call functions in Python similar to how we call functions in math.

    • Python knows some functions by default, and import statements allow us to bring additional functionality from modules.

  • All values in Python have a data type.

    • ints and floats are numbers.

    • ints are integers, while floats contain decimal points.

Next time

We'll learn about strings, a data type in Python designed to store text. We'll also learn how to store many pieces of information in a single value, using arrays.

Note: We will introduce some code in labs and homeworks as well. Not everything will be in lecture. You will learn by doing!