1. Python Introduction I#
Python’s core built-in objects#
Object type: |
Examples: |
Numbers |
123, 3.14, math.pi, … |
Strings |
‘abc’, ‘EPFL’, “Geneva”, … |
Lists |
[1, [2, ‘troi’],4], list(range(99) |
Dictionaries |
{‘Apples’: 200, ‘Pears’: 123.5}, dict(hours=10) |
Tuples |
(x,y,z), (1, [2, ‘troi’],4) |
Sets |
set(‘abc’), {‘E’,’P’,’F’,’L’} |
Other core types |
Booleans, types, None |
Files |
open(‘data.txt’), open(r(‘/home/alex/abc.bin’),’wb’) |
Program unit types |
Functions, modules, classes |
For more details check out the Python docs!
Here, we briefly summarize Numbers, Strings, Lists and Dictionaries.
Numbers in Python#
Python’s core objects include integers, floating-point, complex numbers, etc.
Types of numbers:
int
represents integers, e.g.2
,14213555
float
represents reals, e.g.pi
,1.0
,0.000001
complex
represents complex numbeers, e.g. real + imaginarybool
represents Boolean values,True
andFalse
type()
returns the type of Python objects
>>> type(5) # again, ```>>>```m denotes what you type in a Python shell
int # here is the output!
>>> type(3.0)
float
>>> type(True)
bool
>>> complex(1,1) # define a complex number
(1+1j) # evaluates to this!
>>> complex(0,1)**2 # remember: sqrt(-1) = j
(-1,0j)
>>> type(complex(1,1))
complex
Strings#
strings are concatenations of letters, special characters, numbers, and spaces
they are case sensitive!
strings can be defined by enclosing in quotation marks (”) or single quotes (‘).
Examples:
>>> S = 'Geneva' # make a 6-character string and assign it to a name
>>> S = "Lausanne" # make a 8-character string and assign it to a name
>>> S = str(3) # cast integer 3 to string and assign to name
>>> type(S)
str
Lists#
ordered sequences of objects
accessible by index
have no fixed size and are very flexible
a list is denoted by square brackets []
Three examples:
list1=[0,1,2,3]
list2=[0,'abc'] # lists can have mixed types; here int + str
list3=['EPFL','is','in',['Lausanne','VD']] # they support arbitrary nesting
Dictionaries#
Dictionaries are
collections of key-value pairs that maps from keys to values.
the keys can be any immutable type, and the values can be any type.
like lists they can also be mixed and nested
a dict is denoted by curly brackets {}
An example:
inventory = {'Apples': 200, 'Pears': 123.5}
Debugging in Python - Finding and Fixing Errors#
Bugs are errors in your code that prevent it from working correctly. Learning to debug is essential for every programmer!
Types of Errors#
Syntax Errors: Your code doesn’t follow Python’s rules
Missing colons after
if
statements or loopsUnmatched parentheses or quotes
Python tells you exactly where the problem is
Runtime Errors: Code crashes while running
Division by zero:
5 / 0
Using wrong list index:
my_list[999]
when list only has 3 itemsConverting invalid strings:
int("hello")
Logic Errors: Code runs but gives wrong results
Using
>
instead of<
in a conditionWrong formula in calculations
These are the trickiest to find!
Simple Debugging with print()#
The easiest way to debug is adding print()
statements:
# Check variable values
x = 10
y = 20
print("x is:", x, "y is:", y)
# Track where your code is
print("About to start the loop")
for i in range(3):
print("Loop step:", i)
Reading Error Messages#
Python gives you helpful error messages - always read them carefully! They tell you:
What type of error occurred
Which line caused the problem
What Python expected to see
Interactive Debugging in Jupyter#
In Jupyter notebooks, you can use the interactive debugger:
set_trace()
pauses your code so you can inspect variablesType
n
+ Enter to go to the next lineType
q
+ Enter to quit the debuggerType any variable name to see its current value
Debugging Tips for Beginners#
Start simple: Test with basic examples first
Use print() liberally: See what your variables contain
Read error messages: They usually tell you exactly what’s wrong
Test small pieces: Don’t debug a huge program all at once
Clean up: Remove print statements when you’re done
Advanced Information: Python pdb Debugger
The Python Debugger (pdb) is a powerful command-line tool for advanced debugging:
Starting pdb:
# Modern way (Python 3.7+) breakpoint() # Simple and clean # Traditional way import pdb pdb.set_trace() # Pauses execution herebreakpoint() vs pdb.set_trace():
breakpoint()
: Built-in function (Python 3.7+), no imports needed, configurable
pdb.set_trace()
: Classic approach, works in all Python versions, requires importBoth do the same thing: pause your code and start the debugger
breakpoint()
is preferred in modern Python codeCommon pdb Commands:
n
(next): Execute next line
s
(step): Step into function calls
c
(continue): Continue execution
l
(list): Show current code
p variable_name
: Print variable value
pp variable_name
: Pretty-print variable
h
(help): Show all commands
q
(quit): Exit debuggerAdvanced Features:
Set breakpoints:
b line_number
orb filename:line_number
Navigate call stack:
u
(up) andd
(down)Execute Python code: Just type it in the pdb prompt
Post-mortem debugging:
python -m pdb script.py
When to use pdb:
Complex logic errors that print() can’t solve
Need to examine variables at multiple points
Working in environments without VS Code (see below)
Debugging remote or production code
Full documentation: Python pdb debugger
VS Code Debugger vs pdb#
Starting in class 3, we will use VS Code… so just as a pointer:
VS Code debugger: Graphical interface with mouse clicks, great for beginners
pdb: Command-line debugger, works everywhere, more advanced
Both let you pause code, inspect variables, and step through line by line