In [1]:
# Run this cell to set up packages for lecture.
from lec02_imports import *

Lecture 2 – Variables and Data Types¶

DSC 10, Winter 2025¶

Solution to the activity from last class¶

In the cell below, write an expression that's equivalent to

$$(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.

In [4]:
# Only the last pair of parentheses is necessary.
19 + 6 * 3 - 15 * 100 ** 0.5 * 1 / 30 * 3 / 5 + 4 ** 2 / 2 ** 3 + (6 - 2 / 3) * 12
Out[4]:
100.0

Common mistake¶

In [6]:
100 ** 1 / 2
Out[6]:
50.0

Agenda¶

  • Variables.
  • Calling functions.
  • Data types.

There will be lots of programming – follow along in the notebook by clicking the "💻 code" link on the course website.

Variables¶

Motivation¶

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

In [10]:
60 * 60 * 24 * 365
Out[10]:
31536000

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 errors.

In [12]:
60 * 60 * 24 * 365 * 12
Out[12]:
378432000

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.
$$ \overbrace{\texttt{zebra}}^{\text{name}} = \overbrace{\texttt{23 - 14}}^{\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. zebra is bound to 9 (value) not 23 - 14 (expression).

Think of variable names as nametags!¶

In [19]:
# Note: This is an assignment statement, not an expression.
# Assignment statements don't output anything!
a = 1
No description has been provided for this image
In [21]:
a = 2
No description has been provided for this image
In [23]:
b = 2
No description has been provided for this image

Example¶

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

In [58]:
triton
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[58], line 1
----> 1 triton

NameError: name 'triton' is not defined

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

In [61]:
triton = 15 - 5
In [63]:
triton
Out[63]:
10

Any time we use triton in an expression, 10 is substituted for it.

In [66]:
triton * -4
Out[66]:
-40

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

In [69]:
triton
Out[69]:
10

Naming variables¶

  • 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 😕.

In [73]:
six = 15
In [75]:
i_45love_chocolate_9999 = 60 * 60 * 24 * 365

The following assignment statements are valid, and use good variable names ✅.

In [78]:
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 ❌.

In [81]:
7_days = 24 * 7
  Cell In[81], line 1
    7_days = 24 * 7
     ^
SyntaxError: invalid decimal literal
In [83]:
3 = 2 + 1
  Cell In[83], line 1
    3 = 2 + 1
    ^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

Assignment statements are not mathematical equations!¶

  • Unlike in math, where $x = 3$ means the same thing as $3 = x$, assignment statements are not "symmetric".
  • An assignment statement assigns (or "binds") the name on the left of = to the value on the right of =, nothing more.
In [86]:
x = 3
In [88]:
3 = x
  Cell In[88], line 1
    3 = x
    ^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

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

In [91]:
uc = 2
sd = 3 + uc

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

In [94]:
uc = 7

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

In [97]:
sd
Out[97]:
5

Extra practice¶

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?

Answer this question without actually running any code. Then, to check your answer, copy-paste the three lines of code from above into a code cell and run the cell. Then display the values of the variables by typing each variable name into a code cell and running that cell to see the value of the variable.

In [ ]:
 
In [ ]:
 
In [ ]:
 

Aside: hit tab to autocomplete a set name¶

In [ ]:
 

Calling functions 📞¶

Algebraic functions¶

  • In math, functions take in some input and return some output.
$$f(x, y) = \frac{x}{y} + 2x^2 + y^5$$
  • We can determine the output of a function even if we pass in complicated-looking inputs.
$$f\left(\frac{5-3}{17 \cdot 2}, (4-3)^{-5}\right)$$

Python functions¶

  • Functions in Python work the same way functions in math do.
  • The inputs to functions are called arguments.
  • Python comes with a number of built-in functions that we are free to use.
  • Calling a function, or using a function, means asking the function to "run its recipe" on the given input.
In [108]:
abs(-23)
Out[108]:
23

Some functions can take a variable number of arguments¶

In [111]:
max(4, -8)
Out[111]:
4
In [113]:
max(2, -3, -6, 10, -4)
Out[113]:
10
In [115]:
max(9)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[115], line 1
----> 1 max(9)

TypeError: 'int' object is not iterable
In [117]:
# Only two arguments!
max(9 + 10, 9 - 10)
Out[117]:
19

Nested evaluation¶

We can nest many function calls to evaluate sophisticated expressions.

In [120]:
min(abs(max(-1, -2, -3, min(4, -2))), max(5, 100))
Out[120]:
1

...how did that work?

In [123]:
show_nested_eval()
Out[123]:

Put ? after a function's name to see its documentation 📄¶

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

In [126]:
round(1.45678)
Out[126]:
1
In [128]:
round?
Signature: round(number, ndigits=None)
Docstring:
Round a number to a given precision in decimal digits.

The return value is an integer if ndigits is omitted or None.  Otherwise
the return value has the same type as the number.  ndigits may be negative.
Type:      builtin_function_or_method
In [130]:
round(1.45678, 3)
Out[130]:
1.457

Import statements¶

  • Python doesn't have everything we need built in.
  • In order to gain additional functionality, we import modules through import statements.
  • Modules are collections of Python functions and values.
  • Call these functions using the syntax module.function(), called "dot notation".

Example: import math¶

Some of the many functions built into the math module are sqrt, pow, and log.

In [134]:
import math
In [136]:
math.sqrt(16)
Out[136]:
4.0
In [138]:
math.pow(2, 5)
Out[138]:
32.0
In [140]:
# What base is log?
math.log?
Docstring:
log(x, [base=math.e])
Return the logarithm of x to the given base.

If the base is not specified, returns the natural logarithm (base e) of x.
Type:      builtin_function_or_method
In [142]:
# Tab completion for browsing.
math.
  Cell In[142], line 2
    math.
         ^
SyntaxError: invalid syntax

math also has constants built in!

In [145]:
math.pi
Out[145]:
3.141592653589793

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? For the ones that don't error, try to determine what they evaluate to!

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

In [ ]:
 

Data types¶

What's the difference? 🧐¶

In [151]:
4 / 2
Out[151]:
2.0
In [153]:
5 - 3
Out[153]:
2

To us, 2.0 and 2 are the same number, $2$. 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 add (+), subtract (-), multiply (*), or exponentiate (**) ints, the result will be another int.
  • ints have arbitrary precision in Python, meaning that your calculations will always be exact.
In [159]:
7 - 15
Out[159]:
-8
In [160]:
type(7 - 15)
Out[160]:
int
In [163]:
2 ** 300
Out[163]:
2037035976334486086268445688409378161051468393665936250636140449354381299763336706183397376
In [165]:
2 ** 3000
Out[165]:
1230231922161117176931558813276752514640713895736833715766118029160058800614672948775360067838593459582429649254051804908512884180898236823585082482065348331234959350355845017413023320111360666922624728239756880416434478315693675013413090757208690376793296658810662941824493488451726505303712916005346747908623702673480919353936813105736620402352744776903840477883651100322409301983488363802930540482487909763484098253940728685132044408863734754271212592471778643949486688511721051561970432780747454823776808464180697103083861812184348565522740195796682622205511845512080552010310050255801589349645928001133745474220715013683413907542779063759833876101354235184245096670042160720629411581502371248008430447184842098610320580417992206662247328722122088513643683907670360209162653670641130936997002170500675501374723998766005827579300723253474890612250135171889174899079911291512399773872178519018229989376

float¶

  • A float is specified using a decimal point.
  • A float might be printed using scientific notation.
In [168]:
3.2 + 2.5
Out[168]:
5.7
In [170]:
type(3.2 + 2.5)
Out[170]:
float
In [172]:
# The result is in scientific notation: e+90 means "times 10^90".
2.0 ** 300
Out[172]:
2.037035976334486e+90

The pitfalls of float¶

  • floats have limited precision; after arithmetic, the final few decimal places can be wrong in unexpected ways.
  • floats have limited size, though the limit is huge.
In [175]:
1 + 0.2
Out[175]:
1.2
In [177]:
1 + 0.1 + 0.1
Out[177]:
1.2000000000000002
In [179]:
2.0 ** 3000
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
Cell In[179], line 1
----> 1 2.0 ** 3000

OverflowError: (34, 'Result too large')

Converting between int and float¶

  • If you mix ints and floats in an expression, the result will always be a float.
    • Note that when you divide two ints, you get a float back.
  • The function int converts its input into an int. Likewise, the function float converts its input into a float.
In [182]:
2.0 + 3
Out[182]:
5.0
In [184]:
12 / 2
Out[184]:
6.0
In [186]:
# Want an integer back.
int(12 / 2)
Out[186]:
6
In [188]:
# int chops off the decimal point!
int(-2.9)
Out[188]:
-2

Strings 🧶¶

  • A string is a snippet of text of any length.
  • In Python, strings are enclosed by either single quotes or double quotes (doesn't matter which!)
In [191]:
'woof'
Out[191]:
'woof'
In [193]:
type('woof')
Out[193]:
str
In [195]:
"woof 🐶🐶"
Out[195]:
'woof 🐶🐶'
In [197]:
# A string, not an int!
"1998"
Out[197]:
'1998'

String arithmetic¶

When using the + symbol between two strings, the operation is called "concatenation".

In [200]:
s1 = 'baby'
s2 = '🐼'
In [202]:
s1 + s2
Out[202]:
'baby🐼'
In [204]:
s1 + ' ' + s2
Out[204]:
'baby 🐼'
In [206]:
# Multiplication is repeated addition, same as s1 + s1 + s1.
s1 * 3 
Out[206]:
'babybabybaby'

String methods¶

  • Associated with strings are special functions, called string methods.
  • Access string methods with a . after the string ("dot notation").
    • For instance, to use the upper method on string s, we write s.upper().
  • Examples include upper, title, and replace, but there are many more.
In [209]:
fave_string = 'My favorite class is DSC 10!'
In [211]:
fave_string.title()
Out[211]:
'My Favorite Class Is Dsc 10!'
In [213]:
fave_string.upper()
Out[213]:
'MY FAVORITE CLASS IS DSC 10!'
In [215]:
fave_string.replace('favorite', '😍' * 3)
Out[215]:
'My 😍😍😍 class is DSC 10!'
In [217]:
# You can use string methods directly on strings, even if not stored in a variable.
"hello".upper()
Out[217]:
'HELLO'
In [219]:
# len is not a method, since it doesn't use dot notation.
len(fave_string)
Out[219]:
28

Type conversion to and from strings¶

  • Any value can be converted to a string using the function str.
  • Some strings can be converted to int and float.
In [222]:
str(3)
Out[222]:
'3'
In [224]:
float('3')
Out[224]:
3.0
In [226]:
int('4')
Out[226]:
4
In [228]:
int('baby panda')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[228], line 1
----> 1 int('baby panda')

ValueError: invalid literal for int() with base 10: 'baby panda'
In [230]:
int('4.3')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[230], line 1
----> 1 int('4.3')

ValueError: invalid literal for int() with base 10: '4.3'

Concept Check ✅ – Answer at cc.dsc10.com¶

Assume you have run the following statements:

x = 3
y = '4'
z = '5.6'

Choose the expression that will be evaluated without an error.

A. x + y

B. x + int(y + z)

C. str(x) + int(y)

D. str(x) + z

E. All of them have errors

In [ ]:
 

Aside: Jupyter memory model¶

No description has been provided for this image

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

In [235]:
triton
Out[235]:
10
  • 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¶

  • Assignment statements allow us to bind values to variables.
  • We can call functions in Python similar to how we call functions in math.
    • Python knows some functions by default. Import statements allow us to bring in additional functions.
  • All values in Python have a data type.
    • ints and floats are numbers. Strings (str) are for text.
    • ints are integers, while floats contain decimal points.
    • Strings should be enclosed in single or double quotes.

Next time¶

We'll learn how to store sequences, or many pieces of information, in a single variable.

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