What is Python?

Python is a high-level programming language created in 1991 by Guido van Rossum. It is known to be easy to use and language of choice for scripting and rapid application development in many areas on most platforms.

What can Python do?

Why Python?

Syntax

Python Syntax compared to other programming languages:

Python Indentations

Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important.

Python uses indentation to indicate a block of code.

if 5 > 2: print("Five is greater than two!")

Python will give you an error if you skip the indentation.

Comments

Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:

# This is a comment. print("Hello, World!")

Docstrings

Python also has extended documentation capability, called docstrings.

Docstrings can be one line, or multiline. Docstrings are also comments:

Python uses triple quotes at the beginning and end of the docstring:

"""This is a multiline docstring.""" print("Hello, World!")

Variables

Creating Variables

Unlike other programming languages, Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x = 5 y = "John" print(x) print(y)

Variables do not need to be declared with any particular type and can even change type after they have been set.

x = 4 # x is of type int x = "Sally" # x is now of type str print(x)

What happens is that x had the reference of the value 4 but lost it by receiving the reference of Sally. Because the reference is lost, the value 4 is also lost.

Variables Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:

Remember that variables are case-sensitive

Output Variables

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

x = "awesome" print("Python is " + x)

You can also use the + character to add a variable to another variable:

x = "Python is " y = "awesome" z = x + y print(z)

For numbers, the + character works as a mathematical operator:

x = 5 y = 10 print(x + y)

If you try to combine a string and a number, Python will give you an error:

x = 5 y = "John" print(x + y)

Numbers

There are three numeric types in Python:

Variables of numeric types are created when you assign a value to them:

x = 1 # int y = 2.8 # float z = 1j # complex

To verify the type of any object in Python, use the type() function:

print(type(x)) print(type(y)) print(type(z))

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length:

x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z))

Float

Float, or “floating point number” is a number, positive or negative, containing one or more decimals:

x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z))

Float can also be scientific numbers with an “e” to indicate the power of 10:

x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z))

Complex

Python understands complex numbers:

x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z))

Casting

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions.

Cast to Int

int() constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number):

x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3

Cast to Float

float() constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer):

x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2

Cast to String

str() constructs a string from a wide variety of data types, including strings, integer literals and float literals:

x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0'

Strings

String literals in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

Strings can be output to screen using the print function. For example: print("hello").

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!" print(a[1])

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!" print(b[2:5])

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! " print(a.strip()) # returns "Hello, World!"

The len() method returns the length of a string:

a = "Hello, World!" print(len(a))

The lower() method returns the string in lower case:

a = "Hello, World!" print(a.lower())

The upper() method returns the string in upper case:

a = "Hello, World!" print(a.upper())

The replace() method replaces a string with another string:

a = "Hello, World!" print(a.replace("H", "J"))

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']

Operators

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

Arithmetic

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y

Assignment

Assignment operators are used as shorthand to assign values to variables:

x = 5 x += 3 # equivalent to x = x + 3 x **= 2 # equivalent to x = x ** 2

Comparison

Comparison operators are used to compare two values:

Operator Description Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Logical

Logical operators can be used to combine conditional statements:

Operator Description Example
and Returns True if both statements are true x and y
or Returns True if one of the statements is true x or y
not Reverse the result, returns False if the result is true not y

Membership

Operator Description Example
in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y

Collections

Three collection data types of the Python programming language are introduced:

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.

List

A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

Create a List

fruits = ["apple", "banana", "cherry"] print(fruits)

Access Items

You access the list items by referring to the index number.

Print the second item of the list:

fruits = ["apple", "banana", "cherry"] print(fruits[1])

Change Item Value

To change the value of a specific item, refer to the index number.

Change the second item:

fruits = ["apple", "banana", "cherry"] fruits[1] = "blackcurrant" print(fruits)

Loop Through a List

You can loop through the list items by using a for loop.

Print all items in the list, one by one:

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(x)

You will learn more about for loops in out loops section.

Check if Item Exists

To determine if a specified item is present in a list use the in keyword.

Check if “apple” is present in the list:

fruits = ["apple", "banana", "cherry"] if "apple" in fruits: print("Yes, 'apple' is in the fruits list")

List Length

To determine how many items a list have, use the len() method.

Print the number of items in the list:

fruits = ["apple", "banana", "cherry"] print(len(fruits))

Add Items

To add an item to the end of the list, use the append() method.

Using the append() method to append an item:

fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits)

To add an item at the specified index, use the insert() method.

Insert an item as the second position:

fruits = ["apple", "banana", "cherry"] fruits.insert(1, "orange") print(fruits)

Remove Item

There are two main methods to remove items from a list. The remove() method removes the specified item:

fruits = ["apple", "banana", "cherry"] fruits.remove("banana") print(fruits)

The pop() method removes the specified index, or the last item if index is not specified:

fruits = ["apple", "banana", "cherry"] fruits.pop() print(fruits)

Cast to List

It is also possible to use the list() constructor to make a list:

fruitsAsTuple = ("apple", "banana", "cherry") fruits = list(fruitsAsTuple) print(fruits)

Tuples

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

Create a Tuple

fruits = ("apple", "banana", "cherry") print(fruits)

Access Items

You can access tuple items by referring to the index number.

Return the item in position 1:

fruits = ("apple", "banana", "cherry") print(fruits[1])

Change Item Value

Once a tuple is created, you cannot change its values, they are unchangeable. The following will produce an error:

fruits = ("apple", "banana", "cherry") fruits[1] = "blackcurrant" # The values will remain the same: print(fruits)

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

Print all items in the tuple, one by one:

fruits = ("apple", "banana", "cherry") for fruit in fruits: print(fruit)

You will learn more about for loops in out loops section.

Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword.

Check if “apple” is present in the tuple:

fruits = ("apple", "banana", "cherry") if "apple" in fruits: print("Yes, 'apple' is in the fruits tuple")

Tuple Length

To determine how many items a tuple have, use the len() method.

Print the number of items in the tuple:

fruits = ("apple", "banana", "cherry") print(len(fruits))

Add Items

Once a tuple is created, you cannot add items to it, they are unchangeable. The following will produce an error:

fruits = ("apple", "banana", "cherry") fruits[3] = "orange" # This will raise an error print(fruits)

Remove Item

Tuples are unchangeable, so you cannot remove items from it.

Cast to Tuple

It is also possible to use the tuple() constructor to make a tuple:

fruitsAsList = ["apple", "banana", "cherry"] fruits = tuple(fruitsAsList) print(fruits)

Dictionary

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.

Create a Dictionary

car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(car)

Accessing Items

You can access the items of a dictionary by referring to its key name.

Get the value of the “model” key:

model = car["model"]

Change Values

You can change the value of a specific item by referring to its key name.

Change the “year” to 2018:

car["year"] = 2018

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Print all key names in the dictionary, one by one:

for key in car: print(key)

Print all values in the dictionary, one by one:

for key in car: print(car[key])

You can also use the values() function to return values of a dictionary:

for value in car.values(): print(value)

Loop through both keys and values, by using the items() function:

for key, value in car.items(): print(key, value)

You will learn more about for loops in out loops section.

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword.

if "model" in car: print("Yes, 'model' is one of the keys in car")

Dictionary Length

To determine how many items (key-value pairs) a dictionary have, use the len() method.

Print the number of items in the dictionary:

print(len(car))

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Print the number of items in the dictionary:

car["color"] = "red" print(car)

Removing Items

The pop() method removes the item with the specified key name:

car.pop("model") print(car)

If … Else

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

These conditions can be used in several ways, most commonly in “if statements” and loops.

An “if statement” is written by using the if keyword.

a = 33 b = 200 if b > a: print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that “b is greater than a”.

Indentation

Python relies on indentation, using whitespace, to define scope in the code. Other programming languages often use curly-brackets for this purpose.

If statement, without indentation (will raise an error):

a = 33 b = 200 if b > a: print("b is greater than a")

Elif

The elif keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.

a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that “a and b are equal”.

Else

The else keyword catches anything which isn’t caught by the preceding conditions.

a = 200 b = 33 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 this example a is greater to b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that “a is greater than b”.

You can also have an else without the elif:

a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a")

While Loops

With the while loop we can execute a set of statements as long as a condition is true.

Print i as long as i is less than 6:

i = 1 while i < 6: print(i) i += 1

Remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.

Break Statement

With the break statement we can stop the loop even if the while condition is true:

Exit the loop when i is 3:

i = 1 while i < 6: print(i) if i == 3: break i += 1

Continue Statement

With the continue statement we can stop the current iteration, and continue with the next.

Continue to the next iteration if i is 3:

i = 0 while i < 6: i += 1 if i == 3: continue print(i)

For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters.

Loop through the letters in the word “banana”:

for letter in "banana": print(letter)

Break Statement

With the break statement we can stop the loop before it has looped through all the items:

Exit the loop when x is “banana”.

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) if fruit == "banana": break

Exit the loop when x is “banana”, but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"] for fruit in fruits: if fruit == "banana": break print(x)

Continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next.

Do not print banana:

fruits = ["apple", "banana", "cherry"] for fruit in fruits: if fruit == "banana": continue print(x)

Range Function

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. For example:

for x in range(6): print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

for x in range(2, 6): print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):

for x in range(2, 30, 3): print(x)

The range() and len() functions can be used in order to loop by index and not by element:

fruits = ["apple", "banana", "cherry"] for index in range(len(fruits)): print(index)

Enumerate Function

Sometimes it is useful to loop through the index and element. This can be done using the enumerate() function:

fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(index) print(fruit)

Functions

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

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

def my_function(): print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function(): print("Hello from a function") my_function()

Parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (name). When the function is called, we pass along a name, which is used inside the function to greet the person:

def Greeting(name): print("Hello " + name) Greeting("Dugagjin") Greeting("Mr. President") Greeting("stranger")

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

def sayPlace(country = "Norway"): print("I am from " + country) sayPlace("Sweden") sayPlace("India") sayPlace() sayPlace("Brazil")

Return Values

To let a function return a value, use the return statement:

def doTimesFive(x): return 5 * x print(doTimesFive(3)) print(doTimesFive(5)) print(doTimesFive(9))

Modules

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create 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 mymodule.py:

def greeting(name): print("Hello " + name)

Use a Module

Now we can use the module we just created, by using the import statement.

Import the module named mymodule, and call the greeting function:

import mymodule mymodule.greeting("Dugagjin")

When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc).

Save this code in the file mymodule.py:

person = { "name": "Dugagjin", "age": 104, "country": "Japan" }

Import the module named mymodule, and access the person dictionary:

import mymodule age = mymodule.person["age"] print(age)

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py.

Re-naming a Module

You can create an alias when you import a module, by using the as keyword.

Create an alias for mymodule called mx:

import mymodule as mx age = mx.person["age"] print(age)

Import from Module

You can choose to import only parts from a module, by using the from keyword.

The module named mymodule has one function and one dictionary:

def greeting(name): print("Hello, " + name) person = { "name": "Dugagjin", "age": 104, "country": "Japan" }

Import only the person dictionary from the module:

from mymodule import person print(person["age"])