Categories
Tutorials

Learning Python

Python is a general-purpose programming language, is gaining immense popularity in the field of AI. It’s the go-to choice for companies worldwide to extract valuable insights from their data and maximize its potential through AI-driven solutions.

Unlike other Python tutorials, this is a concise Python 3 programming tutorial for people who think that reading is boring. I try to show everything with simple code examples; there are no long and complicated explanations with fancy words.

This section will get you started with using Python and you’ll be able to learn more about whatever you want after studying it.

Installing Python
Getting started with Python
Variables, Booleans and None
Built-in Function “print”
If, else and elif
Playing with Strings
Lists and tuples
Loops
Dictionaries
Defining functions
Files
Modules
Classes

Note: For this post we will be using Windows as our Operating System for running the commands over the terminal.

Installing Python

It doesn’t matter which operating system you use because Python runs great on Windows, Mac OSX, Linux and many other operating systems. However, installing and launching Python are done differently on different operating systems, so just follow your operating system’s instructions.

Windows

Installing Python on Windows is a lot like installing any other program.

  1. Visit the official Python website.
  2. Move your mouse over the Download menu, but don’t click it. Then click the button that downloads the latest version of Python.
  3. Run the installer.
  4. Make sure that the launcher gets installed and click Install Now.

Mac OSX

Installing Python over Mac OSX will be like installing any other program, you can download the version from their official site and can follow this video tutorial.

Running Python

Next we’ll learn to run Python on a PowerShell or terminal. There are several other ways to run Python, but for now we will stick to the basic.

Windows

  1. Open a PowerShell from your start menu or start screen.
  2. Type py and press Enter. You should see something like this:

Now you can type exit() and press Enter to get out of Python. Or you can just close the PowerShell or Terminal window.

Another Option for using Python

You can use a website like repl.it to run python programs. repl.it is a simple yet powerful online compiler, IDE, interpreter and interactive environment for programming languages such as python. But I highly recommend installing Python. That way you don’t need to open a web browser just to write code, and you can work without an Internet connection.

Getting started with Python

At first launch your Python terminal as explained in the above part.

The >>> means that Python is ready and we can enter a command. The basic idea is really simple: we enter a command, press Enter, enter another command, press Enter and keep going.

You probably don’t know any Python commands yet. Let’s see what happens if we just write something and press Enter.

>>> hello

Oops! That didn’t work. But we get an error message that tells us what’s wrong.

Let’s move further.

Maybe we can press Enter without typing anything?

>>>
>>>

That worked. How about numbers?

>>> 123
123
>>> -123
-123
>>> 3.14
3.14
>>> -12.3
-12.3
>>>

As we can see the echoes come back. Hence it worked!

Comments

Comments are text that does nothing. They can be created by typing a # and then some text after it, and they are useful when our code would be hard to understand without them.

>>> 1 + 2     # comment here
3

Python does not really have a syntax for multi line comments. To add a multi-line comment you could insert a # for each line:

>>> # comment 1st Line
>>> # comment 2nd Line
>>> 1 + 2
3

Strings

Strings are small pieces of text that we can use in our programs. We can create strings by simply writing some text in quotes.

>>> 'hello world'
'hello world'

Strings can also be written with “double quotes” instead of ‘single quotes’. This is useful when we need to put quotes inside the string.

Strings can be joined together easily with + or repeated with *:

>>> "hello" + "world"
'helloworld'>>> "hello" * 3
'hellohellohello'

Using Python as a calculator

Let’s type some math stuff into Python and see what it does.

>>> 17 + 3
20
>>> 17 - 3
14
>>> 17 * 3
51
>>> 17 / 3
5.666666666666667

Python does follow “Bodmas rule”. Starting from * Parentheses * Exponents * Multiplication * Division * Addition * Subtraction.

Variables, Booleans and None

Variables

Variables are easy to understand. They simply point to values. They are containers for storing data values. 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.

>>> a = 1   # create a variable called a that points to 1
>>> b = 2   # create another variable

To get the value of the variable simple use the variable name and press enter.

>>> a       # get the value that the variable points to
1
>>> b
2

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

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0–9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
>>> #Legal variable names:
>>> myvar = "John"
>>> my_var = "John"
>>> _my_var = "John"
>>> myVar = "John"
>>> MYVAR = "John"
>>> myvar2 = "John">>> #Illegal variable names:
>>> 2myvar = "John"
>>> my-var = "John"
>>> my var = "John"

Note: Remember that variable names are case-sensitive

When assigning something to a variable using a =, the right side of the = is always executed before the left side. This means that we can do something with a variable on the right side, then assign the result back to the same variable on the left side.

>>> a = 1
>>> a = a + 1
>>> a
2

To do something to a variable (for example, to add something to it) we can also use +=-=*= and /= instead of +-* and /. The “advanced” %=//= and **= also work.

>>> a += 2          # a = a + 2
>>> a -= 2          # a = a - 2
>>> a *= 2          # a = a * 2
>>> a /= 2          # a = a / 2

This is not limited to integers.

>>> a = 'hello'
>>> a *= 3
>>> a += 'world'
>>> a
'hellohellohelloworld'

Booleans

There are two Boolean values, True and False. In Python, and in many other programming languages, = is assigning and == is comparing. a = 1 sets a to 1, and a == 1 checks if a equals 1.

>>> a = 1
>>> a == 1
True
>>> a = 2
>>> a == 1
False

None

None is Python’s “nothing” value. It behaves just like any other value, and it’s often used as a default value for different kinds of things.

>>> not_val = None
>>> not_val
>>>

Other comparing operators

So far we’ve used ==, but there are other operators also. This list probably looks awfully long, but it’s actually quite easy to learn.

Python divides the operators in the following groups:

Python Arithmetic Operators

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

>>> x = 1
>>> y = 2
>>> x + y # Addition
3
>>> x - y # Subtraction
-1
>>> x * y # Multiplication
2
>>> x / y # Division
0.5
>>> x % y # Modulus
1
>>> x ** y # Exponentiation
1
>>> x // y # Floor division
0

Python Assignment Operators

Assignment operators are used to assign values to variables.

>>> x = 5
>>> x += 3
>>> x
8
>>> x -= 3
>>> x
5
>>> x *= 3
>>> x
15
>>> x /= 3
>>> x
5.0
>>> x %= 3
>>> x
2.0
>>> x = 5
>>> x //= 3
>>> x
1
>>> x **= 3
>>> x
1
>>> x = 5
>>> x &= 3
>>> x
1
>>>
>>> x |= 3
>>> x
3
>>> x ^= 3
>>> x
0
>>> x >>= 3
>>> x
0
>>> x <<= 3
>>> x
0

Python Comparison Operators

Comparison operators are used to compare two values.

>>> x = 2
>>> y = 3
>>> x == y # Equal
False
>>> x != y # Not equal
True
>>> x > y # Greater than
False
>>> x < y # Less than
True
>>> x >= y # Greater than or equal to 
False
>>> x <= y # Less than or equal to
True

Python Logical Operators

Logical operators ( and / or / not ) are used to combine conditional statements.

>>> x = 9
>>>
>>> # and - Returns True if both statements are true
... x < 5 and  x < 10
False
>>>
>>> # or - Returns True if one of the statements is true
... x < 5 or x < 4
False
>>>
>>> # not - Reverse the result, returns False if the result is true
... not(x < 5 and x < 10)
True

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.

>>> x = 9
>>> y = 9
>>>
>>> # is - Returns True if both variables are the same object 
... x is y
False
>>>
>>> # is not  - Returns True if both variables are not the same object
... x is not y
False

Built-in Function “print”

Now we know how to make Python show text.

>>> 'Hello!'
'Hello!'

But that includes quotes''. One way to show text to the user without quotes'' is with the print function. In Python, printing doesn’t have anything to do with physical printers, it just means showing text on the screen.

>>> print('Hello!')
Hello!>>> print("Hello World!")
Hello World!

Let’s see what happens if we type print without the ('Hello') part.

As we can see, print is a function. Functions do something when they are called by typing their name and parentheses. Inside the parentheses, we can pass some arguments too. In print("hello") the function is print and we give it one argument, which is "hello".

Functions are easy to understand, They simply do something when they are called. Functions run immediately when we call them, so the text appears on the screen right away when we run print(something).

Thing that you could do wrong: Sometimes people think that doing thingy = print('hello') means that Python is going to print hello every time we type thingy. But this is not correct! print('hello') runs print right away, and if we type thingy later it’s not going to run print('hello') again.

Handy things about print

We can also print an empty line by calling print without any arguments.

>>> print()>>>

In Python, \n is a newline character. Printing a string that contains a newline character also prints a newline:

>>> print('hello\nworld')
hello
world
>>>

If we want to print a real backslash, we need to escape it by typing two backslashes.

>>> print('hello\\nworld')
hello\nworld
>>>

We can also pass multiple arguments to the print function. We need to separate them with commas and print will add spaces between them.

>>> print("Hello", "World!")
Hello World!
>>>

Unlike with +, the arguments don’t need to be strings.

>>> print(42, "is an integer, and the value of pi is", 3.14)
42 is an integer, and the value of pi is 3.14
>>>

if, else and elif

Using if statements

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

>>> a = 33
>>> b = 200
>>> if b > a:
...     print("b is greater than a") #indented line
...
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”.

An important thing to notice is that the line with a print is indented. You can press the tab key, or if it doesn’t work just press space a few times.

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

Also Note: The prompt changed from >>> to .... It meant that Python was expecting me to keep typing. When I was done, I just pressed Enter twice. My code was executed and the prompt went back to >>>.

Using elif statements

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

>>> a = 33
>>> b = 200
>>> if b > a:
...     print("b is greater than a") #indented line
...
b is greater than a
>>>

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

Using else statements

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")
...
a is greater than b
>>>

In this example a is greater than 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("a is greater than b")
...
a is greater than b
>>>

Playing with Strings

Concatenate

>>> "I said: " + our_string
'I said: Hello World!'
>>>

Multiplier for string

>>> our_string = "Hello World!"
>>> our_string * 3
'Hello World!Hello World!Hello World!'
>>>

Thing You Should Know:

Python strings are immutable. That’s just a fancy way to say that they cannot be changed in-place, and we need to create a new string to change them. Even some_string += another_string creates a new string. Python will treat that as some_string = some_string + another_string, so it creates a new string but it puts it back to the same variable.

Slicing

Slicing is really simple. It just means getting a part of the string. For example, to get all characters between the second place between the characters and the fifth place between the characters, we can do this

>>> our_string = "Hello World!"
>>> our_string[2:5]
'llo'
>>>

So the syntax is like some_string[start:end].

But what happens if we slice with negative values?

>>> our_string = "Hello World!"
>>> our_string[-5:-2]
'orl'
>>>

If we don’t specify the beginning it defaults to 0, and if we don’t specify the end it defaults to the length of the string. For example, we can get everything except the first or last character like this:

>>> our_string = "Hello World!"
>>> our_string[1:] 
'ello World!'
>>> our_string[:-1] 
'Hello World'
>>>

Indexing

Indexing strings also starts at zero. The first character is our_string[0], the second character is our_string[1], and so on.

>>> our_string = "Hello World!"
>>> our_string[0]
'H'
>>> our_string[1]
'e'
>>> our_string[2]
'l'
>>> our_string[3]
'l'
>>> our_string[4]
'o'
>>>

String Methods

Python’s strings have many useful methods. The official documentation covers them all, but I’m going to just show some of the most commonly used ones briefly.

Here’s an example with some of the most commonly used string methods:

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

>>> our_string = "Hello World!"
>>> our_string.upper()
'HELLO WORLD!'

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

>>> our_string = "Hello World!"
>>> our_string.lower()
'hello world!'

The startswith() method returns True if the string starts with the specified value, otherwise False.

>>> our_string = "Hello World!"
>>> our_string.startswith('Hello')
True

The endswith() method returns True if the string ends with the specified value, otherwise False.

>>> our_string = "Hello World!"
>>> our_string.endswith('World!')
True
>>> our_string.endswith('world!')  # Python is case-sensitive
False

The replace() method replaces a specified phrase with another specified phrase.

>>> our_string = "Hello World!"
>>> our_string.replace('World', 'there')
'Hello there!'

The lstrip() method removes any leading characters (space is the default leading character to remove)

>>> our_string = "Hello World!"
>>> '  hello 123  '.lstrip()    # left strip
'hello 123  '

The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

>>> our_string = "Hello World!"
>>> '  hello 123  '.rstrip()    # right strip
'  hello 123'

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

>>> our_string = "Hello World!"
>>> '  hello 123  '.strip()     # strip from both sides
'hello 123'

The count() method returns the number of times a specified value appears in the string.

>>> our_string = "Hello World!"
>>> our_string.count('o')   # it contains two o's
2

The index() method finds the first occurrence of the specified value.

>>> our_string = "Hello World!"
>>> our_string.index('o')   # the first o is our_string[4]
4

The rindex() method finds the last occurrence of the specified value.

>>> our_string = "Hello World!"
>>> our_string.rindex('o')  # the last o is our_string[7]
7

The join() method takes all items in an iterable and joins them into one string.

>>> '-'.join(['hello', 'world', 'test'])
'hello-world-test'

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

>>> 'hello-world-test'.split('-')
['hello', 'world', 'test']

String Formatting

The format() method formats the specified value(s) and insert them inside the string’s placeholder.

The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.

The format() method returns the formatted string.

>>> txt1 = "My name is {fname}, I'am {age}".format(fname = "John", age = 36)
>>> txt1
"My name is John, I'am 36"

Another example:

>>> txt2 = "My name is {0}".format("John")
>>> txt2
'My name is John'

Lists and tuples

Sometimes we may end up doing something like this.

name1 = 'john'
name2 = 'doe'
name3 = 'amin'
name4 = 'mark'
name5 = 'spark'

This code works just fine, but there’s a problem. The name check is repetitive, and adding a new name requires adding even more repetitive. This is where LIST comes into play.

Lists

Instead of adding a new variable for each name it might be better to store all names in one variable. This means that our one variable needs to point to multiple values. An easy way to do this is using a list.

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

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']

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

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names[1]  
'doe'

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names[-1]  
'spark'

You can specify a range of indexes by specifying where to start and where to end the range.

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names[1:3]  
['doe', 'amin']

Note: The search will start at index 1 (included) and end at index 3 (not included) which is why you are seeing doe, amin and not mark.

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

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names[1] = "smith"
>>> names
['john', 'smith', 'amin', 'mark', 'spark']

To determine how many items a list has, use the len() function:

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> len(names)
5

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

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names.append('medium')

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

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names.insert(1,'medium')

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

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names.insert(1,'medium')

The remove() method removes the specified item:

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names.remove('doe')

The del keyword removes the specified index:

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> del names[0] #remove john
>>> names 
['doe', 'amin', 'mark', 'spark']

The del keyword can also delete the list completely:

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> del names

The clear() method empties the list:

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> names.clear()

Copying a List: You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. You can make a copy of a list with the copy() method:

>>> names = ['john', 'doe', 'amin', 'mark', 'spark']
>>> newnamelist = names.copy()
>>> newnamelist
['john', 'doe', 'amin', 'mark', 'spark']

Join Two Lists: Though there are several ways

>>> list1 = ["a", "b" , "c"]
>>> list2 = [1, 2, 3]
>>> list3 = list1 + list2
>>> list3
['a', 'b', 'c', 1, 2, 3]

** There is one thing we are leaving here Loop Through a List. This we will cover while learning Loops.

Tuples

Tuples are a lot like lists, but they’re immutable so they can’t be changed in-place. We create them like lists, but with () instead of [].

Hence once a tuple is created, you cannot add items to it. Tuples are unchangeable.

>>> numbers = (1, 2, 3)
>>> numbers
(1, 2, 3)

You can access tuple items by referring to the index number, inside square brackets:

>>> numbers = (1, 2, 3)
>>> numbers[1]
2

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

>>> numbers = (1, 2, 3)
>>> numbers[-1]
3

Range of Indexes: You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items.

>>> thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
>>> print(thistuple[2:5])
('cherry', 'orange', 'kiwi')

Note: The search will start at index 2 (included) and end at index 5 (not included). Also remember that the first item has index 0.

Change Tuple Values : Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

>>> x = ("apple", "banana", "cherry")
>>> y = list(x)
>>> y[1] = "kiwi"
>>> x = tuple(y)
>>> print(x)
('apple', 'kiwi', 'cherry')

Tuple Length: To determine how many items a tuple has, use the len() method:

>>> x = ("apple", "banana", "cherry")
>>> print(len(x))
3

Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:

>>> thistuple = ("apple", "banana", "cherry")
>>> del thistuple

Join Two Tuples: To join two or more tuples you can use the + operator:

>>> tuple1 = ("a", "b" , "c")
>>> tuple2 = (1, 2, 3)
>>> tuple3 = tuple1 + tuple2
print(tuple3)

** There is one thing we are leaving here Loop Through a Tuple. This we will cover while learning Loops.

Loops

In programming, a loop means repeating something multiple times. There are different kinds of loops:

1. While loops repeat something while a condition is true.
2. For loops repeat something for each element of something.

The While loop

With the while loop we can execute a set of statements as long as a condition is true. Let’s take an example to understand how while loop works.

The program prints 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:

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:

Continue to the next iteration if i is 3:

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

The For loop

for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Let’s take an example to understand how while loop works.

Print each fruit in a fruit list: (***This is where we use the LIST)

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

Note: Don’t forget the indentation at print(x) statement.

The break Statement

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

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

The continue Statement

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

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

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

>>> adj = ["red", "big", "tasty"]
>>> fruits = ["apple", "banana", "cherry"]
>>> for x in adj:
>>>   for y in fruits:
>>>     print(x, y)

Loop Through a List

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

>>> thislist = ["apple", "banana", "cherry"]
>>> for x in thislist:
>>>   print(x)

Loop Through a Tuple

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

>>> thistuple = ("apple", "banana", "cherry")
>>> for x in thistuple:
>>>    print(x)

Dictionaries

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.

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> print(thisdict)
{'year': 1964, 'brand': 'Ford', 'model': 'Mustang'}

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> x = thisdict["model"]
>>> print(x)
'Mustang'

Change Values

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

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> thisdict["year"] = 2020

Loop Through a Dictionary

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

>>> #Print all key names in the dictionary, one by one:
>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> for x in thisdict:
      print(x)
>>> #Print all values in the dictionary, one by one:
>>> for x in thisdict:
  print(thisdict[x])

Dictionary Length

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

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> print(len(thisdict))

Adding Items

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

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> thisdict["color"] = "red"
>>> print(thisdict)

Removing Items

There are several methods to remove items from a dictionary:

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

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> thisdict.pop("model")
>>> print(thisdict)

The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> thisdict.popitem()
>>> print(thisdict)

The del keyword removes the item with the specified key name:

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> del thisdict["model"]
>>> print(thisdict)

Empty Dictionary

The clear() method empties the dictionary:

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> thisdict.clear()
>>> print(thisdict)

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

You can make a copy of a dictionary with the copy() method:

>>> thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
>>> mydict = thisdict.copy()
>>> print(mydict)

Nested Dictionaries

A dictionary can also contain many dictionaries, this is called nested dictionaries.

>>> myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

Defining 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. Plus they 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()
Hello from a 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:

>>> def my_function(fname):
...     print(fname + " Refsnes")
...
>>> my_function("Emil")
Emil Refsnes
>>>

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.

>>> def my_function(food):
...   for x in food:
...     print(x)
...
>>> fruits = ["apple", "banana", "cherry"]
>>> my_function(fruits)
apple
banana
cherry

Return Values

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

>>> def my_function(x):
...   return 5 * x
...
>>> print(my_function(3))
15

Files

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.

>>> f = open("test.txt")    # open file in current directory
>>> f = open("C:/Python38/README.txt")  # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or append a to the file. We can also specify if we want to open the file in text mode or binary mode.

The default is reading in text mode. In this mode, we get strings when reading from the file.

On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.

f = open("test.txt")      # equivalent to 'r' or 'rt' - t: text mode
f = open("test.txt",'w')  # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

When working with files in text mode, it is highly recommended to specify the encoding type i.e utf-8 here. By default in windows, it is cp1252 but utf-8 in Linux.

>>> f = open("test.txt", mode='r', encoding='utf-8')

Closing the File

When we are done with performing operations on the file, we need to properly close the file.

Closing a file will free up the resources that were tied with the file. It is done using the close() method available in Python.

>>> f = open("test.txt", encoding = 'utf-8')
>>> # perform file operations
>>> f.close()

This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.

A safer way is to use a try…finally (exception handling) block.

>>> try:
>>>    f = open("test.txt", encoding = 'utf-8')
>>> # perform file operations
>>> finally:
>>>    f.close()

This way, we are guaranteeing that the file is properly closed even if an exception is raised that causes program flow to stop.

Create a New File

In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

>>> f = open("test.txt", "a")
>>> f.write("my first file\n")
>>> f.write("This file\n\n")
>>> f.write("contains three lines\n")
>>> f.close()

The above example opens the file “test.txt” and append content to the file.

Read Only Parts of the File

To read a file in Python, we must open the file in reading r mode.

We can read the text.txt file we wrote in the above section in the following way:

>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
'This'>>> f.read(4) # read the next 4 data
' is '>>> f.read() # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'>>> f.read()  # further reading returns empty sting
''

Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

>>> import os
>>> os.remove(“test.txt”)

To avoid getting an error, you might want to check if the file exists before you try to delete it:

>>> import os
>>> if os.path.exists("demofile.txt"):
>>>  os.remove("demofile.txt")
>>> else:
>>>  print("The file does not exist")

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.

A file containing Python code, for example: example.py, is called a module, and its module name would be example.

We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.

Create a Module

Let us create a module. Type the following and save it as example.py.

>>> # Python Module example
>>>
>>> def add(a, b):
>>>   result = a + b
>>>   return result

Here, we have defined a function add() inside a module named example. The function takes in two numbers and returns their sum.

Use a Module

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

>>> import example

Using the module name we can access the function using the dot . operator. For example:

>>> example.add(4,5.5)
9.5

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

Variables in Module

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

Suppose the following code is saved in sample.py

>>> person1 = {  "name": "John",
  "age": 36,
  "country": "Norway"
}

Import the module named sample, and access the person1 dictionary:

>>> import mymodule
>>> a = mymodule.person1["age"]
>>> print(a)

Re-naming a Module

We can import a module by renaming it as follows (also can be called as alias):

>>> # import module by renaming it
>>> import example as e
>>> print("Total:", e.add(4,5.5))

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Import and use the platform module:

>>> import platform
>>> x = platform.system()
>>> print(x)

Import Part 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)
>>> 
>>> person1 = {"name":"John", "age": 36, "country":"Norway" }

Import only the person1 dictionary from the module:

>>> from mymodule import person1
>>> print (person1["age"])

Classes/Objects

Python is a multi-paradigm programming language. It supports different programming approaches. And one of the popular approaches to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP).

An object has two characteristics: attributes and behavior

Let’s take an example:

A bird is can be an object,as it has the following properties: name, age, color as attributes while singing, dancing as behavior.

The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don’t Repeat Yourself).

Create a Class

A class is a blueprint for the object.

To create a class, use the keyword class:

>>> class myClass
>>>  x = 5

Create Object

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

>>> myObj = MyClass()
>>> print(myObj.x)

The __init__() Function

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:

>>> class Person:
>>>  def __init__(self, name, age):
>>>    self.name = name
>>>    self.age = age
>>>
>>> p1 = Person("John", 36)
>>>
>>> print(p1.name)
>>> print(p1.age)

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the 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)
>>>
>>> print(p1.name)
>>> print(p1.age)
>>> p1.myfunc()

Modify Object Properties

You can modify properties on objects like this:

>>> p1.age = 40

Delete Object Properties

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

>>> del p1.age

Delete Objects

You can delete objects by using the del keyword:

>>> del p1

What More

Here are few additional resources for you to learn and practice: