Python fundamentals

Overview

  • To provide an overview of core Python functionality and programming techniques
  • Refresh your memory of Python syntax
  • This page only covers the basics and is by no means exhaustive.

Basic variable types

  • Ints: integers; e.g. a = 2
  • Floats: floating-point numbers with decimals; e.g. a = 2.0
  • Strings: collection of characters contained in single or double quotes; individual characters can be accessed using an index (starting at 0)
a = 2
b = 2.0
s = "hello"
print(s[0])
h

Use the int, float, and str functions to convert between types

a = 2.00
print(int(a))
2

Mathematical operations

Operation Description Example
+ Addition 5 + 3 = 8
- Substraction 5 - 3 = 2
* Multiplication 5 * 3 = 15
/ Division 5 / 3 = 1.666…
// Floor division (round down to an integer) 5 // 3 = 1
% Modulo (compute remainder) 5 % 3 = 2
** Exponent 5 ** 3 = 125

Boolean operations

Operation Description Example Value
== Is equal? 1 == 2 False
!= Is not equal? 1 != 2 True
< Less than? 1 < 2 True
> Greater than? 1 > 2 False
<= Less than or equal to? 1 <= 2 True
>= Greater than or equal to? 1 >= 2 False

Logical operations

Operation Description Example Value
and Are both true? 1 < 2 and 3 < 2 False
or Is one true? 1 < 2 or 3 < 2 True
not Negate the conditional not(1 < 2) False

Data structures

Type Example Characteristics
List L = [1, 1.0, ‘one’] Mutable, iterable, ordered
Tuple t = (1, 1.0, ‘one’) Immutable, iterable, ordered
Set s = {1, 1.0, ‘one’} Mutable, iterable, unordered, unique
Dictionary d = {‘a’:1, ‘b’:2, ‘c’:3} Mutable, iterable, ordered
  • Mutable: Can be modified
  • Immutable: Cannot be modified
  • Ordered: Elements can be accessed using an index or a key

Data structures continued

  • Use list, tuple, and set functions to convert between types
  • Elements in lists and tuples can be accessed using an integer index (starting at 0)
  • Elements in dictionaries are accessed using keys
# create a list and print the first value
L = [1, 2, 3]
print(L[0])
1
# create a dictionary of gravitational accelerations in m/s2
g = {'Earth': 9.8, 'Mars':3.7, 'Jupiter':25}
print(g['Earth'])
9.8

If statements

  • Used to make a decision in a program
  • Runs an indented block of code if a conditional statement is true
i = 20

if i < 10:
    print("Doing something because i < 10 and the code is indented")
    
print('Printing non-indented code for all values of i')
Printing non-indented code for all values of i

If-else statements

  • Creates two pathways, the choice depends on whether a condition is true or false
i = 20

if i < 10:
    print('Doing something because i < 10')
else:
    print('Doing something else i >= 10')
Doing something else i >= 10

If-else-elif statements

  • Creates multiple pathways, the choice depends on which condition is true
i = 20

if i < 10:
    print('Doing something because i < 10')
elif i > 10:
    print('Doing something else because i > 10')
else:
    print('Doing something different from the other two cases')
Doing something else because i > 10

For loops

  • For repeating code a fixed number of times
for e in collection:
    # run indented code
  • The indented code is run until e has taken on every value in collection (which is an iterable object like a list or tuple)
# print the numbers from 0 to 10
for i in range(11):
    print(i, end=" ")
0 1 2 3 4 5 6 7 8 9 10 
# capitalise words in a list
L = ['red', 'blue', 'green']
for c in L:
    print(c.capitalize(), end=", ")
Red, Blue, Green, 

While loops

  • For repeating code until a condition becomes false
while condition:
    # run indented code
  • While loops are useful when you don’t know how many times to repeat code
  • Beware of infinite loops!
# compute the square numbers that are smaller than 450
n = 1

while n**2 < 450:
    print(n**2, end=", ")
    n += 1
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 

Break and continue

  • break is used to terminate a loop
  • continue is used to skip an iteration in a loop
for i in range(10):
    print(i, end = " ")
0 1 2 3 4 5 6 7 8 9 
for i in range(10):
    if i == 4:
        break
    print(i, end = " ")
0 1 2 3 
for i in range(10):
    if i == 4:
        continue
    print(i, end = " ")
0 1 2 3 5 6 7 8 9 

Functions

  • Functions are mini-programs based on a collection of code that has been given a name
  • Functions are defined using the def keyword
  • Function inputs are called arguments
  • The return keyword is used to output data from a function
# add two numbers a and b together
def my_sum(a, b):
    c = a + b
    return c

c = my_sum(3, 6)
print(c)
9

Scripts, modules, and packages

  • Modules are Python files (.py) that contain variables, functions, etc
  • Packages are folders (directories) that contain modules
  • Scripts are top-level Python files that import packages and modules
  • Scripts are run (e.g. in Spyder) not modules/packages

A typical file structure might look like this:

emat30008/
|--- main.py
|--- circle.py

where main.py is a script that imports the module circle.py

Importing modules and packages

  • The import keyword is used to load Python code from modules and packages
  • There are many ways to do this; see EMAT10007 notes for more details
# import the math package
import math

# print the variable pi from the math package
print(math.pi)
3.141592653589793

Summary

These slides covered core Python functionality

  • Operations, data types, control flow, loops, functions, modules and packages

Topics not covered but which you are expected to know:

  • Variable scope (local, global), keyword and default arguments, classes, file input and output