Introduction to Python Programming

In this section we will be introducing the fundamental concepts of Python programming. We will do examples and give you problems/challenges to solve.

Python is a dynamic, interpreted (bytecode-compiled) and a very easy language. It has a very straightforward syntax.

We will be using Google's Colaboratory to run our code. See this on how to get started:

The following lessons can also be done on your android smartphone using Qpython

The following are the rules you need to follow in Python Programming:

The Print function:

The print statement in Python 2 is not a function whereas in Python 3 it is, so we need to invoke it with parenthesis :

print("Hello, World")
print ("Hi everyone, welcome to Reacoda")
# you can write a message as a variable and print the message
message = "SARS-CoV-2 is the name of the virus that causes the COVID-19 desease"
print (message)

Indentation

Indentation is used for blocks instead of curly brackets. The standard indentation requires standard Python code to use 4 spaces.

x = 1
if x==1:
  print("x is  1")
  

Basic Data Types

Variables and Types

Python is object orientated and not statically typed. You don't need to declare a variable before using it. Every variable is an object.

Numbers

There are two types of numbers that are supported in Python - integers and floating point numbers.

myint = 48
print(myint)

myfloat = 8.5
print(myfloat)

myfloat1 = float(5)
print(myfloat1)

Strings

Strings are sequences of character data. The string type in Python is called str

Strings are defined either with a single or a double inverted comma.

mystring = 'How to prevent the spread of Covid-19'
print(mystring)

mystring1 = "wash your hands frequently"
print(mystring1)

The difference between the two is that using double quotes makes it easy to include apostrophes (whereas these would terminate the string if using single quotes)

Simple operators can be executed on numbers and strings

seven = 7
twenty = 20 
twentyseven = seven + twenty 
stay = "stay"
at = "at"
home = "home"
if = "if"
you = "you"
feel = "feel"
unwell = "unwell"
prevention = stay + " " + at + " " + home + " " + if + " " +
you + " " + feel + " " + unwell

Assignments can be done on more than one variable "simultaneously" on the same line like this.

Mixing operators between numbers and strings is not supported.

string1, string2 = "cover your cough using the bend of elbow", 
"or use a tissue"
print(string1, string2)

Lists

A list stores a series of items in a particular order. You access items using an index, or within a loop.

Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner. Here is an example of how to build a list.

mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

# prints out 1,2,3
for x in mylist:
    print(x)

Slicing a List

affected_countries = ["South Africa", "Egypt", "Algeria", 
"Morocco"]

first_two = affected_countries[:2]

print(first_two)

Exercise:

In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method. You must add the numbers 1,2, and 3 to the "numbers" list, and the words 'first name' and 'last name' to the strings variable.

You will also have to fill in the variable third_country with the third country in the names list, using the brackets operator []. Note that the index is zero-based, so if you want to access the second item in the list, its index will be 1.

numbers = []
strings = []
affected_countries = ["South Africa", "Algeria", "Egypt", 
"Morocco"]

# write your code here
third_country = None


# this code should write out the filled arrays and the 
# third country in the affected country list (Egypt).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)

Tuples

Tuples are similar to lists, but the items in tuples can't be modified.

dimensions = (1880, 2650)
print (dimensions)

String Formatting

Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

Let's say you have a variable called "name" with your user name in it, and you would then like to print(out a greeting to that user.)

# This prints out "Hello, <your name>!"
name = "<your name>"
print("Hello, %s!" % name)

use two or more argument specifiers, use a tuple (parentheses):

# This prints out "<your name> is <your age> years old."
name = "<your name>"
age = <your age>
print("%s is %d years old." % (name, age))

Any object which is not a string can be formatted using the %s operator as well.

# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)

Here are some basic argument specifiers you should know:

%s - String (or any object with a string 
representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with
 a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation
 (lowercase/uppercase)

Exercise

You will need to write a format string which prints out the data using the following syntax: Hello <your name>. Your current balance is R76.44.

data = ("<your first name>", "<your last name>", 76.44)
format_string = "Hello"

print(format_string % data)

Solution:

data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."

print(format_string % data)

Conditions

Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated. For example:

x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

variable assignment is done using a single equals operator "=", whereas comparison between two variables is done using the double equals operator "==". The "not equals" operator is marked as "!=".

Boolean Operators

The "and" and "or" boolean operators allow building complex boolean expressions, for example:

name = "<your name>"
age = <your age>
if name == "<your age>" and age == <your age>:
    print("Your name is <your name>, and you are
     also <your age> years old.")

if name == "<your name>" or name == "<another name>":
    print("Your name is either <your name> 
    or <another name>.")

The "in" Operator

The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:

name = "<your first name>"
if name in ["<your first name>", "<your last name>"]:
    print("Your name is either <your first name> or <your last name>.")

Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks do not need any termination.

Here is an example for using Python's "if" statement using code blocks:

statement = False
another_statement = True
if statement is True:
    # do something
    pass
elif another_statement is True: # else if
    # do something else
    pass
else:
    # do another thing
    pass
x = 2
if x == 2:
    print("x equals two!")
else:
    print("x does not equal to two.")

A statement is evaulated as true if one of the following is correct: 1. The "True" boolean variable is given, or calculated using an expression, such as an arithmetic comparison. 2. An object which is not considered "empty" is passed.

Here are some examples for objects which are considered as empty: 1. An empty string: "" 2. An empty list: [] 3. The number zero: 0 4. The false boolean variable: False

The "is" operator

Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves. For example:

x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False

The "not" operator

Using "not" before a boolean expression inverts it:

print(not False) # Prints out True
print((not False) == (False)) # Prints out False

Exercise:

Change the variables in the first section, so that each if statement resolves as True.

# change this code
number = 10
second_number = 10
first_array = []
second_array = [1,2,3]

if number > 15:
    print("1")

if first_array:
    print("2")

if len(second_array) == 2:
    print("3")

if len(first_array) + len(second_array) == 5:
    print("4")

if first_array and first_array[0] == 1:
    print("5")

if not second_number:
    print("6")

Solution:

# change this code
number = 16
second_number = 0
first_array = [1,2,3]
second_array = [1,2]

if number > 15:
    print("1")

if first_array:
    print("2")

if len(second_array) == 2:
    print("3")

if len(first_array) + len(second_array) == 5:
    print("4")

if first_array and first_array[0] == 1:
    print("5")

if not second_number:
    print("6")

Loops

There are two types of loops, for and while:

for loops

for loop: Looping through a list Lists can contain millions of items, so Python provides an efficient way to loop through all the items in a list. When you set up a loop, Python pulls each item from the list one at a time and stores it in a temporary variable, which you provide a name for

primes = [2, 3, 5, 7]
for prime in primes:
    print(prime)

while loops

While loops repeat as long as a certain boolean condition is met.

# Prints out 0,1,2,3,4

count = 0
while count < 5:
    print(count)
    count += 1  # This is the same as count = count + 1

"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.

# Prints out 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)

"else" clause for loops

can we use "else" clause for loops?

unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed. If 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.

# Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))

# Prints out 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("this is not printed because for loop is terminated because of break but not due to fail in condition")

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.

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

A function is a block of code which only runs when it is called.

Functions in python are defined using the block keyword "def", followed with the function's name as the block's name.

def my_function():
    print("Hello From My Function!")

Functions may also receive arguments (variables passed from the caller to the function). For example:

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'

def sum_two_numbers(a, b):
    return a + b

Calling Functions in Python

Simply write the function's name followed by (), placing any required arguments within the brackets:

#Define our 3 functions
def 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

# print(a simple greeting)
my_function()

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!
x = sum_two_numbers(1,2)

Exercise:

Classes and Object

A class is a code template for creating objects. Objects have member variables and have behavior associated with them.\

In python a class is created by the keyword class . An object is created using the constructor of the class. This object will then be called the instance of the class.

A very basic class would look something like this:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

to assign the above class(template) to an object you would do the following:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside 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:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

myobjectx.variable

the code below would output the string "blah:

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

print(myobjectx.variable)

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

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()
myobjecty = MyClass()

myobjecty.variable = "yackity"

# Then print out both values
print(myobjectx.variable)
print(myobjecty.variable)

Accessing Object Functions

To access a function inside of an object you use notation similar to accessing a variable

class MyClass:
    variable = "blah"

    def function(self):
        print("This is a message inside the class.")

myobjectx = MyClass()

myobjectx.function()

Exercise:

We have a class defined for vehicles. Create two new vehicles called car1 and car2. Set car1 to be a red convertible worth R 600,000.00 with a name of Fer, and car2 to be a blue van named Jump worth R 200,000.00.

# define the Vehicle class
class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth R%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str
# your code goes here

# test code
print(car1.description())
print(car2.description())

Solution:

# define the Vehicle class
class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str

# your code goes here
car1 = Vehicle()
car1.name = "Fer"
car1.color = "red"
car1.kind = "convertible"
car1.value = 60000.00

car2 = Vehicle()
car2.name = "Jump"
car2.color = "blue"
car2.kind = "van"
car2.value = 10000.00

# test code
print(car1.description())
print(car2.description())

Dictionary

is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized.

For example, a database of phone numbers could be stored using a dictionary like this:

phonebook = {}
phonebook["Karabo"] = 938477566
phonebook["Tebogo"] = 938377264
phonebook["Katlego"] = 947662781
print(phonebook)

Alternatively, a dictionary can be initialized with the same values in the following notation:

phonebook = {
    "Kabelo" : 938477566,
    "Kgomotso" : 938377264,
    "Palesa" : 947662781
}
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:

phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for 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

phonebook = {
   "John" : 938477566,
   "Jack" : 938377264,
   "Jill" : 947662781
}
del phonebook["John"]
print(phonebook)

Last updated