02 | Intro to Python

Learn about the basics of Python.

Author
Affiliation

Mr. Ozan Ozbeker

1 Overview

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.

2 Arithmetic operators

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:

  1. integers: numbers without a decimal part
  2. floating-point numbers (float): numbers with a decimal point (including integer-like values stored in floating form)

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
Tip

In other languages, like R, you use the caret ^ for exponentiation, but in Python ^ is the “XOR” operator, which we won’t cover here.

3 Expressions

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.

4 Arithmetic functions

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 value
abs(-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.

5 Strings

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
Tip

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
Note

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)
Tip

Most code editors color valid strings differently, so keep an eye on syntax highlighting to avoid mistakes.

6 Values and types

We’ve encountered three kinds of values:

  1. 2 (integer)
  2. 42.0 (float)
  3. "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

7 Formal and natural languages

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.

8 Variables

A variable is a name that refers to a value. Create one with an assignment statement:

n = 17

The assignment has three parts:

  1. The variable name
  2. The = operator
  3. An expression (17 here)
pi = 3.141592653589793
message = "pie > π"

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

9 Variable names

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.

million! = 1000000
  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
Tip

Your editor will often highlight keywords in a different color so you can recognize them.

10 The import statement

Some 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

11 Expressions vs statements

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:

n = 17

We evaluate expressions to get their value and execute statements to perform actions.

12 The print() function

When 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
Note

print() separates arguments with a space by default.

13 Function Arguments

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:
math.pow(5, 2)
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
math.pow(2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[54], line 1
----> 1 math.pow(2)

TypeError: pow expected 2 arguments, got 1
math.sqrt("25")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[55], line 1
----> 1 math.sqrt("25")

TypeError: must be real number, not str

14 Comments

As code grows, comments clarify your reasoning or record important details. Python ignores text after a #:

# Variables
force = 500 # Force in Newtons (N)
area = 0.01 # Cross-sectional area in square meters (m²)

# Formula
stress = force / area

# Output
print("Stress:", stress, "in (Pa)")
Stress: 50000.0 in (Pa)

Good comments explain why you wrote the code in a certain way (especially if it’s not obvious):

# Use SI units for consistency throughout the program
area = 0.01

Bad comments restate the obvious:

area = 0.01  # set area to 0.01

Well-chosen variable names can reduce the need for comments, but avoid names so long that they make expressions unreadable.

15 Debugging

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.

15.1 Common Errors

  1. Syntax erros: The code violates Python’s structure rules. Python refuses to run the code and points out where it got stuck:
million! = 1000000
  Cell In[59], line 1
    million! = 1000000
           ^
SyntaxError: invalid syntax
  1. Runtime errors: The code starts running but fails during execution, like dividing a string by an integer:
"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'
  1. Semantic errors: The code runs but does something unintended. For example, mixing up units might produce the wrong numeric result without an obvious error:
# This uses area in cm² instead of m²
force = 500       # Newtons
area = 10         # cm² (wrong units)
stress = force / area
print(stress)     # No error, but incorrect value => semantic error
50.0

16 Exercises

16.1 Rounding Behavior

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

16.2 Deliberate Mistakes

  1. What happens if you use a + sign before a number (+2) or repeat it (2++2)? What about 2--2?
  2. What if you write two values without an operator (4 2)?
  3. What if you call round(42.5) but remove one or both parentheses?

16.3 Type Checking

Guess each expression’s type and then use type() to check:

  • 765
  • 2.718
  • "2 pi"
  • abs(-7)
  • abs
  • int
  • type

16.4 More Arithmetic

  • How many seconds are there in 42 minutes 42 seconds?
  • How many miles are there in 10 kilometers (1.61 kilometers/mile)?
  • If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace in seconds per mile?

16.5 Intentional Errors

  • We’ve seen n = 17 is legal, what about 17 = n?
  • What about x = y = 1?
  • In some languages every statement ends with a semi-colon (;). What happens if you put a semi-colon at the end of a Python statement?
  • What if you put a period at the end of a statement?
  • What happens if you spell the name of a module wrong and try to import maath?

16.6 Volume of a Sphere

The formula for the volume of a sphere with radius \(r\) is \(\frac{4}{3} \pi r^3\). Compute it for \(r = 5\).

  • Start with a variable names radius (in centimeters)
  • Compute volume (in cubic centimeters)
  • Print the result and include comments

16.7 Trigonometry

According to a trig identity, \((\cos x)^2 + (\sin x)^2 = 1\). Test this for x = 42.

  • Create a variable named x to 42
  • Use math.cos() and math.sin() to compute
Note

It might not be exactly 1 because of floating-point imprecision.

16.8 Exploring \(e\)

The math module defines e. Compute \(e^2\) in three ways:

  • Use math.e and the exponentiation operator.
  • Use math.pow to raise math.e to the power 2.
  • Use math.exp, which takes as an argument a value, \(x\), and computes \(e^x\).

Compare the results and see which appears most accurate.

Back to top