Python While Loops

 


Python Loops

Python has two primitive loop commands:


while loops

for loops

The while Loop

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


Example

Print i as long as i is less than 6:


i = 1

while i < 6:

  print(i)

  i += 1

Note: 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.


The break Statement

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


Example

Exit the loop when i is 3:


i = 1

while i < 6:

  print(i)

  if i == 3:

    break

  i += 1

The continue Statement

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


Example

Continue to the next iteration if i is 3:


i = 0

while i < 6:

  i += 1

  if i == 3:

    continue

  print(i)

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:


Example

Print a message once the condition is false:


i = 1

while i < 6:

  print(i)

  i += 1

else:

  print("i is no longer less than 6")


Python For Loops

 


Python 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 languages, 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.


Example

Print each fruit in a fruit list:


fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

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:


Example

Loop through the letters in the word "banana":


for x in "banana":

  print(x)

The break Statement

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


Example

Exit the loop when x is "banana":


fruits = ["apple", "banana", "cherry"]

for x in fruits:

  print(x)

  if x == "banana":

    break

Example

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


fruits = ["apple", "banana", "cherry"]

for x in fruits:

  if x == "banana":

    break

  print(x)

The continue Statement

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


Example

Do not print banana:


fruits = ["apple", "banana", "cherry"]

for x in fruits:

  if x == "banana":

    continue

  print(x)

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


Example

Using the range() function:


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):


Example

Using the start parameter:


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):


Example

Increment the sequence with 3 (default is 1):


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

  print(x)

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:


Example

Print all numbers from 0 to 5, and print a message when the loop has ended:


for x in range(6):

  print(x)

else:

  print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by a break statement.


Example

Break the loop when x is 3, and see what happens with the else block:


for x in range(6):

  if x == 3: break

  print(x)

else:

  print("Finally finished!")

Nested Loops

A nested loop is a loop inside a loop.


The "inner loop" will be executed one time for each iteration of the "outer loop":


Example

Print each adjective for every fruit:


adj = ["red", "big", "tasty"]

fruits = ["apple", "banana", "cherry"]


for x in adj:

  for y in fruits:

    print(x, y)

The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.


Example

for x in [0, 1, 2]:

  pass


Python - Add Set Items

 


Add Items

Once a set is created, you cannot change its items, but you can add new items.


To add one item to a set use the add() method.


Example

Add an item to a set, using the add() method:


thisset = {"apple", "banana", "cherry"}


thisset.add("orange")


print(thisset)

Add Sets

To add items from another set into the current set, use the update() method.


Example

Add elements from tropical into thisset:


thisset = {"apple", "banana", "cherry"}

tropical = {"pineapple", "mango", "papaya"}


thisset.update(tropical)


print(thisset)

Add Any Iterable

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).


Example

Add elements of a list to at set:


thisset = {"apple", "banana", "cherry"}

mylist = ["kiwi", "orange"]


thisset.update(mylist)


print(thisset)


Python - Access Set Items

 


Access Items

You cannot access items in a set by referring to an index or a key.


But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.


Example

Loop through the set, and print the values:


thisset = {"apple", "banana", "cherry"}


for x in thisset:

  print(x)

Example

Check if "banana" is present in the set:


thisset = {"apple", "banana", "cherry"}


print("banana" in thisset)

Change Items

Once a set is created, you cannot change its items, but you can add new items.


Python 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:


Example

def my_function():

  print("Hello from a function")

Calling a Function

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


Example

def my_function():

  print("Hello from a function")


my_function()

Arguments

Information can be passed into functions as arguments.


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


The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:


Example

def my_function(fname):

  print(fname + " Refsnes")


my_function("Emil")

my_function("Tobias")

my_function("Linus")

Arguments are often shortened to args in Python documentations.


Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed into a function.


From a function's perspective:


A parameter is the variable listed inside the parentheses in the function definition.


An argument is the value that is sent to the function when it is called.


Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.


Example

This function expects 2 arguments, and gets 2 arguments:


def my_function(fname, lname):

  print(fname + " " + lname)


my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:

Example

This function expects 2 arguments, but gets only 1:


def my_function(fname, lname):

  print(fname + " " + lname)


my_function("Emil")

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.


This way the function will receive a tuple of arguments, and can access the items accordingly:


Example

If the number of arguments is unknown, add a * before the parameter name:


def my_function(*kids):

  print("The youngest child is " + kids[2])


my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.


Keyword Arguments

You can also send arguments with the key = value syntax.


This way the order of the arguments does not matter.


Example

def my_function(child3, child2, child1):

  print("The youngest child is " + child3)


my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.


Arbitrary Keyword Arguments, **kwargs

If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.


This way the function will receive a dictionary of arguments, and can access the items accordingly:


Example

If the number of keyword arguments is unknown, add a double ** before the parameter name:


def my_function(**kid):

  print("His last name is " + kid["lname"])


my_function(fname = "Tobias", lname = "Refsnes")

Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.


Default Parameter Value

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


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


Example

def my_function(country = "Norway"):

  print("I am from " + country)


my_function("Sweden")

my_function("India")

my_function()

my_function("Brazil")

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.


E.g. if you send a List as an argument, it will still be a List when it reaches the function:


Example

def my_function(food):

  for x in food:

    print(x)


fruits = ["apple", "banana", "cherry"]


my_function(fruits)

Return Values

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


Example

def my_function(x):

  return 5 * x


print(my_function(3))

print(my_function(5))

print(my_function(9))

The pass Statement

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.


Example

def myfunction():

  pass

Recursion

Python also accepts function recursion, which means a defined function can call itself.


Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.


The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.


In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).


To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.


Example

Recursion Example


def tri_recursion(k):

  if(k > 0):

    result = k + tri_recursion(k - 1)

    print(result)

  else:

    result = 0

  return result


print("\n\nRecursion Example Results")

tri_recursion(6)


Python Sets



 myset = {"apple", "banana", "cherry"}

Set

Sets are used to store multiple items in a single variable.


Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.


A set is a collection which is both unordered and unindexed.


Sets are written with curly brackets.


Example

Create a Set:


thisset = {"apple", "banana", "cherry"}

print(thisset)

Note: Sets are unordered, so you cannot be sure in which order the items will appear.


Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.


Unordered

Unordered means that the items in a set do not have a defined order.


Set items can appear in a different order every time you use them, and cannot be referred to by index or key.


Unchangeable

Sets are unchangeable, meaning that we cannot change the items after the set has been created.


Once a set is created, you cannot change its items, but you can add new items.


Duplicates Not Allowed

Sets cannot have two items with the same value.


Example

Duplicate values will be ignored:


thisset = {"apple", "banana", "cherry", "apple"}


print(thisset)

Get the Length of a Set
To determine how many items a set has, use the len() method.

Example
Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))
Set Items - Data Types
Set items can be of any data type:

Example
String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set can contain different data types:

Example
A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}
type()
From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>
Example
What is the data type of a set?

myset = {"apple", "banana", "cherry"}
print(type(myset))
The set() Constructor
It is also possible to use the set() constructor to make a set.

Example
Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Python Collections (Arrays)
There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered and unindexed. No duplicate members.
Dictionary is a collection which is ordered* and changeable. No duplicate members.
*As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

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.

Python Lambda

 


A lambda function is a small anonymous function.


A lambda function can take any number of arguments, but can only have one expression.


Syntax

lambda arguments : expression

The expression is executed and the result is returned:


Example

Add 10 to argument a, and return the result:


x = lambda a : a + 10

print(x(5))

Lambda functions can take any number of arguments:


Example

Multiply argument a with argument b and return the result:


x = lambda a, b : a * b

print(x(5, 6))

Example

Summarize argument a, b, and c and return the result:


x = lambda a, b, c : a + b + c

print(x(5, 6, 2))

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another function.


Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:


def myfunc(n):

  return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in:


Example

def myfunc(n):

  return lambda a : a * n


mydoubler = myfunc(2)


print(mydoubler(11))

Or, use the same function definition to make a function that always triples the number you send in:


Example

def myfunc(n):

  return lambda a : a * n


mytripler = myfunc(3)


print(mytripler(11))

Or, use the same function definition to make both functions, in the same program:

Example
def myfunc(n):
  return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))
Use lambda functions when an anonymous function is required for a short period of time.

Python Arrays



 Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.


Arrays

Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library.


Arrays are used to store multiple values in one single variable:


Example

Create an array containing car names:


cars = ["Ford", "Volvo", "BMW"]

What is an Array?

An array is a special variable, which can hold more than one value at a time.


If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:


car1 = "Ford"

car2 = "Volvo"

car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?


The solution is an array!


An array can hold many values under a single name, and you can access the values by referring to an index number.


Access the Elements of an Array

You refer to an array element by referring to the index number.


Example

Get the value of the first array item:


x = cars[0]

Example

Modify the value of the first array item:


cars[0] = "Toyota"

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).


Example

Return the number of elements in the cars array:


x = len(cars)

Note: The length of an array is always one more than the highest array index.Looping Array Elements

You can use the for in loop to loop through all the elements of an array.


Example

Print each item in the cars array:


for x in cars:

  print(x)

Adding Array Elements

You can use the append() method to add an element to an array.


Example

Add one more element to the cars array:


cars.append("Honda")

Removing Array Elements

You can use the pop() method to remove an element from the array.


Example

Delete the second element of the cars array:


cars.pop(1)

You can also use the remove() method to remove an element from the array.


Example

Delete the element that has the value "Volvo":


cars.remove("Volvo")

Note: The list's remove() method only removes the first occurrence of the specified value.


Array Methods

Python has a set of built-in methods that you can use on lists/arrays.


Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.


Python Classes and Objects

 


Python Classes/Objects

Python is an object oriented programming language.


Almost everything in Python is an object, with its properties and methods.


A Class is like an object constructor, or a "blueprint" for creating objects.


Create a Class

To create a class, use the keyword class:


Example

Create a class named MyClass, with a property named x:


class MyClass:

  x = 5Create Object

Now we can use the class named MyClass to create objects:


Example

Create an object named p1, and print the value of x:


p1 = MyClass()

print(p1.x)

The __init__() Function

The examples above are classes and objects in their simplest form, and are not really useful in real life applications.


To understand the meaning of classes we have to understand the built-in __init__() function.


All classes have a function called __init__(), which is always executed when the class is being initiated.


Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:


Example

Create a class named Person, use the __init__() function to assign values for name and age:


class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age


p1 = Person("John", 36)


print(p1.name)

print(p1.age)

Note: The __init__() function is called automatically every time the class is being used to create a new object.


Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.


Let us create a method in the Person class:


Example

Insert a function that prints a greeting, and execute it on the p1 object:


class Person:

  def __init__(self, name, age):

    self.name = name

    self.age = age


  def myfunc(self):

    print("Hello my name is " + self.name)


p1 = Person("John", 36)

p1.myfunc()

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.


The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.


It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class:


Example

Use the words mysillyobject and abc instead of self:


class Person:

  def __init__(mysillyobject, name, age):

    mysillyobject.name = name

    mysillyobject.age = age


  def myfunc(abc):

    print("Hello my name is " + abc.name)


p1 = Person("John", 36)

p1.myfunc()

Modify Object Properties

You can modify properties on objects like this:


Example

Set the age of p1 to 40:


p1.age = 40

Delete Object Properties

You can delete properties on objects by using the del keyword:


Example

Delete the age property from the p1 object:


del p1.age

Delete Objects

You can delete objects by using the del keyword:


Example

Delete the p1 object:


del p1

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.


Example

class Person:

  pass