Python Basics

About a month ago I decided to broaden my horizon by signing in for a study of MongoDB. It turned out that this course was given in Python, another language that was on my wishlist. Currently I’m in week 3 and I felt it was time to make a little summary for the things I’ve learned.

Python basics

This blog post covers some Python basics, because this was the biggest part of the first week course of MongoDB training.

Lists

What most people know as an so called “array” (in PHP, javascript, etc.)  is called a “List” in Python. Let’s take a look at a simple list in Python that contains the values ‘foo’, ‘bar’ and ‘baz’.

a = ['foo', 'bar', 'baz']

Python has several functions to modify this list ( see: http://docs.python.org/2/tutorial/datastructures.html )

Dictionaries

Dictionaries are sometimes found in other languages (PHP, js) as “associative memories” or “associative arrays”. Unlike lists , dictionaries are indexed by keys which can be any immutable type; strings and numbers can always be keys. Besides that a dictionary can hold one or several lists or other dictionaries.

b = {'foo': 'bar', 'fruit': ['apple', 'banana']}

List Slices

Slices in Python make it easy to extract a part of a list. Python does this by defining an start and/or end point based on the keys (or indexes) of the list. The part left of the colon is the start point, and the right side is the end point

fruit[include:exclude]

If we have a list of fruit, like the one below, we can use this feature of Python to extract “pear” from it.

>>> fruit = ['apple', 'pear', 'banana']
>>> fruit[1:2]
['pear']

We entered 1 as our start point (which is the second item of the list) and 2 as our end (3rd item).

List, Inclusion

Checking whether a certain value exists in a List is extremely easy and short written. Let’s say we have the previous fruit list and we would like to check if “pear” exists. Then the following if statement will help us determining if this is the fact.

if "pear" in fruit:
   print "there is a pear in fruit!"

Working with Dicts (Dictionaries)

Working with Python Dictionaries has some similarities with the List. Adding or manipulating items in the dictionary is done in pretty much the same syntax.

# our example dictionary
book = { "title": "Getting real", "author": "37 signals", "format": "pdf" }

# let's add the price to the dictionary
>>> book['price'] = "free"
>>> book
{'format': 'pdf', 'author': '37 signals', 'price': 'free', 'title': 'Getting real'}

# removing an item is done by using the del command
>>> del(book['format'])
>>> book
{'author': '37 signals', 'price': 'free', 'title': 'Getting real'}

Note! – One little note about dictionaries is that the items of the dictionary don’t keep their order. For example “price” is being put between ‘author’ and ‘title’, whilst this was the last added item.

For loops with Lists & Dicts

For loops enable you to iterate/walk through Lists and Dicts. Below you will find some examples for both lists as dicts:

# for loop on books list
books = ['Getting Real', 'The Bible', 'Zen To Done']
for item in books:
    print item
 # for loop on books dictionaries
books = {'title': 'Getting Real', 'isbn': '12345', 'price': 10.00}
for key in books:
    print key + " has the value " + books[key]

As you can see in the last example is that the key/index is used to retrieve the value.

While loops

While loops enable you to loop through Lists (not for dictionaries).

# while loop on fruits list
fruits = ['apple', 'pear', 'banana']
while(i < len(fruits)):
    print fruits[i]
    i = i + 1

Functions

Functions in python get declared by the term “def”. Little example below:

# define function hello
def hello(name):
   print "hello " + name

# call function hello
hello('visitor')

 

 

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *