Lists
Conditionals
Loops
A list of numbers: 67 78 94 45 55
In [1]:
exam_scores = [67,78,94,45,55,66]
print("scores: " ,exam_scores)
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])
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 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])
In [4]:
exam_scores = [67,78,94,45,55]
print ("Here are the scores:",exam_scores)
Note: If you want to print all elements individually (and do something else with them), you should loop through them – later in lecture...
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)
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)
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)
In [8]:
exam_scores = [67,78,94,45,55]
exam_scores.pop(2)
print (exam_scores)
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)
In [10]:
exam_scores = [67,78,94,45,55]
exam_scores.reverse()
print (exam_scores)
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)
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)
In [13]:
values = [5, 7, 4, 6, 1, 2]
sorted_values = sorted(values)
print("Sorted values:", sorted_values)
In [14]:
values = [5, 7, 4, 6, 1, 2, 45, 12]
sorted_values = sorted(values,reverse=True)
print("Sorted values:", sorted_values)
In [15]:
values = [5, 7, 4, 6, 1, 2, 45, 12]
values.sort(reverse=True)
print("Sorted values:",values)
In [16]:
exam_scores = [67,78,94,45,55]
length = len(exam_scores)
print("number of scores:",length)
This is done with simple statements (in nearly all languages):
In Python, code within a conditional or a loop is denoted by a : followed by indentation (this will become clearer with examples)
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")
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")
In [19]:
name1 = "Alistair"
name2 = "Alastair"
if name1 == name2:
print("names are the same")
else:
print("names are not the same")
Boolean logic is used for combining conditional statements
Used with logical operators can ask questions of almost unlimited complexity
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 :-(")
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 :-) ")
In [22]:
day = "Monday"
if day != "Monday" or day != "Friday":
print("Alistair is researching")
else:
print("Alistair is not 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")
i.e. with negatives both conditions have to be true
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")
Note: you can have make statements as nested and complicated as you need. BUT...
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")
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.
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")
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...)
Two main structures in Python
for
while
for
while
In [27]:
for x in range(1, 6):
print("Row number " + str(x))
Note: As with conditionals, indentation is crucial to denote the code that you want to run within the loop
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
In [29]:
a = 1
while a < 5:
print("The value of a is ",a)
a+=1
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
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)