Python Programming: Intermediate (Leaving Cert Computer Science): Revision Notes
Python Programming: Intermediate
Strings
We will begin by revisiting strings and examining them more closely. A string is an object: it has methods that can be invoked and fields we can access.
Object-oriented programming (methods, fields, objects) is outside the scope of the Leaving Certificate syllabus. The key thing to know is that a method is a function we can access from an object, and a field is a value we can access from an object.
Assuming str is our string, common string methods include:
- str.lower() : converts all characters in the string to lowercase.
- str.upper() : converts all characters in the string to uppercase.
- str.capitalize() : capitalises the first character of the string.
- str.title() : capitalises the first character of each word in the string.
We invoke a method by typing . after the object, followed by the method name.
sentence = "this is my string"
print(sentence.upper()) # THIS IS MY STRING
print(sentence.title()) # This Is My String
- str.strip() : removes leading and trailing whitespace.
- str.lstrip() : removes leading whitespace.
- str.rstrip() : removes trailing whitespace.
sentence = " this is my string "
print(sentence.strip()) # "this is my string"
print(sentence.rstrip()) # " this is my string"
Strings are indexed, meaning each character has a position (index) starting from 0. You can access individual characters or slices of a string using square brackets [].
Consider the string "Hello John"; the index of each character is as follows:
greeting = "Hello John"
first_letter = greeting[0] # "H"
sixth_letter = greeting[5] # " " (whitespace character)
last_letter = greeting[len(greeting) - 1] # "n"
Python also supports negative indexing, which counts from the end of the string. So greeting[-1] is the last character ("n") — a shorter way of writing greeting[len(greeting) - 1].
Indexing also allows us to slice strings, which lets us take substrings.
- [start : end] slices from the start index up to but not including the end index.
- [start : ] slices from the start index up to the end of the string.
- [ : end] slices from the start of the string up to but not including the end index.
greeting = "Hello John"
first_word = greeting[0 : 5] # "Hello"
substring = greeting[2 : 7] # "llo J"
second_word = greeting[6 : ] # "John"
- str.find(sub) : returns the lowest index where substring sub is found, or -1 if not found.
- str.rfind(sub) : returns the highest index where substring sub is found, or -1 if not found.
- str.replace(old, new) : returns a new string where all occurrences of old are replaced by new.
text = "Hello, World!"
print(text.find('World')) # 7
print(text.rfind('o')) # 8
print(text.replace('World', 'Python')) # 'Hello, Python!'
- str.startswith(prefix) : returns True if the string starts with the given prefix.
- str.endswith(suffix) : returns True if the string ends with the given suffix.
- str.isalpha() : returns True if all characters are alphabetic.
- str.isdigit() : returns True if all characters are digits.
- str.isalnum() : returns True if all characters are alphanumeric.
text = "Python3"
print(text.startswith('Py')) # True
print(text.endswith('3')) # True
print(text.isalpha()) # False
print(text.isdigit()) # False
print(text.isalnum()) # True
Escape Characters
Escape characters are used to include special characters in a string. They are prefixed with a backslash, [].
- \n : newline
- \t : tab
- \ : backslash
- ' : single quote
- " : double quote
print("Hello\nWorld") # Newline
print("Hello\tWorld") # Tab
print("Backslash: \\") # Backslash
print("Single quote: \'") # Single quote
print("Double quote: \"") # Double quote
Boolean Expressions
Boolean expressions are expressions that evaluate to either True or False.
- and : returns True if both operands are true.
- or : returns True if at least one operand is true.
- not : returns True if the operand is false.
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
print(not y) # True
Conditionals
Conditionals allow you to execute different blocks of code depending on certain conditions. In Python, conditional statements make decisions by evaluating Boolean expressions.
The if statement tests a condition. If the condition evaluates to True, the block under the if statement runs. If it is False, the block is skipped.
age = 18
if age >= 18:
print("You are an adult.")
If we changed age to 10, for example, the print statement would not execute.
Note that the print statement is indented. Python uses indentation to decide whether code belongs to a certain block — here, the print statement belongs to the if branch. Most editors indent automatically once you type :; otherwise you can indent by pressing the Tab key.
The else statement follows an if and runs when the if condition is False. It provides an alternative set of instructions when the condition is not met.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The elif statement (short for "else if") lets you check multiple conditions. It must follow an if or another elif. When an elif condition is True, its block runs and the remaining elif and else blocks are skipped.
age = 20
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
Lists
Lists are one of the most versatile and commonly used data structures in Python. They store multiple items in a single variable.
Lists are mutable, meaning their elements can be changed after the list has been created. They are defined by enclosing items in square brackets ([]), separated by commas.
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "apple", 3.14, True]
Like strings, lists are indexed.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[2]) # cherry
You can access a range of elements using slicing. The syntax is list[start : end : step].
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:4]) # [0, 1, 2, 3]
print(numbers[5:]) # [5, 6, 7, 8, 9]
print(numbers[::2]) # [0, 2, 4, 6, 8]
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Lists are also objects and support their own methods.
- append() : adds an element to the end of the list.
- insert() : inserts an element at a specified position.
- extend() : adds all elements of another list to the end of the current list.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
fruits.insert(1, "blueberry")
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry', 'orange']
more_fruits = ["mango", "pineapple"]
fruits.extend(more_fruits)
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry', 'orange', 'mango', 'pineapple']
- remove() : removes the first occurrence of a specified value.
- pop() : removes and returns the element at a specified position. With no index, pop() removes and returns the last item.
- clear() : removes all elements from the list.
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry', 'banana']
fruits.pop(1)
print(fruits) # ['apple', 'banana']
fruits.pop()
print(fruits) # ['apple']
fruits.clear()
print(fruits) # []
Iteration
Iteration refers to repeatedly executing a block of code. In Python, we perform iteration using loops. The two primary types are while loops and for loops.
A while loop repeatedly executes a block of code as long as a given condition is True.
count = 0
while count < 5:
print(count)
count = count + 1
"""
0
1
2
3
4
"""
Code analysis
- The variable count is initialised to 0.
- The while loop checks the condition count < 5 before each iteration. If it is True, the loop body executes; if False, the loop terminates.
- On the first pass, count is 0, which is less than 5, so the condition is True. The current value of count is printed, then count is incremented by 1 with count = count + 1. Now count is 1.
- On the next pass, count is 1, still less than 5, so the process repeats.
- The loop continues until the condition evaluates to False (when count reaches 5).
The count = count + 1 portion is a crucial part of the loop, called incrementation. If we didn't increment, count would never change and the loop would run forever — an infinite loop, which may cause the program to hang or crash.
Incrementation is so common that Python supports shorthand notations for reassigning a variable:
count = 0
count += 1 # equivalent to count = count + 1
count -= 2 # equivalent to count = count - 2
count *= 2 # equivalent to count = count * 2
count /= 2 # equivalent to count = count / 2
By declaring a counter before entering a loop, we can iterate over lists and strings. Here is an example that replaces all negative integers in a list with 0.
index = 0
numbers = [2, 4, 5, -1, -3, 5, 1, 0, -4]
while index < len(numbers):
if numbers[index] < 0:
numbers[index] = 0
index += 1
print(numbers) # [2, 4, 5, 0, 0, 5, 1, 0, 0]
Here is an example that counts the number of vowels in a string.
index = 0
counter = 0
vowels = ['a', 'e', 'i', 'o', 'u']
sentence = "here is my string"
while index < len(sentence):
if sentence[index] in vowels:
counter += 1
index += 1
print(counter) # 4
Note the in keyword. It has several interpretations depending on context; here, the condition checks whether the current character is in the list vowels.
A for loop is used to iterate over anything that is iterable — any object that can be looped over, such as a list or a string. The general syntax is:
for variable in sequence:
# do something
fruits = ["apple", "banana", "cherry", "banana"]
for fruit in fruits:
print(fruit)
Note how much easier it is to iterate over a sequence with a for loop than with a while loop — there is no counter to declare, increment, or bounds-check.
The range function generates a sequence of numbers. It is useful for iterating a specific number of times.
# Iterating from 0 to 4
for i in range(5):
print(i)
# Iterating from 1 to 5
for i in range(1, 6):
print(i)
# Iterating with a step
for i in range(0, 10, 2):
print(i)
Providing a third argument to the range function specifies the step of the sequence. The default step is 1.
Remember!
- Strings are objects with useful methods: upper(), lower(), strip(), find(), replace(), startswith(), and the is...() checks.
- Strings and lists are both indexed from 0 and support slicing ([start : end : step]); negative indices count from the end.
- Escape characters (\n, \t, \) insert special characters into strings.
- Boolean expressions combine with and, or, not.
- Conditionals (if / elif / else) choose which block runs, using indentation to define blocks.
- Lists are mutable and have methods like append(), insert(), pop(), remove().
- Loops repeat code: a while loop runs while a condition holds (remember to increment, or you get an infinite loop); a for loop iterates over any iterable, often with range().