Lecture 2 – Lists, conditionals and loops

Recap on Variables

  • A variable
    • named cell of memory storing a single value
    • Assigned a value using the equals symbol
    • Can be given any name you like
      • Except no spaces and cannot start with a number
  • Variables can hold:
    • a string (i.e. text): message = "Hello, World!"
    • an integer: x = 5
    • floating-point: y = 5.3741
  • You can perform basic operations on variables
    • z = x + y
  • You can call functions on your variables length = len(message)

Overview

  • Lists

    • Very useful structure for storing data
    • Can store multiple data types together
    • Appending,slicing, sorting, printing
  • Conditionals

    • Can apply logic to data
    • Boolean logic (True/False)
    • issues with converting plain language into logical statement
  • Loops

    • for and while can be used for all sorts of applications
    • for generally used for working with lists

LISTS

A list of numbers: 67 78 94 45 55


In [1]:
exam_scores = [67,78,94,45,55,66]
print("scores: " ,exam_scores)


scores:  [67, 78, 94, 45, 55, 66]

Lists can be accessed by numerical position (aka index) value: 67 78 94 45 55 position: 0 1 2 3 5

You can also take "slices" using:


In [2]:
exam_scores = [67,78,94,45,55]

print("score 2: " ,exam_scores[1])
print("score 3: " ,exam_scores[2])
print("score 2 & 3: " ,exam_scores[1:3])


score 2:  78
score 3:  94
score 2 & 3:  [78, 94]

Slicing can also be used with strings in the same way. Just imagine that each character in the string is the same as a list element

Changing a list value

Changing a value in a specific position iss similar to defining a variable


In [3]:
exam_scores = [67,78,94,45,55]
exam_scores[2] = 90
print("score: " ,exam_scores[2])


score:  90

Print all values in a list


In [4]:
exam_scores = [67,78,94,45,55]
print ("Here are the scores:",exam_scores)


Here are the scores: [67, 78, 94, 45, 55]

Note: If you want to print all elements individually (and do something else with them), you should loop through them – later in lecture...

Adding to lists

You can add values to the end of a list using the append() method Append is a method so it must be called on a list


In [2]:
exam_scores = [67,78,94,45,55]
exam_scores.append(32) #add a variable to this list
print ("Here are the scores:",exam_scores)


Here are the scores: [67, 78, 94, 45, 55, 32]

Other useful list methods


In [6]:
# extend(list) - appends another list

exam_scores = [67,78,94,45,55]
exam_scores2 = [54,73,65]
exam_scores.extend(exam_scores2)
print (exam_scores)


[67, 78, 94, 45, 55, 54, 73, 65]

In [7]:
# insert(index,item)-insert an item at a given index

exam_scores = [67,78,94,45,55]
exam_scores.insert(4,90)
print (exam_scores)


[67, 78, 94, 45, 90, 55]

In [8]:
exam_scores = [67,78,94,45,55]
exam_scores.pop(2)
print (exam_scores)


[67, 78, 45, 55]

Sometimes we may want to capture the popped value.


In [9]:
exam_scores = [67,78,94,45,55]
popped_value = exam_scores.pop(2)
print (exam_scores)
print("Popped value=", popped_value)


[67, 78, 45, 55]
Popped value= 94

In [10]:
exam_scores = [67,78,94,45,55]
exam_scores.reverse()
print (exam_scores)


[55, 45, 94, 78, 67]

Sorting list

sorted() – is a built-in function and will create a new list object


In [11]:
names = ["James", "John", "Andy", "Ben", "Chris", "Thomas"]
sorted_names = sorted(names)
print("Sorted names:" ,sorted_names)


Sorted names: ['Andy', 'Ben', 'Chris', 'James', 'John', 'Thomas']

sort() – is a method and will replace the original list object


In [12]:
names = ["James", "John", "Andy", "Ben", "Chris", "Thomas"]
names.sort()
print("Sorted names:",names)


Sorted names: ['Andy', 'Ben', 'Chris', 'James', 'John', 'Thomas']

Sorting lists numerically


In [13]:
values = [5, 7, 4, 6, 1, 2]
sorted_values = sorted(values)
print("Sorted values:", sorted_values)


Sorted values: [1, 2, 4, 5, 6, 7]

Sorting big to small


In [14]:
values = [5, 7, 4, 6, 1, 2, 45, 12]
sorted_values = sorted(values,reverse=True)
print("Sorted values:", sorted_values)


Sorted values: [45, 12, 7, 6, 5, 4, 2, 1]

In [15]:
values = [5, 7, 4, 6, 1, 2, 45, 12]
values.sort(reverse=True)
print("Sorted values:",values)


Sorted values: [45, 12, 7, 6, 5, 4, 2, 1]

Finding the length of a list


In [16]:
exam_scores = [67,78,94,45,55]
length = len(exam_scores)
print("number of scores:",length)


number of scores: 5

CONDITIONALS

  • Often you will want to add logic to your programs
  • This is done with simple statements (in nearly all languages):

    • if
    • else
    • elif (aka else if)
  • In Python, code within a conditional or a loop is denoted by a : followed by indentation (this will become clearer with examples)

Comparisons (logical operators)

An if statement is either true or false (synonymous with 1 or 0), these are known as Boolean values.


In [17]:
x = 5
y = 5
if x == y :
    print("x and y are the same")


x and y are the same

Examples of logical operators in action


In [18]:
a = 5
b = 4

if a < b:
    print("a is less than b") #conditional block must be indented four spaces or a tab


else:
    print("a is not less than b")


a is not less than b

In [19]:
name1 = "Alistair"
name2 = "Alastair"

if name1 == name2:
    print("names are the same")
else:
    print("names are not the same")


names are not the same

Boolean logic

  • Boolean logic is used for combining conditional statements

    • and
    • or
    • not
  • Used with logical operators can ask questions of almost unlimited complexity

  • Important to make sure you understand the logic of your question to combine conditions correctly

Using and

  • Code to test if both marks are greater than or equal to 70 Code

In [20]:
biol733_mark = 75
biol734_mark = 72

if biol733_mark >= 70 and biol734_mark >= 70:
    print("You're getting a distinction :-)")

else:
    print("You're not getting a distinction :-(")


You're getting a distinction :-)

Using or

  • Code to test if either mark is less than 50

In [21]:
biol733_mark = 34
biol734_mark = 55

if biol733_mark <50  or biol734_mark < 50:
    print("You've failed a module :-( ")

else:
    print("You've passed your modules :-) ")


You've failed a module :-( 

Converting English to Boolean

“If the day is not Monday or Friday, I am researching”


In [22]:
day = "Monday"

if day != "Monday" or day != "Friday":
    print("Alistair is researching")

else:
    print("Alistair is not researching")


Alistair is researching

This is wrong!

Statement really is:

“If the day is not Monday and the day is not Friday, I am researching”


In [23]:
day = "Monday"

if day != "Monday" and day != "Friday":
    print("Alistair is researching\n")

else:
    print("Alistair is not researching\n")


Alistair is not researching

i.e. with negatives both conditions have to be true

Nested statements


In [24]:
a = 4
b = 4
c = 6

if a == b:
    print("a equals b")

    if b >= c:
        print("and b is greater or equal to c")

    else:
        print("and b is less than c")

else:
    print("a doesn't equal b")


a equals b
and b is less than c

Note: you can have make statements as nested and complicated as you need. BUT...

  1. Your indentation Must be correct
  2. Always work out your logic in advance and add comments to your code (otherwise your code won’t do what you want it to do)

Using elif

elif is very useful if you want to test lots of conditions in order


In [25]:
module_code = "BIOL734"
if module_code == "BIOL007":
    module_name = "Statistics for Life Science"

elif module_code == "BIOL733":
    module_name = "Perl Programming"

elif module_code == "BIOL734":
    module_name = "Post-genomic technologies"

else:
    module_name = "Unknown module code"
print("The module is " + module_name + "\n")


The module is Post-genomic technologies

This tests the if statement first, then the first elsif statement and so on.

If no condition is matched, the else condition will be evaluated.

exit

exit() is very useful for forcing a program to finish


In [26]:
a = 4
b = 5

if a == b:
    print("a equals b\n")

else:
    exit("Error - a doesn't equal b\n")

print("Program continues...\n")


Program continues...

exit is very useful for error checking in your program e.g. if you want to check that something must happen to avoid a runtime error (remember example of dividing by zero last week...)


LOOPS

Looping structures

Two main structures in Python

  • for

  • while

  • for

    • Used for repeating code a number of times or iterating over items in an object such as a list
  • while

    • Used for looping in a conditional manner

for loops


In [27]:
for x in range(1, 6):
    print("Row number " + str(x))


Row number 1
Row number 2
Row number 3
Row number 4
Row number 5

Note: As with conditionals, indentation is crucial to denote the code that you want to run within the loop

  • for initiates the loop
  • x is a variable that represents the current loop item (in this case an integer representing the number of the loop)
  • range() creates a list of numbers between two given integers

Loop through a list


In [28]:
exam_scores = [67,78,94,45,55]

counter = 1
for x in exam_scores:
    print("score " + str(counter) + ": " + str(x))
    counter +=1 # “+=“ is the same as counter = counter + 1  incrementing


score 1: 67
score 2: 78
score 3: 94
score 4: 45
score 5: 55

while loops

  • while loops are completely flexible:
    • you can use whatever conditional statement you like
    • you need to ensure that you have the correct logic for making sure the loop ends at some point

In [29]:
a = 1

while a < 5:
    print("The value of a is ",a)
    a+=1


The value of a is  1
The value of a is  2
The value of a is  3
The value of a is  4

while loops are used a lot for reading from files (lecture 5) – the conditional statement is that you keep reading until there are no lines left in the file

Loops that never end...

  • Need to be careful that your loops actually finish

In [30]:
# a = 1

# while 4<5:
#    print("The value of a is ",a)
#    a+=1

The value of a is 1 The value of a is 2 The value of a is 3

....

Does not stop

Note: If your program doesn’t finish for any reason or gets into an infinite loop: In PyCharm you can hit the stop button in the bottom left hand corner

On the command line - you can terminate by pressing Ctrl + C (or by closing the command prompt window)

Summary

  • Lists
    • Very useful structure for storing data
    • Manipulating, sorting, printing
  • Conditionals
    • Can ask complex (unlimited) questions of data
    • Boolean logic
    • issues with converting plain language into logical statement
  • Loops
    • for and while can be used for all sorts of applications
    • extremely useful when working with large data files