# Python Tutorial¶

Python is a language which prides itself on simplicity of reading and understanding. If you'd like to read more about python go to https://en.wikipedia.org/wiki/Python_(programming_language) !

If you'd like to read further than this, or a more basic guide I would recommend: https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3

Here's an example python program to print something on the screen:

# 1. Arithmetic¶

Like every programming language, Python is a good calculator. Run the block of code below to make sure the answer is right!

The order of operations you learned in school applies, BEDMAS (brackets, exponents, division, multiplication, addition, subtraction):

Numbers are valid Python code as are the common operators, +, /, * and -. You can write different types of numbers including integers, real numbers (floating point) and negative integers.

Since 42 is literally 42, we call these numbers literals. You are literally writing number in your Python code.

# 2. Variables¶

In python, variables are similar to C, Java and other languages - they store a certain value. Specifically, in python variables do not have a type. So, a string can also become an integer, and then even into a function! Literals are given types of string, integer, float, lists, objects, etc. But the variable's type can change.

# 3. Exceptions in Python¶

Python only understands certain code. When you write something Python doesn't understand it throws an exception and tries to explain what went wrong, but it can only speak in a broken Pythonesque english. Let's see some examples by running these code blocks

Python tries to tell you where it stopped understanding, but in the above examples, each program is only 1 line long.

It also tries to show you where on the line the problem happened with caret ("^").

Finally it tells you the type of thing that went wrong, (NameError, SyntaxError, ZeroDivisionError) and a bit more information like "name 'gibberish' is not defined" or "unexpected EOF while parsing".

Unfortunately you might not find "unexpected EOF while parsing" too helpful. EOF stands for End of File, but what file? What is parsing? Python does it's best, but it does take a bit of time to develop a knack for what these messages mean. If you run into an error you don't understand please ask.

# 4. Strings¶

We have already seen a string literal in Python, "Hello, World!"

Text literals are surrounded by quotes. Without the quotes Hello by itself would be viewed as a variable name. You can use either double quotes (") or single quotes (') for text literals. Note that in python a character is just a string with 1 character and isn't a different data type.

Let's use strings:

Strings in Python are a bit more complicated because they have their own functions (operations to perform on them) which we can call to modify them:

To convert another data type like float, integer, etc into a string, you can use the str() function:

#### Indexed by Zero¶

For better or worse, everything in Python is index by 0 like C/C++ or Java. We will see this over and over again but for now if you call format like this:

We would call "I" the 0th string passed into the function .format() and 'Python' the 1st.

#### Multi line strings¶

Frequently you will have a string which spans multiple lines. There are 3 ways to handle this in python:

• Use a backslash
• Triple quotes

## Exercise: Use the help() function¶

To find more about a specific enity in python, simply do help(<entity>). Try it out!

• Find the help for the find() function we used earlier by typing help("abcd".find). How many arguments does it have ?
• Find the help for the find() function and check what the function split() does ?

## Exercise: String functions¶

• Use the <str>.replace() function replace the text in "Hello world" to "Hello python"
• Use the <str>.zfill() function to take an integer and pad it with zeroes to make it 5 characters long: Define a = 512 and convert it to "00512"
• Use the <str>.startswith() function to check if a string starts with a vowel. Run it on "python" and "india".

# 5. If Else¶

Like all languages, Python allows us to conditionally run code.

To have an if condition we need the idea of something being true and something being false. We have True or False as "boolean" values. True would represent OK where as false would represent No or Cancel.

We can write expressions with operations too.

In order to write an "if" statement we need code that spans multiple lines

if condition:
print("Condition is True")
else:
print("Condition is False")



Some things to notice. The if condition ends in a colon (":"). In Python blocks of code are indicated with a colon (":") and are grouped by white space. Notice the else also ends with a colon (":"), "else:". Let's try changing the condition and see what happens.

About that white space, consider the following code:

if condition:
print("Condition is True")
else:
print("Condition is False")
print("Condition is True or False, either way this is outputted")



Since the last print statement isn't indented it gets run after the if block or the else block.

You can play with this. Try indenting the last print statement below and see what happens.

You can also use "and", "or", "not" to combine conditions (No ugly && and || here):

True and True is True
True and False is False
False and True is False
False and False is False
not True is False

## Exercise - Boolean values¶

Below change the values of the three variables to make the entire "if condition" true.

# 6. Lists¶

So far we have numbers, strings, and conditional if statements. Now for our first container - a list.

A list in Python is just like an array or a linked list. They have a defined order and you can add to it or remove from it. Let's take a look at some simple lists.

List literals are all about square brackets ("[ ]") and commas (","). You can create a list of literals by wrapping them in square brackets and separating them with commas.

As python doesn't care too much about data types, you can even mix different types of things into the same list; numbers, strings, booleans (unlike arrays)

We can put variables into a list and set a variable to a list.

Like strings, lists have their own operations. "append" is an interesting one. "append" lets you add an item to the end of a list.

There is that 0 indexing again. The first element of the list is given index value 0.

#### Length¶

We can also find the lenght of the list using the len function:

#### Splicing¶

Parts of a list can also be gotten using the splice operator. To use the splice operator, square brackets with color (:) is used:

## Exercise - Use the functions .join() and .split()¶

• Use the <str>.join() function to join a list of items using a comma: Convert ["bread", "butter", "jam"] -> "bread, butter, jam"
• Use the <str>.split() function to split a string into a list: Convert back the earlier "bread, butter, jam" -> ["bread", "butter", "jam"]

# 7. Loops¶

Indexes are useful, but lists really shine when you start looping.

Loops let you do something for each item in a list. They look like this:

for item in my_list:
print(item)  # Do any action per item in the list



"for" and "in" are required. "my_list" can be any variable or literal which is like a list. "item" is the name you want to give each item of the list in the indented block as you iterate through. We call each step where item has a new value an iteration.

In python, we don't use constructs like for ( int i = 0; i < maximum; i++ ) which are just confusing, rather we create a "range" of integers from 0 to maximum and loop over that:

And then we can use that with a loop to print a list of squares.

# 8. Dictionaries¶

We have come a long way! Just one more section. Dictionaries are another container like lists, but instead of being index by a number like 0 or 1 it is indexed by a key which can be almost anything. The name comes from being able to use it to represent a dictionary.

List literals use square brackets ("[]") but dictionaries use braces ("{}").

{"wikipedia.org": "The free encyclopedia",
"wikisource.org": "The free library"}



In a dictionary the key comes first followed by a colon (":") than the value then a comma (",") then another key and so on. This is one situation where a colon doesn't start a block.

We can loop over the keys in a dictionary to list all of our definitions...

In fact, dictionaries can contain any type of values. Hence, you can have a list as the value of a dictionary:

We can also get the keys and values as lists:

## Exercise: Loop over the keys, values, and items¶

• Loop over a dict using for key in <dict>: and print all the keys. Verify that the same result is got when using for key in <dict>.keys().
• Loop over the values of a dict by first getting all the values using the <dict>.values() function.
• Loop over the keys and values of a dict by requesting 2 items from the list. Do for key, val in dict.items(): and try printing both the key and value side by side.

# 9. Functions¶

To avoid code repetition and to break code into smaller intelligible blocks, functions are useful. A function takes in certain variables (arguments) and gives out a return value. The arguments and return value do not need to define a data type again, as python isn't too worried about data types.

A function is defined using the def keyword:

def <function name>(<arg1>, <arg2>, <arg3>, ..., <argN>):
<function body>
return <value to return>

Because there's no data type for the arguments and return type, we can give strings, ints, floats, lists, etc. Anything that supports the + operator in our example. But if the arguments given cannot be operated on by + it gives an error. And it is the job of the developer of the function to ensure that the arguments given are sane:

Python also supports assigning values using the argument name. When using argument names (also called keyword arguments - kwargs) the order of the arguments do not matter as the name of the argument is used. This gives flexibility, as you don't have to remember which argument comes first and which comes second! Let's see it in action:

Not all functions need to return a value. And by default if a return value is not given, it returns None.

Functions can also have default values for arguments:

## Exercise - Fibonacci function¶

Write a function that prints the values of the fibonacci series until a given maximum value. For example, print_fibonacci(10) would print:

>>> print_fibonacci(10)
1, 1, 2, 3, 5, 8

# 10. Classes¶

Python also has Object Oriented Programming (OOP) in it's structure. A class is a template which holds class variables and functions (methods) and operates on the class itself.

To use a class, objects which conform to the class template need to be created:

The __init__() function is the class constructor and can not return anything. The first argument self is the object that's being created. Hence, in our above class, when the object is created, it has 2 member variables url and description which are assigned to empty string ("") in the constructor.

Other than the variables created in the class, python can dynamically add more variables in the class:

Classes can also define functions which can be used to perform functions using the object variables.

Object methods start with the keyword self normally. When w1.function() is used, the object before the period (w1) is passed to function()'s first argument. Hence, function() would be defined as def function(self): where self is a reference to the object itself.

Here's an example:

## Exercise - Create a WebSite object for each item in the wiki_sites dictionary¶

Loop over every (key, value) pair in the dictionary wiki_sites and create a list of WebSite objects using the WebSite class.

• The key of the dictionary should be stored in the url of the object.
• The value of the dictionary should be stored in the description of the object.

## Exercise - Create a class to store a mediawiki page¶

Create a class which can store a mediawiki page (has content and name of the page) and create 2 functions to:

1. Check if the page is empty (the content is an empty string ""): <obj>.empty() which returns True or False
2. Generate the URL of the page using a base url: <obj>.url() returns "wikipedia.org/wiki/<page name>")

Below you will find some example code to test your class