2000 + 25
2025
Learn about the basics of Python.
This module covers the Python basics you need for this course. It isn’t an exhaustive guide to Python, but it’s enough for anyone with previous coding experience (see Prerequisite Course(s)).
You will learn how Python represents numbers, letters, and words, followed by arithmetic operations. We’ll also build important programming vocabulary. I won’t test you on these terms, but you’ll need them for future lessons.
Next, we’ll learn about variables, statements, the
import
statement, and the print()
function.
We’ll also discuss function arguments and Python modules.
An arithmetic operator is a symbol that represents a computation. For example:
+
performs addition:2000 + 25
2025
-
performs subtraction:2030 - 5
2025
*
performs multiplication:405 * 25
10125
/
performs division:10125 / 5
2025.0
Notice that the result of division is 42.0
vs
42
. Python recognizes two numeric types:
If you add, subtract, or multiply two integers, the result remains an integer. However, dividing two integers produces a floating-point result.
Python also supports integer division with the
operator //
, which always return an integer:
4050 // 2
2025
This operator is called “floor division” because it always rounds down:
4051 // 2
2025
The modulus operator %
returns the
remainder after dividing two numbers:
4051 % 2 # remainder is 1
1
If a number divides evenly, %
returns
0
:
4050 % 2 # remainder is 0
0
Finally, **
performs exponentiation (raising a number to
a power):
4.58442641 ** 5
2025.0000056375889
In other languages, like R, you use the caret
^
for exponentiation, but in Python ^
is the
“XOR” operator, which we won’t cover here.
An expression is a combination of operators and values:
6 + 6 ** 2
42
Python follows standard order of operations:
12 + 5 *6
42
Use parentheses to change that order:
12 + 5) * 6 (
102
Every expression evaluates to a value, so
6 * 7
becomes 42
.
Python provides functions that work with numbers, such as:
round()
rounds a float to the nearest integer:round(4.58442641 ** 5)
2025
abs()
returns the absolute valueabs(-2025)
2025
When you call a function, you must use parentheses. Omitting them causes a syntax error:
abs 42 # correct usage: abs(42)
Cell In[15], line 1 abs 42 # correct usage: abs(42) ^ SyntaxError: invalid syntax
If you type only the function name:
abs
<function abs(x, /)>
Python tells you that abs
is indeed a function, along
with some extra details.
A string is a sequence of characters. You can enclose them in single or double quotes:
print('Hello')
print("World")
Hello
World
Use double quotes if you need an apostrophe, or single quotes if you need a double quote:
print("That's her book")
print('"I see," he said')
That's her book
"I see," he said
Python treats single and double quotes the same; you can choose either as long as you’re consistent.
Triple-quoted strings can span multiple lines or contain both single and double quotes:
print('''"That's great", she said.''')
print("""
To be,
or not to be,
that is definitely a question.
""")
"That's great", she said.
To be,
or not to be,
that is definitely a question.
Strings can hold spaces, punctuation, and digits:
print("How the turn tables... uhh wait. What was line 5?")
How the turn tables... uhh wait. What was line 5?
Use the +
operator to concatenate
(join) strings:
print('Well, ' + "it's a small " + 'world.')
Well, it's a small world.
Use the *
operator to repeat strings:
print('RA' + 'TA' * 3)
RATATATA
Other arithmetic operators don’t work on strings.
You can use len()
to find a string’s length:
len('12345')
5
Notice that len()
counts the the letters between the
quotes, but not the quotes themselves.
Avoid backticks `
or curly quotes “ ”
because they cause syntax errors:
print(`hello`)
Cell In[24], line 1 print(`hello`) ^ SyntaxError: invalid syntax
print(“hello”)
Cell In[25], line 1 print(“hello”) ^ SyntaxError: invalid character '“' (U+201C)
Most code editors color valid strings differently, so keep an eye on syntax highlighting to avoid mistakes.
We’ve encountered three kinds of values:
2
(integer)42.0
(float)"text"
(string)A kind of value is called a type. Every value has a type, also referred to as “belongs to” a type.
Python provides a function, type()
, that tells you the
type of any value:
type(2)
int
type(42.0)
float
type("text")
str
int
, float
, and str
can also
convert values:
int(42.9) # rounds down to 42
42
float(42) # converts integer 42 to float 42.0
42.0
str(123) # converts number 123 to the string "123"
'123'
If you try arithmetic on a string, you get an error:
print(123 * 3) # numeric multiplication
print("123" * 3) # string repetition
369
123123123
print("500" / 5) # TypeError: can't divide a string by an integer
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[33], line 1 ----> 1 print("500" / 5) # TypeError: can't divide a string by an integer TypeError: unsupported operand type(s) for /: 'str' and 'int'
To fix this, cast to the right type:
int("126") * 3
378
If you have a large integer, you may type it like
1,000,000
. This is a legal expression in Python, but the
value is not what you would expect:
1,000,000
(1, 0, 0)
Python interprets 1,000,000
as a comma-separated
sequence of integers. We’ll learn about this kind of sequence later.
You can use underscores to make large numbers easier to read:
1_000_000
1000000
Natural languages (English, Spanish, etc.) evolved over time and rely on context, idioms, and sometimes ambiguity. Formal languages like Python are precise and unambiguous. Python does exactly what you write, so details matter. Small mistakes in spelling or punctuation can cause big errors. You might find this rigid at first, but you’ll adapt with practice.
A variable is a name that refers to a value. Create one with an assignment statement:
= 17 n
The assignment has three parts:
=
operator17
here)= 3.141592653589793
pi = "pie > π" message
Once assigned, you can use these variables:
print(message)
print(n + 5)
print(2 * pi)
print(round(pi))
print(len(message))
pie > π
22
6.283185307179586
3
7
You can use letters and digits in a variable name but cannot start
with a digit. Although uppercase letters are allowed, most Python code
uses lowercase. Use underscores to connect words: your_name
or airspeed_of_unladen_swallow
.
A name containing punctuation (million!
) or starting
with a number (76trombones
) triggers a syntax error. Some
words, like class
, are keywords and cannot be variable
names.
! = 1000000 million
Cell In[40], line 1 million! = 1000000 ^ SyntaxError: invalid syntax
76trombones
is illegal because it starts with a
number.
76trombones = 'big parade'
Cell In[41], line 1 76trombones = 'big parade' ^ SyntaxError: invalid decimal literal
class
is also illegal, but it might not be obvious
why.
class = 'Defense Against the Dark Arts'
Cell In[42], line 1 class = 'Defense Against the Dark Arts' ^ SyntaxError: invalid syntax
Your editor will often highlight keywords in a different color so you can recognize them.
import
statementSome features require importing. For example, to use
the math
module:
import math
A module is a collection of variables and functions.
Python’s math
module provides a variable called pi
that contains the
value of the mathematical constant π:
math.pi
3.141592653589793
Use the dot to access module features:
print(math.sqrt(25))
print(math.pow(5, 2)) # 5 ** 2 behaves the same as math.pow(5, 2)
5.0
25.0
An expression calculates a value, regardless of its complexity:
19 + n + round(math.pi) * 2
42
A statement performs an action without producing a value you can use:
= 17 n
We evaluate expressions to get their value and execute statements to perform actions.
print()
functionWhen you type an expression in many Python environments, it displays
the result. But if you have multiple expressions in a single cell (or
script), only the last one appears. Use print()
to display
more than one item:
print(n + 2)
print(n + 3)
print("The value of pi is approximately", math.pi)
19
20
The value of pi is approximately 3.141592653589793
print()
separates arguments with a space by default.
The expressions inside a function call’s parentheses are arguments. Different functions accept different numbers of arguments:
int()
can take one required argument and an optional
base:int("101", 2)
5
math.pow()
takes two arguments:pow(5, 2) math.
25.0
round()
can take an optional second argument (decimals
to round):round(math.pi, 3)
3.142
print()
accepts any number of arguments:print("Any", "number", "of", "arguments")
Any number of arguments
If you supply too many or too few arguments, or if the arguments are the wrong type, Python raises a TypeError:
float("123", 2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[53], line 1 ----> 1 float("123", 2) TypeError: float expected at most 1 argument, got 2
pow(2) math.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[54], line 1 ----> 1 math.pow(2) TypeError: pow expected 2 arguments, got 1
"25") math.sqrt(
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[55], line 1 ----> 1 math.sqrt("25") TypeError: must be real number, not str
We call mistakes in code bugs, and the process of finding and fixing them debugging. You might feel frustrated when things break, but remember it’s normal and part of learning.
Think of the computer as precise but inflexible. You must provide exact instructions because it doesn’t infer or guess what you mean.
! = 1000000 million
Cell In[59], line 1 million! = 1000000 ^ SyntaxError: invalid syntax
"126" / 3
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[60], line 1 ----> 1 "126" / 3 TypeError: unsupported operand type(s) for /: 'str' and 'int'
# This uses area in cm² instead of m²
= 500 # Newtons
force = 10 # cm² (wrong units)
area = force / area
stress print(stress) # No error, but incorrect value => semantic error
50.0
Experiment with round()
when a number ends in
0.5
. It sometimes rounds up and sometimes down. Figure out
the pattern:
round(42.5)
42
round(43.5)
44
+
sign before a number
(+2
) or repeat it (2++2
)? What about
2--2
?4 2
)?round(42.5)
but remove one or both
parentheses?Guess each expression’s type and then use type()
to
check:
765
2.718
"2 pi"
abs(-7)
abs
int
type
1.61 kilometers/mile
)?n = 17
is legal, what about
17 = n
?x = y = 1
?;
). What happens if you put a semi-colon at the end of a
Python statement?import maath
?The formula for the volume of a sphere with radius \(r\) is \(\frac{4}{3} \pi r^3\). Compute it for \(r = 5\).
radius
(in
centimeters)volume
(in cubic centimeters)According to a trig identity, \((\cos x)^2
+ (\sin x)^2 = 1\). Test this for x = 42
.
x
to 42
math.cos()
and math.sin()
to
computeIt might not be exactly 1 because of floating-point imprecision.
The math
module defines e
. Compute \(e^2\) in three ways:
math.e
and the exponentiation operator.math.pow
to raise math.e
to the power
2
.math.exp
, which takes as an argument a value, \(x\), and computes \(e^x\).Compare the results and see which appears most accurate.
14 Comments
As code grows, comments clarify your reasoning or record important details. Python ignores text after a
#
:Good comments explain why you wrote the code in a certain way (especially if it’s not obvious):
Bad comments restate the obvious:
Well-chosen variable names can reduce the need for comments, but avoid names so long that they make expressions unreadable.