Introduction to Programming

(In Python 3)

 

Timothy Clark

What is Python?

  • Python is a dynamically typed, general-purpose, interpreted programming language
  • Named after the "Monty Python" comedy group
  • Python is becoming increasingly popular, because its ease of use and modularity
  • We're using Python 3

What can I make with Python?

  • Simple programs (quickly)
  • Portable programs
  • Websites/Web Servers
  • GUI Apps
  • Network Programming
  • AI & Machine Learning

Installation

Installing Python & PIP

# Ubuntu Linux
sudo apt install -y python3

# Mac - open a terminal!

Running .py files

# Windows
py main.py

# Mac/Linux
python3 main.py
def add(a, b):
	print("{} + {} = {}".format(a, b, a + b))

print("Hello World!")

add(2, 6)

Not working? Try repl.it/languages/python3

The Basics

Hello Python!

# Your first program!

print("Hello World!")

Comments

Comments tell others programmers (and you) what a line of code does

 

They tell the interpreter to ignore the line(s)

# This is a single line comment
# This is another single line comment

# print("hello!")


'''
This
comment
is a
multi-line comment
'''

Maths!

Computers are very good at Mathematics!

 

How fast can you calculate:

3 * 4

 

What about? 3245 * 4657

a = 4
b = 3

a + b # 7

a - b # 1

a * b # 12
a ** b # 64

13 / 2 # 6.5
13 // 2 # 6
16 % b # 1

Data Types

Python can store a few primitive types of data:

  • Integers (unbounded)
  • Floats
  • Strings
  • Booleans
# Integer (int)
34
786
345

# Float (float)
3.14159
2.5

# String (str)
"Hello"
'Python 2 is dead'
"a"


# Booleans (bool)
True
False

True and False
True or False
not True


# Declaration
my_variable = 42

Variables

You can store values for later use in variables

# Integer (int)
34
786
345

# Float (float)
3.14159
2.5

# String (str)
"Hello"
'Python 2 is dead'
"a"


# Booleans (bool)
True
False

True and False
True or False
not True

Logic and Loops

Conditionals

Conditionals (or "if" statements) evaluates a boolean statement, and performs different actions dependent on the result

# if <BOOLEAN>:
# 	do something

if True:
  pass

if x > y:
  print("x is bigger")
elif x < 0:
  print("x and y are negative")
else:
  print("something else")
  

Loops

"for" and "while" statements allow you to repeat a statement multiple times

 

This allows you to write "DRY" code

for i in range(10):
  print(i)
  
j = 0
while j < 10:
  print(j)
  j += 1

Functions

Functions

Functions are like putting snippets of code in a box, and dealing with it more abstractly.

 

They can receive parameters when called/invoked, and they can return values.

def do_something():
  print("I did something")
  print("I did another thing!")

def do_nothing():
  pass

def add(a, b):
  return a + b

def add_and_multiply_by_20(blah, bleh):
  x = add(blah, bleh)
  return x * 20


do_something()
do_nothing()
add(3, 4)
add_and_multiply_by_20(43, 26)

Lists

Lists

Lists (or arrays, as they are called in most programming languages) are data structures that can store any type of data in an ordered, indexed structure

trees = ["Maple", "Birch", "Oak", "Beech"]

trees[0] # "Maple"
trees[2] # "Oak"

print(trees)
trees.append("Willow")
print(trees)

nums = range(1, 10)

nums[3] # 4



stuff = ["blah", "blah", 34, 3.14]

stuff[1:3]
stuff[:3]

print(stuff)
stuff[1] = "bleh"
print(stuff)

del stuff[0]
stuff.remove(34) 

print(stuff)

Other Data Structures

Tuples are like lists, but immutable, meaning you can't modify their contents

 

Dictionaries are a key-value store that you can use to associate a set of keys to some data

fruits = ("orange", "apple", "banana")

fruits[1] = "cherry" # This won't work

for fruit in fruits:
  print(fruit)

o, a, b = fruits
print(a)
  
  
  
my_dict = {
  "brand": "Apple",
  "model": "iPhone",
  "year": 2007
}

my_dict["model"] # "iPhone"

for key in my_dict:
  print(key, my_dict[key])

Importing and Extensibility

Import

Python allows reuse of code by importing functions from modules, simply just another file.

# main.py

import stuff

stuff.say_hello("World")
stuff.say_hello("Everyone")

main.py

stuff.py

/

# stuff.py

def say_hello(thing):
  print("Hello", thing)
# main.py (alternative)

from stuff import say_hello
# from stuff import * (imports everything)

say_hello("World")
say_hello("Everyone")

Random

import random

things = ("cherry", "bell", "orange", "pear") # Tuple

while True:
    spin = [things[random.randint(0, 3)] for x in range(3)]
    print(spin)

    if spin[0] == spin[1] == spin[2]:
        print("You Win!")
    else:
        print("You lose.")

    if input("Spin again?"):
        break
	print()

Object-Oriented Programming

Person

How can we represent a Person?

 

People have names, ages and birthdays!

class Person:
  def __init__(self, name):
    self.name = name
    self.age = 0
    
  def birthday(self):
    self.age += 1
      
      
me = Person("Tim")
you = Person("Derek")

print(me.name, me.age)
print(you.name, you.age)

for i in range(21):
	me.birthday()

for i in range(30):
	you.birthday()
    
you.name = "Steve"

print(me.name, me.age)
print(you.name, you.age)

__str__

class Person:
  def __init__(self, name):
    self.name = name
    self.age = 0
    
  def birthday(self):
    self.age += 1
  
  def __str__(self):
    return "Hi, my name is {}, and I'm {} years old".format(self.name, self.age)
      
      
p1 = Person("Derek")
p2 = Person("Steve")

for i in range(11): p1.birthday()
for i in range(37): p2.birthday()
    
print(p1)
print(p2)

Inheritance

class Person:
  def __init__(self, name):
    self.name = name
    self.age = 0
    
  def birthday(self):
    self.age += 1
  
  def __str__(self):
    return "Hi, my name is {}, and I'm {} years old".format(self.name, self.age)
    
    
class Student(Person):
  def __init__(self, name, subject, year):
    super().__init__(name)
    self.degree = subject
    self.graduation = year
        
  def graduate(self, grade):
    print("Congratulations {}! You graduated {} with a {} in {}".format(self.name, self.degree, grade, self.graduation))
  
  
s = Student("Sarah", "Computer Science", 1999)
for i in range(19): s.birthday()
s.graduate("1.1")

Reading

docs.python.org

w3schools.com/python

tutorialspoint.com/python3

Questions?