Brainbotox · Lessons · Exams

Python Fundamentals for Beginners: Syntax, Data Types, Functions

by lazizanie · Programming · Python · English

Learn Python from zero: running code, variables and types, control flow, lists, dicts and sets, functions and modules, classes, exceptions and files, with quizzes.

Study this lesson with its quizzes on Brainbotox →

What is Python? Running code, indentation and pip

Python is a high-level, interpreted, dynamically typed language known for readable syntax, used for web back ends, automation, data analysis and machine learning.

Running Python

python3 hello.py      # run a file
python3               # start the interactive prompt (REPL)
# hello.py
name = 'Ada'
print('Hello,', name)

There is no compile step to run by hand and no main function is required: the file is executed from top to bottom.

Indentation is syntax

if name == 'Ada':
    print('Welcome back')     # inside the if: indented 4 spaces
    print('Ada')
print('Done')                 # outside the if
Python uses indentation, not braces, to mark blocks. A line ending with a colon opens a block, and all its lines share the same indentation. Wrong indentation raises IndentationError.

Basics of the syntax

  • Comments start with #.
  • No semicolons at the end of lines.
  • Names are case-sensitive: total and Total differ.
  • The style guide PEP 8 recommends snake_case for variables and functions.

Packages and virtual environments

python3 -m venv .venv            # create an isolated environment
source .venv/bin/activate        # activate it (Windows: .venv\Scripts\activate)
pip install requests             # install a package from PyPI

pip installs third-party packages. A virtual environment keeps each project's packages separate, so two projects can use different versions.

Use Python 3. Python 2 reached end of life in 2020.

Check yourself

  1. How does Python mark the block of code inside an if statement?
  2. What starts a comment in Python?
  3. What is pip?
  4. Why use a virtual environment?
  5. A Python program must define a main function to run.
  6. Which naming style does PEP 8 recommend for variables?

Take the quiz on Brainbotox

Python variables, data types, numbers and strings

A Python variable is a name bound to an object. You never declare its type: the type belongs to the object, and a name can later be bound to an object of another type.

The basic types

TypeExampleNotes
int42Unlimited size
float3.1464-bit floating point
str'hello'Text, single or double quotes
boolTrue, FalseCapitalised
NoneTypeNone"No value"
x = 10
x = 'ten'          # allowed: dynamic typing
print(type(x))     # <class 'str'>
Python is dynamically but strongly typed: '3' + 3 raises TypeError. Convert explicitly with int('3'), str(3) or float('2.5').

Arithmetic

ExpressionResultOperator
7 / 23.5True division: always a float
7 // 23Floor division
7 % 21Remainder
2 ** 101024Power

Strings

s = 'Python'
s[0]        # 'P'      first character
s[-1]       # 'n'      last character
s[1:4]      # 'yth'    slice: start included, end excluded
len(s)      # 6
s.upper()   # 'PYTHON' a new string
name, age = 'Ada', 36
print(f'{name} is {age} years old')    # f-string
Strings are immutable. s[0] = 'J' raises TypeError, and methods such as upper() and replace() return a new string.
input() always returns a string. Convert it before doing arithmetic: age = int(input('Age: ')).

Check yourself

  1. What is the result of 7 / 2 in Python 3?
  2. What does '3' + 3 do?
  3. For s = 'Python', what is s[1:4]?
  4. What does s[-1] return?
  5. You can change one character of a Python string in place with s[0] = 'J'.
  6. What does 2 ** 3 evaluate to?

Take the quiz on Brainbotox

Python control flow: if, for, while and truthiness

Python decides with if, elif and else, and repeats with for, which iterates over a sequence, and while, which repeats as long as a condition holds.

Conditions

if score >= 90:
    grade = 'A'
elif score >= 70:
    grade = 'B'
else:
    grade = 'C'
label = 'pass' if score >= 50 else 'fail'     # conditional expression
if 0 < score < 100: ...                         # comparisons can be chained

The logical operators are the words and, or and not.

Truthiness

These values count as false: False, None, 0, 0.0, the empty string '', and empty collections [], {}, (), set(). Everything else is true.
items = []
if not items:
    print('The list is empty')

for loops

for i in range(3):          # 0, 1, 2
    print(i)
for i in range(2, 10, 2):   # 2, 4, 6, 8  (start, stop excluded, step)
    print(i)
for name in ['Ada', 'Bob']:
    print(name)
for index, name in enumerate(['Ada', 'Bob']):
    print(index, name)

while, break and continue

n = 10
while n > 0:
    n -= 3
    if n == 4:
        continue     # skip to the next iteration
    if n < 0:
        break        # leave the loop

== and is

== compares values. is tests whether two names refer to the very same object. Use is only for None: if result is None:.

Check yourself

  1. Which values does range(3) produce?
  2. Which of these is falsy in Python?
  3. Which keyword is used for 'else if' in Python?
  4. What does enumerate(items) give in a for loop?
  5. What is the recommended way to test for None?
  6. What does break do?

Take the quiz on Brainbotox

Python lists, tuples, dictionaries and sets

Python has four built-in collections: the list (ordered, changeable), the tuple (ordered, fixed), the dictionary (key to value) and the set (unique items).

TypeLiteralOrderedMutableDuplicates
list[1, 2, 3]YesYesYes
tuple(1, 2, 3)YesNoYes
dict{'a': 1}Insertion orderYesKeys unique
set{1, 2, 3}NoYesNo

Lists

nums = [3, 1, 2]
nums.append(4)          # [3, 1, 2, 4]
nums.pop()              # removes and returns 4
nums.sort()             # sorts in place, returns None
ordered = sorted(nums)  # returns a new sorted list
nums[0], nums[-1], nums[1:]
2 in nums               # True
len(nums)               # 3
nums = nums.sort() sets nums to None. Use nums.sort() alone, or nums = sorted(nums).

Tuples

point = (3, 4)
x, y = point            # unpacking
a, b = b, a             # swap two variables

Dictionaries

ages = {'Ada': 36}
ages['Bob'] = 41
ages['Eve']             # KeyError: missing key
ages.get('Eve', 0)      # 0: safe access with a default
for name, age in ages.items():
    print(name, age)

Keys must be immutable (hashable): strings, numbers, tuples. A list cannot be a key.

Sets

tags = {'a', 'b', 'a'}       # {'a', 'b'}
tags.add('c')
unique = set([1, 1, 2])      # {1, 2}
{1, 2} & {2, 3}              # {2}  intersection

An empty set is set(), because {} is an empty dictionary.

List comprehensions

squares = [n * n for n in range(5)]                 # [0, 1, 4, 9, 16]
evens = [n for n in range(10) if n % 2 == 0]

Check yourself

  1. What is the main difference between a list and a tuple?
  2. What does nums.sort() return?
  3. What happens with ages['Eve'] when 'Eve' is not a key?
  4. What does {} create?
  5. What is [n * 2 for n in range(3)]?
  6. A list can be used as a dictionary key.

Take the quiz on Brainbotox

Python functions, arguments, scope and modules

A function is defined with def, receives arguments by position or by name, and returns a value with return. Without a return statement it returns None.

Defining and calling

def greet(name, greeting='Hello'):
    '''Return a greeting for name.'''        # docstring
    return f'{greeting}, {name}'
greet('Ada')                         # 'Hello, Ada'
greet('Bob', greeting='Hi')          # keyword argument
def min_max(values):
    return min(values), max(values)  # returns a tuple
low, high = min_max([3, 1, 2])

*args and **kwargs

def total(*args):            # extra positional arguments, as a tuple
    return sum(args)
total(1, 2, 3)
def show(**kwargs):          # extra keyword arguments, as a dict
    for key, value in kwargs.items():
        print(key, value)
show(name='Ada', age=36)

The mutable default argument trap

def add(item, items=[]):     # the list is created ONCE, at definition
    items.append(item)
    return items
add(1)    # [1]
add(2)    # [1, 2]  surprise
def add(item, items=None):   # correct
    if items is None:
        items = []
    items.append(item)
    return items
Default values are evaluated once, when the function is defined. Never use a list or dict as a default; use None.

Scope

A variable assigned inside a function is local. A function can read a global variable, but to assign to it you need the global keyword, which is best avoided: pass values in and return results.

Lambda

people.sort(key=lambda p: p['age'])     # a small anonymous function

Modules

import math
from random import randint
import datetime as dt
print(math.sqrt(16))

Any .py file is a module that others can import.

if __name__ == '__main__':
    main()     # runs only when the file is executed directly, not when imported

Check yourself

  1. What does a function return when it has no return statement?
  2. Inside def f(*args), what is args?
  3. Why is def add(item, items=[]) a bug?
  4. What does if __name__ == '__main__': check?
  5. Which statement imports only sqrt from math?
  6. A Python function can return several values, which arrive as a tuple.

Take the quiz on Brainbotox

Python classes, exceptions and files

A class bundles data and behaviour, exceptions signal errors that you handle with try and except, and files are opened safely with the with statement.

Classes

class BankAccount:
    def __init__(self, owner, balance=0):     # the initialiser
        self.owner = owner
        self.balance = balance
    def deposit(self, amount):
        if amount <= 0:
            raise ValueError('Amount must be positive')
        self.balance += amount
    def __str__(self):
        return f'{self.owner}: {self.balance}'
acc = BankAccount('Ada')
acc.deposit(100)
print(acc)              # Ada: 100
self is the instance the method is called on. It must be the first parameter of every instance method, and Python passes it automatically.

Inheritance

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return '...'
class Dog(Animal):
    def speak(self):                 # overrides the parent method
        return 'Woof'

Call the parent version with super(), for example super().__init__(name).

Exceptions

try:
    n = int(text)
    result = 10 / n
except ValueError:
    print('Not a number')
except ZeroDivisionError as e:
    print('Error:', e)
else:
    print(result)          # runs if no exception occurred
finally:
    print('Done')          # always runs
ExceptionRaised when
ValueErrorRight type, wrong value: int('abc')
TypeErrorWrong type: 'a' + 1
KeyError, IndexErrorMissing dict key; list index out of range
FileNotFoundErrorThe file does not exist
Catch specific exceptions. A bare except: hides every error, including typos in your own code.

Files

with open('notes.txt', 'w', encoding='utf-8') as f:
    f.write('first line\n')
with open('notes.txt', encoding='utf-8') as f:
    for line in f:
        print(line.strip())

with closes the file automatically, even if an error occurs. Mode 'r' reads (the default), 'w' overwrites, 'a' appends.

Check yourself

  1. What is __init__ in a Python class?
  2. What does self refer to?
  3. Which exception does int('abc') raise?
  4. When does the else block of a try statement run?
  5. What does opening a file with mode 'w' do to existing content?
  6. Why use with open(...) as f:?

Take the quiz on Brainbotox