Warning - This site is moving to https://getthecodingbug.anvil.app
Topics covered
Two types of loops: For and While
Using break and continue
Defining and using Functions
Using Reeborg's World
Classes and Objects
Dictionaries
Loops
There are two types of loops in Python, 'for' and 'while'.
The 'for' loop
For loops iterate over a given sequence. Here is an example:
# example for loop
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
results in:
2
3
5
7
For loops can iterate over a sequence of numbers using the "range" function.
# example for loop with range
for x in range(5):
print(x)
results in:
0
1
2
3
4
Note that the range function is zero based.
For loops can iterate over a sequence of numbers using the "range" function.
# example for loop with range
for x in range(3,6):
print(x)
4
5
results in: (Note that the 6 is not printed - that is where the for loop is told to end)
3
You can alter the steps (default is 1), as follows:
# example for loop with range and step modifier
for x in range(3,8,2):
print(x)
results in:
3
5
7
'while' loops
While loops repeat as long as a certain boolean condition is met, for example:
# example while loop
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
results in:
0
1
2
3
4
'break' and 'continue' statements
break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples:
# using 'break' statements
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
results in:
0
1
2
3
4
"for" or "while" statement. A few examples:
# using 'continue' statements
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue # This causes a early branch back to the beginning of the for loop print(x)
results in:
1
3
5
7
9
Can we use 'else' clause for loops?
Unlike languages like C, C++. we can use 'else' in 'for' loops. When the loop condition of 'for' or 'while' statement fails then code part in 'else' is executed.
If a 'break' statement is executed inside for loop then the 'else' part is skipped. Note that 'else' part is executed even if there is a continue statement.
Here are a few examples:
# using else in while loops
count=0
while(count < 5):
print(count)
count += 1
else:
print("count value reached %d" %(count))
results in:
0
1
2
3
4
count value reached 5
# using else in for loops
for i in range(1, 10):
if(i % 5 == 0):
break
print(i)
else:
print("this is not printed because for loop is terminated") print("because of break but not due to fail in condition")
results in:
1
2
3
4
Exercise
Loop through and print out all even numbers from the numbers list in the same order they are received.
Don't print any numbers that come after 237 in the sequence.
# Exercise - don't print any numbers after 237 numbers = [
951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941, 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470, 743, 527
]
# your code goes here
Functions
What are Functions?
Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time.
Also functions are a key way to define interfaces so programmers can share their code.
How do you write functions in Python?
As we have seen on previous lessons, Python makes use of blocks.
A block is a area of code of written in the format of:
block_head:
1st block line
2nd block line
…
Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...)
Block keywords you already know are "if", "for", and "while".
Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
# defining a function
def my_function():
print("Hello From My Function!")
Functions may also receive arguments (variables passed from the caller to the function), for example:
# defining a function with arguments
def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
Functions may return a value to the caller, using the keyword- 'return', for example:
# returning values from a function
def sum_two_numbers(a, b):
return a + b
How do you call functions in Python?
Simply write the function's name followed by (), placing any required arguments within the brackets.
For example, lets call the functions written above (in the previous example):
# defining functions, then calling themdef my_function():
print("Hello From My Function!")def my_function_with_args(username, greeting):
print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
def sum_two_numbers(a, b):
return a + b # calling the functions my_function() my_function_with_args("John Doe", "I wish you a great year!") x = sum_two_numbers(1,2)
print(x)
results in:
Hello From My Function!
Hello, John Doe , From My Function!, I wish you a Great Year!
3
Exercise
In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
1. Add a function named "list_benefits()" that returns the following list of strings:
"More organised code",
"More readable code",
"Easier code reuse",
"Allowing programmers to share and connect code together"
2. Add a function named "build_sentence(info)" which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"
3. Run and see all the functions work together!
# Modify the first two functions as described in 1 and 2 above
def list_benefits():
pass # your code should replace this pass statement
def build_sentence(benefit):
pass # your code should replace this pass statement
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))
name_the_benefits_of_functions()
Using Reeborg's World
Reeborg's World is intended to help beginners to learn programming, using Python.
You can learn all about Reeborg's World here: http://reeborg.ca/index_en.html
We are going to use Reeborg's World to practice functions.
First, open up a new tab in your browser and go to: http://reeborg.ca/reeborg.html
Here you should see a grid with a little Reeborg robot facing right in the bottom left-hand corner.
To the right is a blue panel on which you can write some python statements.
Write 'move()' without the quotes in the panel and then click the 'Play' button above the grid.
Reeborg should have moved one space to the right. If he did not do what you expected, check that you have entered your code correctly and retry.
You can reset Reeborg by clicking the 'Reload' button (4 buttons to the right of the 'Play' button)
Try adding more 'move()' statements and see what happened, when you 'Reload' and 'Play' again.
Adding your own functions
Now lets add a function.
First, wipe all your code, then enter the code below:
# Define a move three places function
def move3places():
move()
move()
move()
# Now use the function we have just created
move3places()
Reeborg has a number of in-built functions - you can see them by clicking the 'Reeborg's keyboard' button on the menu. You will notice that there is a 'turn_left()' function. Try it and make Reboorg move around the grid.
Notice also that there is no 'turn_right()' function.
Challenge - Create your own 'turn_right()' function, then use it in your program to navigate the whole grid.
Classes and Objects
Objects are an encapsulation of variables and functions into a single entity.
Objects get their variables and functions from classes. Classes are essentially a template to create your objects.
A very basic class would look something like this:
Functions may return a value to the caller, using the keyword- 'return', for example:
# defining a class
class MyClass:
variable = "blah"
def func(self):
print("This is a message inside the class.")
We'll explain why you have to include that "self" as a parameter a little bit later.
First, to assign the above class(template) to an object you would do the following:
# define a class
class MyClass:
variable = "blah"
def func(self):
print("This is a message inside the class.")# using the class myobjectx = MyClass()
Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass".
Accessing Object Variables
To access the variable inside of the newly created object "myobjectx" you would do the following:
First, to assign the above class(template) to an object you would do the following:
# define a class
class MyClass:
variable = "blah"
def func(self):
print("This is a message inside the class.")# using the classmyobjectx = MyClass()print(myobjectx.variable)
Would print out:
blah
You can create multiple different objects that are of the same class(have the same variables and functions defined).
However, each object contains independent copies of the variables defined in the class.
For instance, if we were to define another object with the "MyClass" class and then change the string in the variable above:
# define the class class MyClass:
variable = "blah"
def func(self):
print("This is a message inside the class.")
# create two objects of that class myobjectx = MyClass()
myobjecty = MyClass() # change the variable of one of the objects
myobjecty.variable = "yackity"
# Then print out both objects's values
print(myobjectx.variable)
print(myobjecty.variable)
Would print out:
blah
yackity
Accessing Object Functions
To access a function inside of an object you use notation similar to accessing a variable:
myobjextx.func()
Would print out the message, "This is a message inside the class."
Exercise
We have a class defined for vehicles. Create two new vehicles called car1 and car2.
Set car1 to be a red convertible worth $60,000.00 with a name of Fer,
and car2 to be a blue van named Jump worth $10,000.00.
Add your code after the '# your code goes here' comment, below:
# define the Vehicle class
class Vehicle:
name = ""
kind = "car"
colour = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." % \ (self.name, self.colour, self.kind, self.value)
return desc_str
# your code goes here
# test your code
print(car1.description())
print(car2.description())
Note: The back-slash ('\') inside the 'desc_str' variable, above, is a way of splitting a long python statement into 2 or more lines.
Dictionaries
A dictionary is a data type similar to lists, but works with keys and values instead of indexes.
Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.
For example, a database of phone numbers could be stored using a dictionary like this:
# create a dictionary
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781 # display its contents
print(phonebook)
Alternatively, a dictionary can be initialized with the same values in the following notation:
# create a dictionary
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}# display its contents
print(phonebook)
Iterating over dictionaries
Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it.
To iterate over key value pairs, use the following syntax:
# create a dictionary
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# iterate over the key value pairsfor name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
Removing a value
To remove a specified index, use either one of the following notations:
# create a dictionary
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}# remove an entry, using deldel phonebook["John"]
print(phonebook)# remove an entry, using pop phonebook.pop("Jill")
print(phonebook)
Exercise
Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.
# Exercise
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# write your code here
# testing your code
if "Jake" in phonebook:
print("Jake is listed in the phonebook.") else: print("Jake is NOT in the phonebook yet!")
if "Jill" not in phonebook:
print("Jill is not listed in the phonebook.") else: print("Jill is STILL listed in the phonebook!")