Python Basics

  • Python Syntax

  • Variables and data types

  • Storing lots of data in memory: Lists and Tuples

  • Whitespace

  • Functions

  • Comments in code

What does python syntax look like?

salary = 100000
tax_rate = 0.2
salary_after_tax = salary * (1-tax_rate)
print(salary_after_tax) 
80000.0

What parts of Python did we use in that code?

print('Hello world')   
Hello world

Variables and data types in python

  • Variables hold data.

  • For example, this might be a number (e.g. an integer) or a text string.

  • Your computer program uses the data in its operations.

Let’s create a really simple variable call simple_sum as the sum of two integers.

simple_sum = 1 + 1
print(simple_sum) 
2
  • You can conduct mathematical operations on variables

Operator

Name

Description

a + b

Addition

Sum of a and b

a - b

Subtraction

Difference of a and b

a * b

Multiplication

Product of a and b

a / b

True division

Quotient of a and b

a // b

Floor division

Quotient of a and b, removing fractional parts

a % b

Modulus

Integer remainder after division of a by b

a ** b

Exponentiation

a raised to the power of b

-a

Negation

The negative of a

Example:

  • the variable z is product of variable x raised to the power of y

x = 10
y = 2
z = x ** y
print(z)
100

Example:

  • the variable foo is the negation of variable bar

bar = 10
foo = -bar
print(foo)
-10

Variables Names

  • Variables names can only contain letters, numbers, and underscores ( _ ).

  • Underscores are used instead of spaces.

  • For example, use student_name instead of student name.

  • If you include a space then you will get an SyntaxError!

lecturer name = 'tom'
  File "<ipython-input-6-bb25698b12f8>", line 1
    lecturer name = 'tom'
             ^
SyntaxError: invalid syntax
  • Each variable has a data type.

  • Python is dynamically typed.

  • This means that Python does all of the work for you!

foo = 1000
bar = 'hello everyone'
print(type(foo))
print(type(bar))
<class 'int'>
<class 'str'>
foo = True
bar = False
spam = 3.142
eggs = 10000000

print(type(foo))
print(type(bar))
print(type(spam))
print(type(eggs))
<class 'bool'>
<class 'bool'>
<class 'float'>
<class 'int'>

Introduction to Lists and Tuples

  • A Python List is a simple and flexible way to store variables and any type of data

foo = [1, 2, 3, 4, 5]
print(foo) 
[1, 2, 3, 4, 5]
  • The elements stored within a List have a numbered index

  • Indexes start from zero (don’t forget)

foo = [1, 2, 3, 4, 5]
print(foo[0])
print(foo[1])

foo[4] = 999
print(foo)
1
2
[1, 2, 3, 4, 999]
  • A List is very flexible and can hold different types of variable

bar = ['spam', 5, 82.96, True]
bar[1] = 'eggs'
print(bar) 
['spam', 'eggs', 82.96, True]
  • A List has a length

length_of_list = len(bar)
print(length_of_list)  
4

Inserting and removing items

New list items:

  • can be appended to the end of a list a List

  • or inserted at a specified index

Existing list items:

  • Can be removed from a specified index

  • or by value

foo = []
foo.append('spam')
foo.append('eggs')
print(foo)

#foo.insert(1, 'bar')
#print(foo)

#del foo[2] # Remove a specific index 
#print(foo)

#foo.remove('spam') #Remove a specific value
#print(foo)
['spam', 'eggs']
  • A Tuple is similar to a List with one key difference

  • A List is mutable where as a Tuple is immutable

foo = [1, 2, 3, 4, 5]
bar = (1, 2, 3, 4, 5)

print(foo)
print(bar)
[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)
foo[1] = 999 #list
bar[1] = 999 #tuple
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-0887368b13a8> in <module>
      1 foo[1] = 999 #list
----> 2 bar[1] = 999 #tuple

TypeError: 'tuple' object does not support item assignment

Functions

  • We have already encountered a function: print()

  • print() is one of Python’s built in functions

  • Python has lots of them!

  • If you are not sure how they work you can use the help() function!

help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

Importing functions from Python modules

  • Functions are stored within modules

  • Use the import statement to access the modules you need

  • Let’s generate a random integer between 1 and 100.

  • We need to a function from the random module

import random as rnd

u = rnd.randint(1, 100)
print(f'I generated a random integer {u}')
I generated a random integer 31
  • We can also import specific functions from modules

from random import randint, gauss

u1 = randint(1, 100)
u2 = gauss(0, 1)
print(f'I sampled from a random int {u1} and a normally distributed value {u2}')
I sampled from a random int 80 and a normally distributed value 0.25118187063605696

Custom Functions

  • You can also code your own bespoke functions

  • A function is a reusable block of code that has a single responsibility

  • That means you function should do one thing only

Motivation

  • You have been asked to convert a dataset of degrees celsius figures to fahrenheit

deg_celsius = 20
fahrenheit = 9.0/5.0 * deg_celsius + 32
print(fahrenheit)

deg_celsius = 10
fahrenheit = 9.0/5.0 * deg_celsius + 32
print(fahrenheit) 
68.0
50.0
  • A reusable function would come in very handy here!

def convert_celsius_to_fahrenheit(deg_celsius):
    deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
    print(f'{deg_celsius} degrees celsius is equivalent to {deg_fahrenheit} degrees fahrenheit')
convert_celsius_to_fahrenheit(20)
convert_celsius_to_fahrenheit(10) 
20 degrees celsius is equivalent to 68.0 degrees fahrenheit
10 degrees celsius is equivalent to 50.0 degrees fahrenheit
  • An alterantive way to write the same function

  • Instead of using print() we can return the result

  • And store the result in a new variable result_fahrenheit

def convert_celsius_to_fahrenheit(deg_celsius):
    deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
    return deg_fahrenheit
result_fahrenheit = convert_celsius_to_fahrenheit(22)
print(result_fahrenheit)
71.6
  • Watch out for whitespace rules!

  • if you use : then you must indent (use tab or 4 spaces) on the next line

def convert_celsius_to_fahrenheit(deg_celsius):
deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
return deg_fahrenheit 
  File "<ipython-input-24-33c89eb1548a>", line 2
    deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
    ^
IndentationError: expected an indented block
  • If a func returns a value you can pass it to another func

def add(num1, num2):
    return num1 + num2

def square(num):
    return num ** 2  
result = square(add(1, 1))
print(result)  
4

Comments in code

def convert_celsius_to_fahrenheit(deg_celsius):
    '''
    Converts d egrees celcius to degrees fahrenheit
    Returns a float representing the temperature in degrees fahrenheit.
    
    Parameters:
    -----------
    deg_celsius: float
        a float temperature in degress celsius e.g. 18.5
    '''
    deg_fahrenheit = 9.0/5.0 * deg_celsius + 32
    return deg_fahrenheit
help(convert_celsius_to_fahrenheit)
Help on function convert_celsius_to_fahrenheit in module __main__:

convert_celsius_to_fahrenheit(deg_celsius)
    Converts d egrees celcius to degrees fahrenheit
    Returns a float representing the temperature in degrees fahrenheit.
    
    Parameters:
    -----------
    deg_celsius: float
        a float temperature in degress celsius e.g. 18.5
  • Using # is another way to add comments to code

  • Useful to clarify “complex” code and aid your memory.

  • Won’t be picked up by help()

from math import pi

def area_of_circle(radius):
    #  pi x squared(radius)
    area = pi * radius ** 2 
    return area 
help(area_of_circle)
Help on function area_of_circle in module __main__:

area_of_circle(radius)

In Python Functions can return multiple values

def list_info(data):
    '''
    Returns Sum, Length and Mean of list @data 
    
    Parameters:
    ----------
    data: list
        a list containing numeric data
    '''
    list_sum = sum(data)
    list_length = len(data)
    list_mean = list_sum / list_length
    
    return list_sum, list_length, list_mean

data = [1, 2, 3, 4, 5]

results = list_info(data)
print(f"The variable 'results': {results} has type {type(results)}")

data_sum, data_length, data_mean = list_info(data)
print(f'Seperate variables: sum {data_sum}, length {data_length}, mean {data_mean}')
The variable 'results': (15, 5, 3.0) has type <class 'tuple'>
Seperate variables: sum 15, length 5, mean 3.0

End