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.
Last updated
In this section we will be introducing the fundamental concepts of Python programming. We will do examples and give you problems/challenges to solve.
Last updated
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 :
Indentation
Indentation is used for blocks instead of curly brackets. The standard indentation requires standard Python code to use 4 spaces.
Python is object orientated and not statically typed. You don't need to declare a variable before using it. Every variable is an object.
There are two types of numbers that are supported in Python - integers and floating point numbers.
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.
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
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.
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.
Slicing a List
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.
Tuples
Tuples are similar to lists, but the items in tuples can't be modified.
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.)
use two or more argument specifiers, use a tuple (parentheses):
Any object which is not a string can be formatted using the %s operator as well.
Here are some basic argument specifiers you should know:
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.
Solution:
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated. For example:
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 "!=".
The "and" and "or" boolean operators allow building complex boolean expressions, for example:
The "in" operator could be used to check if a specified object exists within an iterable object container, such as a list:
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:
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
Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the instances themselves. For example:
Exercise:
Change the variables in the first section, so that each if statement resolves as True.
Solution:
There are two types of loops, for and while:
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
While loops repeat as long as a certain boolean condition is met.
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.
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.
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.
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.
Functions may also receive arguments (variables passed from the caller to the function). For example:
Functions may return a value to the caller, using the keyword- 'return'
Simply write the function's name followed by (), placing any required arguments within the brackets:
Exercise:
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:
to assign the above class(template) to an object you would do the following:
Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass"
To access the variable inside of the newly created object "myobjectx" you would do the following:
the code below would output the string "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
To access a function inside of an object you use notation similar to accessing a variable
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.
Solution:
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:
Alternatively, a dictionary can be initialized with the same values in the following notation:
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:
To remove a specified index, use either one of the following notations