21
Python Basics, Python 101!
Python is an interpreted, object oriented ,dynamically typed, high level programming language. This means that instead of executing all of the source code at once, python executes it line by line. Its high level built-in data structures combined with dynamic typing make it suitable for rapid application development.
Python has applications in a wide range of areas including:
Artificial intelligence and machine learning.
Web development
Game development
Digital signal processing
A datatype is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data.
In python there are a variety of data types including strings, float, int, boolean.
A string is a collection of characters enclosed in quotation marks .It could be double ("")or single ('')quotation marks but one must ensure that they don't mix them up.
x = "hello world"
A float is a decimal number
num_float = 0.42
An int is a number without any decimals
num_integer = 25
Boolean has two types; true or false.
You can easily get the data type of a variable in python using the type()
function
type(x) will return str data type.
Python is made up of a variety of data structures some inbuilt and some can be user defined.
Data structures are code structures that define how data is stored and organized.
Python has four built-in data structures i.e. lists, dictionaries ,tuples and sets.
A List is an array-like data structure that contains an ordered collection of items.
ordered means that every item in a list has a position.
Lists are mutable (can be changed).
A list is created by defining a list name and the items are put in square brackets.
For example
my_list = []
The items are separated by comas.
my_list = [a,b,c,d]
If you want to get an element from a list you use zero based indexing, meaning that the first element is at position 0
get_first_item = my_list[0]
This will return the first item in the list which is a.
Lists have many methods which can be used to perform operations on them.
For example
append()
which is used to add an element at the end of the list
insert()
which is used to add an element at a specified position.
copy()
which is used to return a copy of the entire list.
A tuple is like a list but it is immutable meaning it cannot be changed once it's declared. Tuples are also ordered meaning that they have a defined order and it will not be changed. A tuple is declared using parenthesis ().
my_tuple = (oranges,mangoes,apples)
It's also possible to declare a tuple with one element. To do this, ensure that you add a coma after the element in parenthesis so that python can know that it's a tuple.
one_tuple = (banana,)
If you never want to change your elements they should be declared in a tuple since it's immutable.
Sets are unordered collections meaning that the elements follow no specific order (are unindexed). They are declared with curly brackets {}.
Sets are mutable, they can be changed, items can be removed, added or replaced.
my_set = {1,2,3,4,5}
Sets are used when we need to confirm the presence or absence of an item in a set. In other words, they are used for membership tests.
A dictionary is a collection of key/value pairs. A dictionary is initialized using curly brackets {} and filled with colon : separated keys and values (key : value). Dictionaries are ordered and changeable .
my_dict = {
"Name": "James",
"age":25,
"Nationality": "Ugandan"
}
Note that the keys in dictionaries can not be duplicated.
A function is a set of instructions that you want to use repeatedly in a program. Instead of writing these instructions every time you need them, they can easily be written in a function once and for all. The function just needs to be called in case you need to use the instructions.
A function is created using the def key word.
def my_function():
print("Hello")
The function can be called by using its name followed by parenthesis
my_function()
Parameters are specified in the function definition by putting them in the parenthesis. If you have more than one parameter, they can be separated using comas
def my_add_function(a,b):
return(a+b)
my_add_function(1,2)
Here a and b are parameters
An argument is what is passed through when calling the function.
1 and 2 are arguments.
Control flow is the order in which a program executes its instructions.
Control flow in python is regulated by control statements and loops.
Python has a variety of logical operators used to perform logic in control flow.
These include:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Often, you need to execute some statements only if some condition holds, or choose statements to execute depending on several mutually exclusive conditions. The Python compound statement if, which uses if, elif, and else clauses, lets you conditionally execute blocks of statements.
Usually if statements are used with logical operators as shown in the example below
a = 12
b = 5
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In the first condition b is less than a so it will print false.
In the second a is not equal to b so it will print false
then in the third it will print 'a is greater than b' since its true.
Remember that in python indentation is very important.
Loops are used to iterate over a sequence.
The key word for is used.
countries = ["Uganda", "Kenya", "Tanzania"]
for x in country:
print(x)
This will print each country.
While loop executes a set of statements as long as a condition is true.
i = 1
while i < 4:
print(i)
i += 1
We can add a break statement to stop the loop even if the while condition is true.
i = 1
while i < 4:
print(i)
if i == 3:
break
i += 1
Using the continue statement, we can stop the current iteration, and continue with the next.
i = 0
while i < 4:
i += 1
if i == 3:
continue
print(i)
I hope this brief introduction was helpful and insightful.