Introduction to Programming with Python

Erick Martins Ratamero
Research Fellow

Hello




@erickratamero

Acknowledgements

This Workshop

  • Building blocks
  • Putting the pieces together
  • Writing complete structures

These Slides




tiny.cc/camdupython

Let's talk about Python

Talking Python

One of Python's most attractive features

Two Modes of Operation

Scripting Mode

  • Code in file
  • Save & load programs
  • More control

Interactive Mode

  • Terminal-based
  • Direct feedback
  • Try out code

Setting Up

Download Thonny from https://thonny.org

Install Thonny

Done!

Getting help

help()

(then Q for quit)

Documentation at docs.python.org/3

Just googling stuff is surprisingly helpful (and what everyone does)

Syntax

Some of it you already know

Python as a calculator

Building Blocks

VARIABLES


Variables store values under a specified name

VARIABLES

Assigning variables in python

name = "Erick"
gender = "male"
height = 1.73 

Types of variables

Variables can store values of different types:

string - a sequence of characters, comprising text

"a", "London", 'X', 'General Assembly'

int - an integer, or whole number

1, 5, 9999, -7

float - a floating point number (using a decimal point)

3.14, 1.68, 1.0

bool - boolean; binary true or false values

True, False

Changing types

'Casting' a variable to another type


int("42")
float("1.69")
str(1.5) 

Exercise


Choose 4 things in this room and create variables of 4 different types based on them

Operators

You can process the values in your variables by operators :

= Assignment: assign a value to a variable
== Comparison: are two variables equal?
!= Comparison: are two variables not equal?

<, >, <=, >=

Less-than, greater-than, less or equal, greater or equal
+, -, *, / Mathematical operators
and, or Logical operators

Specific behaviour depends on data type

>>> start = "Lon"
>>> start
'Lon'
>>> end = "don"
>>> start + end
'London'
>>> start + start + end
'LonLondon'
>>> town = 3 * start + end
>>> town
'LonLonLondon'
>>> 1 + 1
2
>>> cats = 2
>>> cats
2
>>> dogs = 3
>>> cats == dogs
False
>>> cats < dogs
True
>>> dogs + 1
4
>>> dogs
3
>>> dogs = dogs + 1
>>> dogs
4
>>> pets = cats + dogs
>>> pets
6

 Questions? 

Exercise

Create two string variables :

first for your first name and last for your last name.

Can you make your full name by combining first and last?

Bonus:

What happens if we compare first and last with the ‘<' and ‘>' operators?

Why?

(Cheating encouraged)

Extra exercises

https://www.w3resource.com/python-exercises/python-basic-exercises.php

Collections

Collections of Values

Values can also be stored in a collection :

List

Dictionary

Lists

We can store multiple values in a list:

>>> l = [1,3,9,4,884328881]
>>> n = ['first', 'second', 'third', 'fourth']
>>> m = l + n
>>> m
[1, 3, 9, 4, 884328881, 'first', 'second', 'third', 'fourth']

A list is a ordered sequence of items (between [...]) each with their own index:
>>> m[0]
1
>>> m[8]
'fourth' 

Indices

Cool things you can do with lists


>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[1:5]
[1, 2, 3, 4]
>>> l[:5]
[0, 1, 2, 3, 4]
                                
>>> del l[5:]
>>> l
[0, 1, 2, 3, 4] 
>>> l.append(5)
>>> l
[0, 1, 2, 3, 4, 5] 
>>> l.reverse()
>>> l
[5, 4, 3, 2, 1, 0]
>>> 5 in l
True
                                                
                    
https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

Bonus

Lists are sequences, and so are strings
>>> s = "General Assembly"
>>> s[0]
'G'
>>> s[:7]
'General' 

Dictionaries

Dictionaries store key: value pairs associatively.
>>> personX = {'first':'Erick', 'last':'Ratamero', 'twitter':'@erickratamero'}
>>> personX['first']
'Erick'
>>> personX['age'] = 32
>>> personX
{'twitter': '@erickratamero', 'last': 'Ratamero', 'age': 32, 'first': 'Erick'}
>>> for i in personX.items():
...     print(i)
... 
('first', 'Erick')
('last', 'Ratamero')
('twitter', '@erickratamero')

some things you can do with Dictionaries

>>> list(personX.keys())
['twitter', 'last', 'first']
>>> list(personX.values())
['@erickratamero', 'Ratamero', 'Erick']

Questions?

Exercise

Create a dictionary to represent yourself (or someone else) with some attributes (e.g. hometown, favourite film, height)

Bonus:

Add a list of interests to the dictionary. What do you use as key, what do you use as value? (Cheating encouraged)

Extra exercises

https://www.w3resource.com/python-exercises/list/
https://www.w3resource.com/python-exercises/dictionary/

Putting the pieces together

Loops

For Loops

You use loops to repeat a statement.

A for-loop is useful when you know how many times you want to repeat an action (e.g. for every item in a list)

for item in sequence:
                        
    do something with item


Mind the Indentation

For Loops


For Loops

for example:

>>> ages = [18, 21, 16, 12]
>>> for age in ages:
....    print(age)
....
18
21
16
12 

Visualise this code in action

While Loops

A while-loop is useful when you don’t know when you want to stop looping yet.

A while-loop statement checks a condition and loops until the condition is no longer satisfied.

while condition true:
    do something

While loops

While Loops

for example:

>>> gas = 42
>>> while gas > 0:
...     print("Vroom!")
...     gas = gas - 10
... 
Vroom!
Vroom!
Vroom!
Vroom!
Vroom! 
Visualise this code in action

Exercise

Write a program that prints all even numbers between 0 and 50

Write a program that prints the first 10 odd numbers

(Cheating encouraged)

Conditional Statements

Conditional statements

Conditional statements enable you to deal with multiple options.

A part of your code is executed based on the truth value of a condition. You perform conditional checks with: if, elif, else

if condition:
    action
elif other condition: #optional
    other action
else:
    final action
>>> age = 17
>>> if age < 18:
...     print("no drinks for you")
... 
no drinks for you

conditional statements

Conditional statements

>>> ages = [18, 21, 16, 12]
>>> for age in ages:
...     if age >= 18:
...         print("come on in")
...     elif age >= 16:   
            print("not quite yet")
        else:
...         print("get outta here")
... 
come on in
come on in
not quite yet
get outta here
Visualise this code in action

Exercise

Write a program to find all numbers which are divisible by 7 and multiple of 5, between 1500 and 2700

Write a program that prints all the numbers from 0 to 6 except 3 and 6.

(Cheating encouraged)

Extra exercises

https://www.w3resource.com/python-exercises/python-conditional-statements-and-loop-exercises.php

Functions

Functions

Functions perform a collections of tasks, bundled under a specific name

Take input argument(s), execute statement(s), return output

Input and output can be of all different types

>>> name = "Erick Ratamero"
>>> length = len(name)
>>> length
18
>>> type(length)
<type 'int'> 

Built in functions

docs.python.org/3/library/functions.html

Functions

You can define your own functions like this:

def function_name(argument(s)):
    action with argument(s)
>>> def multiply(a, b):
...     return a * b
...
>>> multiply(3,4)
12

>>> def greet(name):
...     print("hello "+ name)
... 
>>> greet('Erick')
>hello Erick
Mind the Indentation

Questions?

Exercise

Write a function with an appropriate name that:

  • takes as input a person (represented as dictionary)
  • prints out information about the person


(Cheating encouraged)

Extra exercises

https://www.w3resource.com/python-exercises/python-functions-exercises.php

Writing complete structures

Modules

A module is a package of code that extends the native functionality of Python.

Use modules to:

  • plot graphs
  • download web pages
  • read and write .csv files
  • anything else someone else has already written

Importing a modules into your script is simple:

>>> import random
>>> random.randint(0,10)
0
>>> random.randint(0,10)
9
>>> random.randint(0,10)
3

When necessary, we will use Thonny to install extra modules

Scripts

You can also write your code conveniently in a file using your favourite text editor

Such a file is a program or script and can look as simple as this:

print("Hello World")  

Save your script as “[a_descriptive_name].py”

Navigate in terminal to the location of your file

Run “python [a_descriptive_name].py” either on command line or inside a program that does that for you (we will use Thonny)

Scripts

# this is a comment, use them!
'''
Comments can also 
span multiple lines
'''
# print() is a very useful function
# mind the quotes
print("Hello World")

Questions?

Exercise

Implement a function in a script, run it to let it print output

(Cheating encouraged)

Useful Resources

google “python” + your problem / question (not a joke)

python.org/doc/; official python documentation, useful to find which functions are available

stackoverflow.com; huge gamified help forum with discussions on all sorts of programming questions, answers are ranked by community

codecademy.com/tracks/python; interactive exercises that teach you coding by doing

wiki.python.org/moin/BeginnersGuide/Programmers; tools, lessons and tutorials