Fathomable Python Programming — Beginner’s Guide
DOWNLOAD AND INSTALLATION OF PYTHON
I. Download Python Here
II. Endeavour to Add Python 3.7 to PATH
by clicking the check button as indicated by the arrow below then click Install Now
Installation of Python 3.x Version
After installation to check if Python is properly installed. Search Python IDLE or do the following in your command prompt or terminal:
You may wish to continue with the command prompt or terminal.
If you do not want to download and install the IDLE you can use any online editor. Some of the common online editors on Python are:
1. The official Online Python Shell
2. Repl.it
3. Rextester
4. GDB
5. Tutorialspoint Terminal
6. Ideone
7. PythonAnywhere
8. Sympy
9. Jdoodle
10. Codechef
11. HackerEarth
HISTORY OF PYTHON
To know Python history type the command license()
or help(license())
in the Python Shell. An Interactive Python Shell has the command prompt >>>
. The shell executes code line by line thereby provide comfortable command-line interface.
That’s a lot of text!
To reduce the number of lines do the following:
Mouse Over the text area and Right click on the text area
→ Mouse Over on the yellow 'squeezed text'
→ 'right-click for more options'
→'view'
Note that the number of lines provided by the help()
function varies depending on the area, font-size of your screen.
Data Structure and Variables
Generally in all programming languages, a variable is defined or declared when a value is assigned to it with the assignment operator (=
). When variables are defined these values are stored or allocated in a memory area or space. This means that variable references or locates the value when needed.
In many programming languages, variables are best thought of as containers or buckets into which you put data.
Statically-typed languages might miss the type-safety that comes with declarations like those found in C,
So in C, for example, when you write
you are essentially defining a “memory bucket” named x
, and putting the value 4
into it.
Most Programming Languages are statically-typed language meaning that there are data types, but variables are bound to them.
Python Variables are Pointers
In Python, by contrast, variables are the best thought of not as containers but as pointers. So in Python, when you write
you are essentially defining a pointer named x
that points to some other bucket containing the value 4
. Note one consequence of this: because Python variables just point to various objects, there is no need to "declare" the variable, or even require the variable to always point to information of the same type! This is the sense in which people say Python is dynamically-typed: variable names can point to objects of any type.
Python is a dynamically-typed language meaning that there are data types, but variables are not bound to any of them. Objects contain data types.
So in Python, you can do things like this:
this dynamic typing is one of the pieces that makes Python so quick to write and easy to read.
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
What are Classes and Objects in Python?
Python is an object-oriented programming language. An object is simply a collection of data (variables) and methods (functions) that act on those data. And, a class is a blueprint for the object.
Python is an object-oriented programming language, and in Python everything is an object.
We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
As many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation. Objects are created majorly by methods and attributes.
Methods are like attributes, except they are functions that you can call using opening and closing parentheses. For example, floating-point numbers have a method called is_integer
that checks whether the value is an integer.
When we say that everything in Python is an object, we really mean that everything is an object — even the attributes and methods of objects are themselves objects with their own type
information
These objects contain data along with associated metadata and/or functionalities. This metadata is also called attributes. There are various data types in Python. These objects can be integers (int()
), floating-point numbers (float()
), boolean (True
/ False
), strings (str()
) etc.
View Image
Python has types; however, the types are linked not to the variable names but to the objects themselves.
Python doesn’t declare variables (other programming languages like JavaScript declare variables before the identifier — e.g. var variableName
in JavaScript).
Objects can be either mutable or immutable. A mutable object can be changed after it is created, and an immutable object can’t.
Primitive Data Types (Structures)
Data Structure is used to organize and structure pieces of data in computer programming. Data structures can be divided into two categories: Primitive Data Structure and Non-Primitive Data structures. Primitive data structures are the simplest forms of representing data hence the name primitive, while the non-primitive structures are designed to organize and manage sets of primitive data. All Primitive Data Types (Structures) are immutable objects.
Python has five primitive data types:
- Integer
- Float
- Complex
- String
- Boolean
Numbers include positive or negative whole numbers with no decimal point, Floating point numbers (with decimal), Complex numbers. A boolean can be either be True
or False
. A string literal or text is a set of characters, including space enclosed in two quotation mark.
We can check each if a value is a data type by using the built-in function called the isinstance()
function. It returns True
if the data in the first argument (values in a function parenthesis (()
) are referred to as arguments) correspond to the data type in the second argument. For example isinstance(43, int)
. If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
Non — Primitive Data Types (Structures)
Non-primitive data structures can store an object (data type) or a collection of objects (data types) in various formats. The non-primitive structures are designed to organize and manage sets of primitive data. Python has five non-primitive data types:
- List
- Set
- Dictionary
- Frozenset
- Tuple
View Image
In the example when a comma and space was created it means that as many data types (same or different) can be added.
Note: int, float, complex, bool, str, list, set, dict, frozenset, tuple are all built-in types but thet are not the only objects in Python.
Let’s take a look at each of the data types.
Instead of type()
use help()
in the example above to get more description on the data types — integer floating-point, complex number, a string literal, a boolean value, list, set, frozenset, tuple and dictionary
Numbers — help('NUMBERS')
Numbers are integer, floating point, complex numbers which are immutable.
Let’s See another example.
View Image
Numerical types have a real
and imag
attribute that returns the real and imaginary part of the value, if viewed as a complex number
Complex numbers can be expressed in the form a + bj
, where a and b are real numbers or a is a real part while b is an imaginary part and j is a solution of the equation x * x= −1. j
is an imaginary number because when squared gives a negative result.
Complex number conversion is done with the complex()
function. See the example below.
View Image
Type help('COMPLEX')
or help(complex)
Python as a Calculator
Python can easily be used as a calculator by simply inputting values and binary operator (Operators in-between two operands (values or variables)) in a console to perform mathematical operations. See the example below.
View Image
Comparison Operators
Comparison operators simply compare values.
Here is the list of various comparison operators:
View ImageTry It Here
In the example above the returned boolean value can be reversed by using the not
operator. For example, not x < y
will return False.
In Python also apart from joining strings with the addition symbol (+
) we can also repeat strings with the multiplication symbol (*
). See the example below.
View Image
Python also allows you to compare three values at the same time.
View Image
You will see more of tuples later.
A quick notes about the symbols ,
and +
Note:
Commas (,) are only used to separate variables, parameters, values and arguments. They should not be mistaken with the plus (+) symbol for concatenation.
When commas are used between variables or values, the returned output is a tuple. Commas automatically creates space between values unlike the plus (+) symbol for concatenation which apart from string concatenation, the + is used for arithmetic addition of the same types (e.g. numbers or booleans)
Strings — help('STRINGS')
View ImageTry It Here
Strings separated by commas produces a tuple
It is a good practice in Python to make your string not more than 80 characters in a line according to Python Enhancement Proposals (PEP). This is strictly for readability of code by other users. Long strings can be broken by doing the following:
open bracket
→ provide the string literals
→ click the enter (return) key
→ close the bracket
.
View Image
Strings Comparison
View Image
In the examples above, the comparison 'Z' > 'A'
gets to a result at the first step while the strings 'Glow'
and 'Glee'
are compared character-by-character:
2. Lowercase characters has a greater index in the internal encoding table than uppercase characters. Python uses Unicode in this ordering.
G
is the same asG
.l
is the same asl
.o
is greater thane
. Stop here. The first string is greater.
Not a real dictionary, but Unicode order
The comparison algorithm given above is roughly equivalent to the one used in dictionaries or phone books, but it’s not exactly the same.
For instance, case matters. A capital letter "A"
is not equal to the lowercase "a"
. Which one is greater? The lowercase "a"
. Why? Because the lowercase character has a greater index in the internal encoding table Python uses (Unicode).
Escape Characters In Strings
Following table is a list of some escape or non-printable characters that can be represented with backslash notation.
An escape character gets interpreted; in a single-quoted as well as double-quoted strings.
Backslash notation Description Example\newline Backslash and >>> "line1 \
newline ignored line2 \
line3"
'line1 line2 line3'\\ Backslash (\) >>> print("Honey\\Sugar")
Honey\Sugar\' Single quote(') >>> "He\'s Property"
"He's Property"\"\" Double quote (") >>> "He is 5\" tall"
'He is 5" tall'\a ASCII Bell/Alert >>> print("a \a b")
(BEL) a b\b ASCII Backspace >>> print("a \b b")
(BS) a b\f ASCII Formfeed >>> print("a \f b")
(FF) a b\n ASCII Linefeed >>> print("Name\nJohn\nBob")
(LF) Name
John
Bob\r ASCII Carriage >>> print("a \r b \r c")
Return (CR) a b c\t ASCII Horizontal >>> print("Bello\tOsagie")
Tab (TAB) Bello Osagie\v ASCII Vertical >>> print("Hello \v Bello!")
Tab (VT) Hello Bello!\ooo Character with >>> print("\110\145")
octal value ooo He
>>> print("\043")
##\xhh Character with >>> print("\x48\x65")
hex value hh He
>>> print("\x23")
#
\N{name} Character named >>> print(u"\N{DAGGER}")
name in the †
Unicode database\uxxxx Prints 32-bit hex >>> print(u"\u041b"))
value Unicode Л
character\Uxxxxxxxx Character with 3 >>> print(u"\U000001a9")
2-bit hex value Ʃ
xxxxxxxx. Exactly
eight hexadecimal
digits are required.
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
Indices may also be negative numbers, to start counting from the right:
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:]
is always equal to s
:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labelled i and j, respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3]
is 2.
Attempting to use an index that is too large will result in an error:
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
However, out of range slice indexes are handled gracefully when used for slicing:
>>> word[4:42]
'on'
>>> word[42:]
''
Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:
>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
If you need a different string, you should create a new one:
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
The built-in function len()
returns the length of a string:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
Boolean — help('BOOLEAN')
View Image>>> # Boolean - True, False
>>> # Boolean in Python is either True or False
>>> # A different data type can be converted to a boolean
>>> # Boolean conversion is done with the bool() function
>>> # True can be any real number except that False is 0
>>> # True can be any string except that False is am empty string ('')
>>> # True numbers or string can be arguments in the bool() function
>>> true_boolean, false_boolean = True, False
>>> true_boolean, false_boolean
(True, False)
>>> bool(3 + 14j), bool(0)
(True, False)
>>> bool('A text'), bool('')
(True, False)Try It Here
Boolean is used in conditional statements to check inputs that are True.
Objects Identity — help(id)
Like said earlier objects can be values and variables contain data types which can be assigned to a variable. In Python, each object has an id() function assigned to it. The built-in function id()
returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory, although this is specific to the Python implementation and the platform being used.
>>> '''Note: Every object has an identity, a type and a value. An object’s
*identity* never changes once it has been created; you may think of it
as the object’s address in memory. The "is" operator compares the
identity of two objects; the "id()" function returns an integer
representing its identity.'''
Theis
operator compares the identity of two objects.
View Image>>> person1 = 'angel'
>>> person2 = 'andela'
>>>
>>> id(person1)
55907712
>>> id(person2)
55907904
>>> person1 is person2
>>> False
>>> person1 is 'angel'
True
>>> person2 is 'andela'
True
>>>
>>> age1 =25
>>> age2 = 34
>>> id(age1)
1807836720
>>> id(age2)
1807836864
>>> age1 is age2
False
>>> age1 is 25
True
>>> age2 is 34
True
2. Function
So far we’ve only seen pre-defined functions
or built-in functions
like help()
, str()
, print()
etc.
Apart from built-in functions, functions can also be created by users. This is called user-defined function
Creating a user-defined function starts by defining the function with the def
keyword like so def function_name():
. The parenthesis maybe empty or may contain parameters. Everything after defining the function (that is after the def function_name():
) must be indented. The indentation must also be consistent.
A function is a block of code designed to perform a particular task.
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Parameters allows arguments to reference it when a function is to be called. This is done by passing values to the arguments.
See example below:
para_1, para_2,..., para_n
are the parameters, var1, var_2
are the variables and arg_1, arg_2, arg_3
are the arguments.
In the code below shows a demo, copy the code in a file
or console and replace each parameter para_1, para_2, para_3
with any number. Also, maintain the indentation. Indentation occurs after the semi-colon (:
).
Demo:
def function_name(para_1, para_2, para_3):
var1 = para_1 + para_2 + para_3
var2 = para_1 * para_2 * para_3
print(var1, var2)function_name(arg_1, arg_2, arg_3) def function_name(para_1, para_2, para_3):
var1 = para_1 + para_2 + para_3
var2 = para_1 * para_2 * para_3
print(var1)
print(var2)function_name(arg_1, arg_2, arg_3)def function_name(para_1, para_2, para_3):
var1 = para_1 + para_2 + para_3
var2 = para_1 * para_2 * para_3
return var1, var2function_name(arg_1, arg_2, arg_3)
The semi-colon creates a block code. Within the function, declaration indentation must be maintained. By default to create an indentation you click four spaces or a tab on your keyboard. A function declaration within another function declaration will need eight spaces and two tabs from the left margin. Python IDLE automatically creates this indentation for you.
Note: You can choose any number of indentation but make sure it is consistent otherwise Python will pop up a syntax error — expected an indented block
or SyntaxError: inconsistent use of tabs and spaces in indentation
A parameter is a place holder for arguments in a function definition. When a function is called the arguments are data passed to the parameter(s). A parameter is like a variable and an argument is like a value — just like assigning a value to a variable.
Note: function name is also called an identifier.
Arguments can be value or data — string, int, float e.t.c.
Up till now, we have been using a function to output values of our variables print()
function. Values are passed to the parenthesis in order to execute them. We can think of arguments in a similar way as values passed in a function call.
If you are using an interactive console or shell, the environment with the command prompt (>>>
) then the print() function is optional to output values line upon line.
Try it here
Functions call can be done outside a function scope to return or output result. This makes called function behave like a global variable.
What then is Global Variable?
A Global variable can be used anywhere in the console or python environment — that is a global variable have global scope. They can be accessed within and outside the function scope.
What is a Local Variable?
A local variable can only be used within a function scope. A local variable has local scope.
Since local variables are only recognized inside their functions, variables with the same name can be used outside the function or in different functions but this can cause confusion as your program or application grows. It is therefore advisable to use different variable names.
Local variables are created when a function starts and deleted when the function is completed. If you try to access a local variable in global scope, you will be prompted an error message.
Let’s take this examples — limiting our operation to addition, subtraction, multiplication and division.
Try it here
Functions can also be used as a variable — We can think of functions outside a function scope as a global variable. This means that a function can be used in expressions or can be stored as value to a variable.
To use a function as a value to a variable we must have returned (return statement) the called function in our function scope.
Try it here
Try it here
Notice the print() function in our declared or defined math_operation() function. When the print() function was used four times in our console it outputted four values on different lines. The return (when python reaches the return statement, the function will stop executing) keyword exit our function and return values when called in a single line.
In the examples below the global variable is arithmetic_operation while the local variables are addition, subtraction, multiplication and division. The local variable can’t be accessible outside of the defined function, math_operation(a, b, c).
If you try to access any of the local variables in the global scope, an error is prompted.
The example above shows that once a local variable leaves a function scope, they can’t be accessible in a global scope. The most important message is always in the last line — NameError: name ‘multiplication’ is not defined.
We can also have a function in a function. One application of enclosing functions is to make your function private or hidden to the global scope. This feature is called closure.
The closure has a feature in python where an inner function has access to the outer (enclosing) function’s variable — a scope chain.
The closure has three scope chains: it has access to its own scope — variables defined between its colon. It has access to the outer function’s variables. It has access to the global variables
Try it here
In the example above, the arithmetic_operation() has access to the math_operation() variables but it behaves like a local function in a global scope. The math_operation() will only give us a function definition of both functions — function math_operation and function arithmetic_operation, <function math_operation.<locals>.arithmetic_operation at 0x032CDC00>. This function definition gives us a hint that we missing another parenthesis. The math_operation function can be accessible if two parentheses are provided — math_operation()(). We had to exit the inner function first (arithmetic_operation()) then exit the outer function (math_operation()) with the return keyword.
The operation variable is assigned a value math_operation() in the global scope and we called the entire function using this variable as a function name — operation().
Arithmetic operations are not the only thing we can do in a function, well we can do a lot of other operations or tasks.
See example below:
Try it here
Function declaration allows passing of default argument(s) to parameter(s). This means when the function is called, the arguments to these parameters can be omitted.
A default parameter can be overridden if an argument is provided for the default parameter in the function call such as — my_name(‘John’, ‘Doe’, 34). Here 34 overrides the default argument for the age of 25 in the example below:
Try it here
age = 25: Here age is a default parameter which has argument or value 25.
The parenthesis after the return keyword is optional. You can only return a data once with or without a parenthesis to exit a function.
In python, strings are joined or concatenated by using the plus sign (+).
What actually is the return keyword doing anyway?
The return keyword is used to exit a function and return a value (when called by the function). See the example below. Notice that statements after the return line will not be executed:
Try it here
To learn more on built-in functions type help('FUNCTIONS')
Help Function
Apart from using the help() function on objects or data types, the help() function can also be used to provide helpful messages on modules, keywords, symbols, topics.
Type help() in the Python console as shown below.
Notice the message generated by the help() function above
To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics".
You can choose from the list of module names and check it’s a description. For example the math module. See the example below
Maybe you are not sure of the Python built-in class, data type etc. you can do the following steps:
help(0)
→help(0"click the 'Tab' key")
or help(0)
→help(0"click the 'Tab' key")
Type any number e.g. 0 then immediately after the number (with no space) click the “TAB” key on your keyboard as shown above. Any number can be used.
If you have done that you will see a list of built-in class, types then select the one you are looking for e.g. slice help(slice)
. Most of them in the list are functions and error names.
Instead of 'Tab' key
key you can use Ctrl + Space
Input Function
We have seen in the examples so for that the print() function output result. There is also another function called the input() function which get input from the user. The function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped). Since the input function always returns string one can perform data type conversion from string to int, float, bool etc.
Method
A method is a like a function. A method can be identified as object_name.method_name()
method_name() is the method name or method
while object_name is the object name or object or data type. One may also write it as object_name.function_name()
. But because the function_name()
runs on an object it is called a method()
instead. So far we haven’t used any method. All we have used so far are functions. A function is a first class object. A method is an object when it is bound with the object by the period (.
). A method can be a pre-defined function or built-in function. The help()
on most object will give a list of built-in methods — help(object) like help(str)
, help(list)
etc. If you try this on any help(method) you are more likely to get an error message. For a string method bound to a method looks like str.method()
. This is the same for other data types like int, list, tuple, etc. For example list.method()
. In general since data types are object we can also write data_type.method_name()
.
object
→.
→immediately click the 'tab' key
→select method from the list
Or
object
→.
→click the 'Tab' key
→wait a few second to see the list of methods
Instead of Tab
you can us Ctrl + space
import math
math.sqrt(64) //8.0
Type any number e.g. 0 then immediately after the number (with no space) click the “TAB” key on your keyboard as shown above.
So far we have seen that a function can be a method but a method can’t be a function. Data-types also be a module. We will see more of modules later.
See the example below:
Example of built-in method are count(), append() etc.
A user defined method is a function in a class scope. Below C is an object. Line 1 is the class object (class C:
)
class C:
def method(self)
pass
c = C()
In line 2, def method(self)
the function name is considered a method because the function is defined in a class namespace.
In line 5, where c = C()
, c is the new object .
To learn more on built-in methods type help('METHODS')
3. Control Flow: conditional statements
“If” uses an expression to evaluate whether a statement is True or False. If it is True, it executes what is inside the “if” statement. For example:
10 is greater than 4, so the “print” code is executed. Notice the short hand If.
The “else” statement will be executed if the “if” expression is false.
The short hand if..else makes our code shorter.
You can also use an “elif” statement if the if and else statement are false.
See example below:
Boolean — True and False values are used to evaluate condition statements. If the statement is true output result, otherwise it is false ignore the output.
Try it here
Logical operators — and , or, not
Logical operators are used to combine conditional statements:
and — Returns True if both statements are true
or — Returns True if one of the statements is true
There’s also one more logical operator in python which is the not keyword — It basically just reverses a boolean value (True to False or False to True). Let’s reverse the above example using the not operator.
not — Reverse the result, returns False if the result is true.
The else statement evaluates true when the if or elif conditions are false.
In the example below we used the if and else statement. This means that if the condition is false, else statement evaluates result to true. Anytime a condition is true it gets printed out in the console or terminal.
Let’s see the logic behind this operation.
Logical and operator
Try it here
Logical or operator
Try it here
Try it here
Try it here
Try the examples above on your own using the short hand If..else
Let have a more practical example of what we have learned so far. If you are using the official python console create a new file and save file name with the .py extension — For example (my_file_name.py)
If the official python isn’t yet downloaded on you PC, click here then install it.
How to run python module or file:
Search for python IDLE → File → New File → Save → (save file with extension .py — e.g. myfile.py) → Test the code — print(‘Hello World’) or enter the code below in File → Run → Run Module
Do the above steps in the examples below:
The above code is written in Python Module
The result will be produce in Python shell
See more examples below:
Here is the output of Example I:
Here’s the same example but using return keyword instead:
Output of Example II:
Try it here
Example III
Example II can also be written as below — using return keyword in each block scope. Just know that anytime we use return in a function scope or block scope we actually exiting the function:
Try it here
In the examples above, we imported the random module in our console (import random). The imported random keyword is global (since it is out of the function scope) so it can be used anywhere in the global scope. This imported module is simply a random number generator. The random module generates random numbers which we can specify the range e.g. random.randint(13, 55) — includes both ends (13 and 55). The random number range from 13 to 55, stored in our variable, age in our function, eligible_voters(). The age variable is passed in each of our if, elif, else statements in order to confirm age of each voters (confirm_voter_age) according to the random age generated of each voters. The return keyword in Example III is used to exit each scope of the if, elif and else statement — This effectively allow us to exit the function at once as in Example II.
Also because we can only concatenate (join) a string and a string together, age is converted to a string, str(age) — casting. Note that each statement has confirm_voter_age variable which stores string values and their values varies in age according if voter is a teenager, youth or an adult — even if we didn’t specify the age for adult we can deduce that adults age are in range 31 to 55. The adult voters age is the default voter age if the if and elif conditions fail (false) — Notice the age range attached to them in our if, elif, else statement condition.
We used the print() functions to output our confirm_voter_age variable in each statement condition (Example I). We also did the same thing in Example II and Example III, but with a return keyword which breaks out or exit the function, eligible_voters() in order to determine which confirm_voter_age value to output.
Another very important thing of functions is to invoke or call our function — eligible_voters(‘’). Without calling the function we can’t see the output — meaning print() and return keyword will be of no use. The eligible_voters(‘’) — notice the quote in the parenthesis. We can also call the function like so — eligible_voters(str()). We have to use quotation marks because we have a parameter confirm_voter_age in our defined (declared) function — eligible_voters(confirm_voter_age), but we can also see the parameter as a variable in our function more than once (thrice). This mean our parameter in our function declaration is also a variable which has string value (‘’). Remember strings are texts enclosed in single or double quotation marks. Therefore we just pass ‘’ as an argument to our eligible_voters() to let python figure out or know that we already have the argument or variable value as string and we expect a string to be printed out— That Simple!!!
If we didn’t have confirm_voter_age parameter in our function then the function has no parameter — def eligible_voters() and we can call it without the two quotation marks — eligible_voters().
Try it here
You can have multiple elif statements and the default else statement can be optional. See example below:
Output:
Try it here
There are lots of modules in python that is impossible to consider just in this tutorial. Modules in python are code library which are buit-in in python or created by users. Apart from modules, python also has a lot of keywords, symbols. But if you are interested in learning some “modules”, “keywords”, “symbols”, or “topics”
See example below:
Try it here
We see there’s a lot of modules.
To check what a particular module can do e.g. ‘random’
Try it here
With lots of modules or code library, python can do alot.
Let’s see another example:
Alternatively Search and click Python Module Docs you will be granted a local server — localhost.
Let’s consider the datetime module:
Double click the ‘Squeezed text’ or right click and view
Try it here
Let’s take one last module — pip
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: pip is already installed if you are using Python 2 >=2.7.9 or Python 3 >=3.4 downloaded from python.org or if you are working in a Virtual Environment created by virtualenv or pyvenv. Just make sure to upgrade pip.
Python version 3.4 or later, PIP is included by default.
For example:
You may do the examples below if you are using the latest python version, but the latest version already has pip installed by default.
If you have pip by default and you wish to upgrade do the following:
Type help(‘modules pip’) in your python environment. Now that is alot.
Let’s create a pip module:
STEPS
Click here→Copy everything in the page→paste it in your python IDLE File →save file with the .py extension(e.g. pip.py or saveasanything.py)→Run →Run Module
Try it here
I. Click here→Copy everything in the page as shown above
Save it anything but with the .py extension(saveasanything.py)
II. Paste it in your Python IDLE file as shown above.
III. Run the file (save file with the .py extension(e.g. saveasanything.py)→Run →Run Module) as shown above.
Note alternatively, you can upgrade pip in your terminal. See example below:
Do the help(‘saveasanything’)
Instead of import saveasanything you can shorten the module name.
Note when importing if file is saved as saveasanything.py then we import using the file name or module.
Check the module you just created — Notice the arrow below:
Note this newly created module (saveasanything) is only available to your Personal Computer (other users can import your module), others are built-in modules.
What is a Package?
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Note if you need a pip package to be installed go to the command prompt to install the package
pip install ‘package’ — e.g. pip install camelcase
Note: If you wish to uninstall camelcase use command pip uninstall camelcase.
Now go to python IDLE and do the following:
Now on your own create your own module on your PC Python IDLE file:
I. Copy the code here to your python IDLE file
II. Save the file
III import module to your console
Try it here
Find more packages here and Learn about installing packages.
Assignment Operators
Before we look into Looping / Iteration, let’s see what assignment operators looks like.
We have already come across assignment operators in this tutorial.
For example instead of writing x + y = 1, one can write in the form x += y.
See example below:
4. Looping / Iteration
In python, we can iterate in different forms. Let’s talk about two: while and for loop.
We often need to repeat actions.
For example, outputting goods from a list one after another or just running the same code for each number from 1 to 10.
Loops are a way to repeat the same code multiple times.
If we are to print the same code over and over this will just be tiresome and sometimes impossible to do. Since the code performs the same task or action, there’s a shorter way of avoid code repetition as a good programmer.
For example take a look at this general loop algorithm
Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ …
That is, begin executes once, and then it iterates: after each condition test, body and step are executed.
See example below:
One can tell this is a bad coding practice which is hard to maintain. What if we wanted to loop till a thousand or even more.
Let’s take a look at a shorter and better way of doing the same code above.
While Looping: while the statement is True, the code inside the block will be executed. So, this code will print the number from 1 to 5.
The while loop needs a “loop condition.” If it stays True, it continues iterating.
A single execution of the loop body is called an iteration. The loop in the examples above makes five iterations.
If start_count += 1 was missing from the example above, the loop would repeat (in theory) forever.
Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by while.
Another basic bit of code to better understand it:
Try it here
The loop condition is True so it keeps iterating — until we set it to False. If it doesn’t see the the boolean False, it iterate forever. This can crash your system. Infinite loops can take all of your computer processing power potentially freezing your computer. It is something to avoid.
On your own reverse the iteration. That is begin iteration at 5 and end at 1.
Hint — Use the greater than or equal to operator (>=) in your statement condition and the decrement operator (-=) to step down each iteration.
For Looping: This example is like the while loop example we did earlier except that the code is shorter. for loop in python uses the range keyword to determine when the loop will start and stop.
See? It is so simple. The range starts with 1 and goes until the 6th element (5 is the 5th element). When the loop encounters the 6th element, it treats it as a boolean, False and discard it. Hence the 6th element, 6 is not printed.
Try the short hand: for count in range(1, 6): print(count). Short hand occurs generally when we have one statement in our block scope.
In Python 0 represent the False keyword, and 1 represent the True keyword. Try performing mathematical operation with the True, False keyword (e.g. True + True + False * True)
See the example below:
The Break Statement
With the break statement we can stop the loop even if the while condition is true
The Continue Statement
With the continue statement we can stop the current iteration, and continue with the next
Let’s see a more practical example:
Let’s create a simple calculator:
5. Data Structure: List (Arrays), Dictionary, Set, Tuple — Python Collection
List: Collection | Array | Data Structure
A list is a collection which is ordered and changeable. In Python lists are written with square brackets. Allows duplicate members.
Imagine you want to store the integer 1 in a variable. But maybe now you want to store 2. And 3, 4, 5 …
Do I have another way to store all the integers that I want, but not in millions of variables? You guessed it — there is indeed another way to store them.
But maybe you are asking: “How can I get a value from this array?”
Great question. List has a concept called index. The first element gets the index 0 (zero). The second gets 1, and so on. You get the idea.
List is a collection that can be used to store a list of values (like these integers that you want). So let’s use it:
Elements are accessible in an array using index. This feature is due to the fact that the elements are ordered.
It is really simple. We created an array and stored it on my_integers then tried accessing each items or elements, but when accessing items that are out of range in a list, an error message is prompted — IndexError: list index out of range.
Let’s try step the array, my_integers_in_list by 2.
Let’s use another method to produce the same result.
The above example are written in a different format, but the same result.
How do one know when an array or list is out of range?
Great question! Sometimes one might not have the time to count the elements one after the order. There is a built in function that determines the number of elements in an array — len()
Now to get the last index:len(elements in list) — 1
See example below:
Imagine that you don’t want to store integers. You just want to store strings, like a list of your relatives names. Mine would look something like this:
We just learned how Lists indices work. But I still need to show you how we can add an element to the List data structure (an item to a list).
The most common method to add a new value to a List is append. Let’s see how it works:
There is an alternative way to check if an item is in a list and one can access the entire items in a list instead of accessing items one at a time.
See example below:
The break statement in for loop:
Let’s see the effect on list — In the example below us while loop on your own:
The continue statement in for loop:
Let’s see the effect on list
Let’s see a more practical example:
Dictionary: Key-Value Data Structure
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. No duplicate members in a dictionary.
Now we know that Lists are indexed with integer numbers. But what if we don’t want to use integer numbers as indices? Some data structures that we can use are numeric, string, or other types of indices.
Let’s learn about the Dictionary data structure. Dictionary is a collection of key-value pairs. Here’s what it looks like:
Alternatively, we can create a dictionary in the following way:
I created a Dictionary about me. My name, age, and country. Those attributes are the Dictionary keys (property names).
As we learned how to access the List using index, we also use indices (keys in the Dictionary context) to access the value stored in the Dictionary.
In the example, I printed a phrase about me using all the values stored in the Dictionary. Pretty simple, right?
The key is the index pointing to the value. How do we access the Dictionary value? You guessed it — using the key. Let’s try it:
We could also add the key-value pair to an empty dictionary.
As we did with Lists, let’s learn how to add elements to a Dictionary. The key pointing to a value is a big part of what Dictionary is. This is also true when we are talking about adding elements to it:
Accessing items in Dictionary:
The break statement in for loop:
Let’s see the effect on dictionary
The continue statement in for loop:
Let’s see the effect on list:
Set: Collection | Data Structure
You cannot access items in a set by referring to an index, since sets are unordered, the items has no index.
Let’s create a set:
As we did with Lists, Dictionary let’s learn how to add elements to a Set.
Accessing items in set (via looping):
You can not access items in a set by referring to an index, since sets are unordered, the items has no index.
Tuple: Collection | Data Structure
Let’s create a tuple:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. Allows duplicate members.
You can also access tuple items. We can also use index to access an item in tuple. Note in the example below, tuple is created without the parenthesis. This is because in Python tuple can be created with or without parenthesis:
Once a tuple is created, you cannot change its value and you can’t add item(s) either — immutable object
Accessing items in tuple:
The break statement in for loop:
Let’s see the effect on tuple:
The continue statement in for loop:
Let’s see the effect on list:
6. Classes and Objects
Objects are a representation of real world objects like cars, dogs, or bikes. The objects share two main characteristics: data and behavior.
Cars have data, like number of wheels, number of doors, and seating capacity They also exhibit behavior: they can accelerate, stop, show how much fuel is left, and so many other things.
We identify data as attributes and behavior as methods in object-oriented programming. Again:
Data → Attributes and Behavior → Methods
And a Class is the blueprint from which individual objects are created. In the real world, we often find many objects with the same type. Like cars. All the same make and model (and all have an engine, wheels, doors, and so on). Each car was built from the same set of blueprints and has the same components.
Python Object-Oriented Programming
Python, as an Object-Oriented programming language, has these concepts: class and object.
A class is a blueprint, a model for its objects.
So again, a class it is just a model, or a way to define attributes and behavior (as we talked about in the theory section). As an example, a vehicle class has its own attributes that define what objects are vehicles. The number of wheels, type of tank, seating capacity, and maximum velocity are all attributes of a vehicle.
With this in mind, let’s look at Python syntax for classes:
We define classes with a class statement — and that’s it. Easy, isn’t it?
Objects are instances of a class. We create an instance by naming the class.
Here car is an object (or instance) of the class Vehicle.
Remember that our vehicle class has four attributes: number of wheels, type of tank, seating capacity, and maximum velocity. We set all these attributes when creating a vehicle object. So here, we define our class to receive data when it initiates it:
We use the init method. We call it a constructor method. So when we create the vehicle object, we can define these attributes. Imagine that we love the Tesla Model S, and we want to create this kind of object. It has four wheels, runs on electric energy, has space for five seats, and the maximum velocity is 250km/hour (155 mph)
All attributes are set. But how can we access these attributes’ values? We send a message to the object asking about them. We call it a method. It’s the object’s behavior.
This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first gets the attribute value, and the second sets a new value for the attribute.
This is slightly different than defining methods. The methods work as attributes. For example, when we set the new number of wheels, we don’t apply two as a parameter, but set the value 2 to number_of_wheels. This is one way to write pythonic getter and setter code.
But we can also use methods for other things, like the noise of an horn method.
So there we have it:
In Python, we can do that using @property (decorators) to define getters and setters. Let’s see it with code:
And we can use these methods as attributes:
This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first gets the attribute value, and the second sets a new value for the attribute.
Let’s see another example’s
Inheritance
Inheritance provides a way to share functionality between classes.
Imagine several classes, Cat, Dog, Rabbit and so on. Although they may differ in some ways (only Dog might have method bark), they are likely to be similar in others (all having the attributes color and name).
This similarity can be expressed by making them all inherit from a super-class Animal, which contains the shared functionality.
To inherit a class from another class, put the super-class name in parenthesis after the class name
If a class inherits from another with the same attributes or methods, it overrides them.
Inheritance can also be indirect. One class can inherit from another, and that class can inherit from a third class.
The function super is a useful inheritance-related function that refers to the parent class. It can be used to find the method with a certain name in an object’s super-class.
super().spam() calls the spam method of the super-class.
Modules?
Consider a module to be the same as code library.
A module is a a file containing a set of functions you want to include in your application
Creating a Module
To create a module just save the code you want in a file with the file extension .py
Save this code in a file named multiplicationanddivisiontable.py:
We just created a module in the multiplicationanddivisiontable.py
Try help(‘multiplicationanddivisiontable’) — with quotation marks around module name and help(multiplicationanddivisiontable) — without quotation marks around module
What about importing module in a console like we did in other built-in modules — like the datetime module:
Example A
Example B
Try it here
Note: help(multiplicationanddivisiontable) has no quotation marks around it because we first imported multiplicationanddivisiontable in Example A then used the help() function on module in Example B. If we were to use help function first before importing then we write help(‘multiplicationanddivisiontable’) — module with quotation marks. This is applicable to built-in modules too.
Try help(‘multiplicationanddivisiontable’) — with quotation marks around module name and help(multiplicationanddivisiontable) — without quotation marks around module
Try it here
To learn more about python click here
To learn more about python programming click here
I hope this write up is helpful. Remember to give give a feedback or give it a clap, follow and share.