Python20Revision.pptx

Revision Round Two

Python Programming

Major Topics

Variables

Input and Output

Functions

Conditionals – if/elif/else

Iterations – while and for loops

Lists

Testing

Professional Practices

Python Variables

Every variable in Python is created when it’s assigned (‘=‘) a value

name = “Bob”

Variable name rules

No spaces

No keywords (words that already have special meaning)

Must start with a letter

camelCase or underscores_for_spaces

3

Getting values in Python

Built-in function:

variableName = input(prompt)

Displays prompt and then gets a value from the keyboard. This value will be stored in variableName as a string

Typecast to an int or float if needed

num_name = int(input(prompt))

Math

Basic math can be done with numerical types (int or float)

Symbols

Addition is ‘+’

Subtraction is ‘-’

Division is ‘/’

Multiplication is ‘*’

Because ‘X’ already has a meaning… it is the letter ‘X’

Modulo is ‘%’

Display variables

print

Use ‘concatenation’ to join things together

In planning and Python we use ‘+’ to indicate this:

display “The sum of “ + num1 + “ and “ + num2 “ is “ + num3

We MUST explicitly insert spaces

In flowgorithm use the ampersand (&)

Python allows us to print a collection of things, separated by commas. It will insert spaces automatically:

print(“The sum of”, num1, “and”, num2, “is”, num3)

functions

Keyword ‘def’

Inputs (if any) in brackets after name, separated by commas

Have empty brackets if there are none

Return at end (if needed)

def getValue(prompt)

num = int(input(prompt))

return num

Calling functions

If it returns a value

We assign the returned value to a variable using the ‘=‘ statement:

result = getResult(num1, num2)

Otherwise:

Just call it by name:

displayResults(score)

Decisions

Basic keyword

if

Decision block structure

if <condition> :

<code goes here>

Note header ends with ‘:’ as well as indentation

Similar basic structure to function block

Compound decisions

Can combine decisions with boolean keywords:

and, or, not

E.g. if temp >35 and temp < 40

Each side MUST be a full decision

temp > 35 and < 40 is not possible

Path Condition Result
Porridge is too hot Temperature > 40° Complain “It’s too hot”
Porridge is too cold Temperature < 35° Complain “It’s too cold”
Porridge is just right Temperature > 35° and < 40° Eat someone else’s porridge

For Example…

if num > 0 and num <= 10:

print(“Valid Number”)

if num <= 0 or num > 10:

print(“Invalid Number”)

More complex decisions

New Keyword needed:

else

For the ‘false’ path

And more complex again…

New keyword needed:

elif

for each branch other than the first and last

Examples

if num > 0:

print(“You Entered ” & num)

else:

print(“Invalid Number”)

or

if num <= :

print(“Invalid Number”)

else:

print(“You Entered ” & num)

Examples

if score < 50:

print(“Fail”)

elif score <65:

print(“Pass”)

elif score <75:

print(“Credit”)

elif score <85:

print(“Distinction”)

else:

print(“High Distinction”)

Types of Loops

Two ‘categories’ of iterations

Definite (we KNOW how many times)

Indefinite (no way of knowing)

‘while’ loops for indefinite

‘for’ loops for definite

Can use while here too, but for makes it easier

Definite also applies if the computer knows at runtime, even though we cannot predict it at writing time…

16

While loops

Also know as a ‘pre-test’ loop

Tests the loop condition BEFORE it runs

May never run if the condition is false to start with

Like decisions, an iteration ‘block’ has 2 parts

Header

while <condition> :

Body

Code within the loop, must be indented

While loops

Let’s implement this in Python:

get value from user

while value is less than zero:

print an error

display prompt

get value

display value

For loops

For loop header is very different

Header

for variable in collection:

collection can be either:

A range

range(10)

A list

Names

More in CP1404…

For loops

On the first iteration variable will have the value of the first thing in the collection

On each iteration the value of variable changes to be the next value in the collection

range(10) is [0,1,2,3,4,5,6,7,8,9]

Up to, but not including, the stop value!

for count in range(10)

print(count)

Will display the numbers

0,1,2,3,4,5,6,7,8 and 9

on separate lines

Arrays (Lists in Python)

Like any variable we create a list by giving it a value:

listName = []

Creates an empty list

Can give it values, separated by commas, instead of making it empty

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

Creates a list of five integers

1 to 5

Iterating over a list

For loops were designed to access lists, so they are our preferred method here

We know the number of iterations (size of the list)

Builtin function ‘len()’ can tell us this at runtime (avoids magic numbers)

‘For’ loop header can use this value

22

Examples

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

for i in range(len(myList))

print(myList[i])

Iterating over a list

But there is an even simpler way

We can use the list itself as the container to loop over:

for num in myList:

print(num)

Will print each value in the list 

24

Testing Code

Why?

We (should) have already checked our design, so we know it works

So why do we need to make sure the code works?

We need to check that we implemented our solution correctly

Testing Code

How?

Try running it, see what happens 

If and when error messages appear READ THEM!

Right now they may seem unhelpful, but we will become familiar with them over time

What are we testing?

That it runs

Syntax errors

That it gives the correct results

Logic errors

Are there any user inputs which break the program

Runtime errors

27

Testing functions

Each function should be tested individually

Called ‘unit testing’

Create a simple ‘main’ which tests each function with sample input

28

Testing Decisions

Each decision should be tested individually

Put it in a function by itself, and test it with fixed inputs (or user input)

Test ALL ‘boundary conditions’

E.g.

If temp <= 35 Then

We need to test this with temp = 34, 35 and 36 to ensure it behaves as we expect

29

Testing Loops

Each loop should be tested individually

Put it in a function by itself, and test it with fixed inputs

Test the number of runs

E.g.

while count <= 10

Does this exit when count is 9, or 10, or 11?

Does it behave as we expect?

30

Professional Practices

Commenting standards

Position (above/end of line)

On functions

Style

Length

Position is a style choice, some people prefer to comment on the line above, some comment at the end of the line

Functions should have a comment on the line above, indicating what the function is for

Style should be clear and concise

Length should be as short as possible without being unclear

31

Naming Standards

Valid variable names != good variable names

Naming conventions

Capsfirst – used for Class names

We don’t use these in CP1401, but you will see them in the future.

ALLCAPS – reserved for unchanging (constant) values

Constants – Local and Global

In Python we cannot ‘define’ constants

Use ALLCAPS to indicate constancy

IF a value is only used in one function it should be defined inside that function

If it is used in several places it can be defined at the top of our code, outside of ALL functions (including main) as a ‘global ‘constant’

Global constants allow me to avoid passing around data which is used in several places

Why is this allowed when global variables are not?