Python Fundamentals for Beginners: Syntax, Data Types, Functions
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 ifIndentationError.Basics of the syntax
- Comments start with
#. - No semicolons at the end of lines.
- Names are case-sensitive:
totalandTotaldiffer. - The style guide PEP 8 recommends
snake_casefor 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.
Check yourself
- How does Python mark the block of code inside an if statement?
- What starts a comment in Python?
- What is pip?
- Why use a virtual environment?
- A Python program must define a main function to run.
- Which naming style does PEP 8 recommend for variables?
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
| Type | Example | Notes |
|---|---|---|
int | 42 | Unlimited size |
float | 3.14 | 64-bit floating point |
str | 'hello' | Text, single or double quotes |
bool | True, False | Capitalised |
NoneType | None | "No value" |
x = 10 x = 'ten' # allowed: dynamic typing print(type(x)) # <class 'str'>
'3' + 3 raises TypeError. Convert explicitly with int('3'), str(3) or float('2.5').Arithmetic
| Expression | Result | Operator |
|---|---|---|
7 / 2 | 3.5 | True division: always a float |
7 // 2 | 3 | Floor division |
7 % 2 | 1 | Remainder |
2 ** 10 | 1024 | Power |
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-strings[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
- What is the result of 7 / 2 in Python 3?
- What does '3' + 3 do?
- For s = 'Python', what is s[1:4]?
- What does s[-1] return?
- You can change one character of a Python string in place with s[0] = 'J'.
- What does 2 ** 3 evaluate to?
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 chainedThe logical operators are the words and, or and not.
Truthiness
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
- Which values does range(3) produce?
- Which of these is falsy in Python?
- Which keyword is used for 'else if' in Python?
- What does enumerate(items) give in a for loop?
- What is the recommended way to test for None?
- What does break do?
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).
| Type | Literal | Ordered | Mutable | Duplicates |
|---|---|---|---|---|
| list | [1, 2, 3] | Yes | Yes | Yes |
| tuple | (1, 2, 3) | Yes | No | Yes |
| dict | {'a': 1} | Insertion order | Yes | Keys unique |
| set | {1, 2, 3} | No | Yes | No |
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} intersectionAn 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
- What is the main difference between a list and a tuple?
- What does nums.sort() return?
- What happens with ages['Eve'] when 'Eve' is not a key?
- What does {} create?
- What is [n * 2 for n in range(3)]?
- A list can be used as a dictionary key.
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 itemsNone.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 importedCheck yourself
- What does a function return when it has no return statement?
- Inside def f(*args), what is args?
- Why is def add(item, items=[]) a bug?
- What does if __name__ == '__main__': check?
- Which statement imports only sqrt from math?
- A Python function can return several values, which arrive as a tuple.
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: 100self 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| Exception | Raised when |
|---|---|
ValueError | Right type, wrong value: int('abc') |
TypeError | Wrong type: 'a' + 1 |
KeyError, IndexError | Missing dict key; list index out of range |
FileNotFoundError | The file does not exist |
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
- What is __init__ in a Python class?
- What does self refer to?
- Which exception does int('abc') raise?
- When does the else block of a try statement run?
- What does opening a file with mode 'w' do to existing content?
- Why use with open(...) as f:?