An Introduction to Python for the Experienced Programmer, Part 3
This article continues where the second article in this series left off. You should read the first and second articles in this series before reading this article.
The previous articles discussed installing Python, using some core functions along with manipulating strings, and using operators, statements, and looping functions. Now look at how dictionaries, custom functions, and import modules work in Python.
If you have programmed in Ruby, you can notice some similarities between Ruby in Python.
Dictionaries
Dictionaries are another fancy way of storing temporary data. Dictionaries are actually an advanced type of list. Each item is associated with a key that is later used to access a value. Hash-maps also use a similar concept in most languages.
In Python, declaring a dictionary is easy and uses the curly bracket notation:
dictionaryName = {'item1':1,'item2':2,'item3':3}
To print out a dictionary value, simply do the following:
print(dictionaryName['item_1'])
The key happens to be the string 'item1', and the associated value is the integer 1. All keys must be a string, but that key can reference any type. As with a list, you can use the delcommand to remove an item:
del dictionaryName['item_1']
When printing out the dictionary list, sometimes it isn't in the original order that you declared the values for. A dictionary is an unordered list.
Functions
Functions in Python are closest to Ruby in terms of syntax. As with Ruby, the def keyword is used in Python to define a function. The syntax to declare a function is
def functionName(variables ..): statements [ ... ] return type
A simple function appears below:
def add(x, y): answer = x + y return answer answer = add(5,8) print(answer)
Notice that when printing out the answer, you can use the same variable name as defined to assign the answer in the function itself. Using the same name for a variable not in the function is not a problem because when out-denting statements after the function, these statements are no longer in the function's scope.
Below are some of Python's built-in functions for handling strings and numbers:
# find length of string length = len("How long is this string?") # convert an integer to a string x = 15 print(str(x)) # floating point answer x = float(20)/float(7) print(x) # round the floating point answer up to next whole number print(round(x)) # get random integer between 0 and 10import random x = random.randrange(1,10) print(x)
You can get a list of Python's built-in functions and what they do from this URL: http://docs.python.org/3.2/library/functions.html.
Importing Modules
In most other mainstream languages, you would import classes instead of modules. But, modules in Python, like Ruby, are a collection of functions. The way Python declares and uses functions does not support fundamental OO concepts such as inheritance, encapsulation, and so on. So, is Python an OO language? I would have to say it isn't. Although everything is an object in Python, JavaScript is also similar, and JavaScript technically is not an OO language. Neither JavaScript nor Python implement OO concepts but do handle objects in a scripting manner, hence the reference to Python scripts.
Importing built-in modules are easy:
import math print(math.sqrt(16))
To import a custom module, try adding the add function above to a script called myMath. To use myMath, do the following:
import myMath answer = myMath.add(5,8) print(answer)
You can get a list Python's modules and what they do from this URL:
http://docs.python.org/3.2/py-modindex.html.
Making Programs
Making programs often involve collecting user input, doing something with that input, and then giving the results back to the user. You can create a simple program using the addfunction. The function asks the user for two numbers and then gives the user the answer. To get input from the user, you can use the built-in input function:
import myMath x = input('Enter the first number: ') y = input('Enter the second number: ') answer = myMath.add(int(x),int(y)) print(answer)
To handle errors, use theTry...Exceptstatements:
try: import myMath x = input('Enter the first number: ') y = input('Enter the second number: ') answer = myMath.add(int(x),int(y)) print(answer) except: print('You entered an incorrect value')
You can expand a program by adding if...elifmultistatements, loops, and more functions. As you can see, building a program is easy with Python, even a more complicated program. Because Python programs are a single tier (application layer), you do not have to worry about “separation of concerns” as with large industrial applications. You can use Python, however, in one of the layers of a large application to handle business logic.
Conclusion
This article picked up where the second article in this series left off. Here you learned how to use dictionaries, functions, and import modules. If you read all articles in this three-part series, you should now be comfortable starting your own Python programs. You can also explore ways on how to integrate Python into aiding web applications in creating business rules and workflows. You can even use Python for mobile platforms such as Android or embedded systems such as micro-controllers. There are so many possibilities.
Python has a lot of changes between versions in eliminating commonly used functions. Built-in function names from older version are often replaced with a different name or eliminated, which unfortunately breaks functionality for programs made with earlier versions. Java and .NET are more careful about this because it is essential there is as much backward compatibility as possible to allow industrial applications to continue working.
Although there are so many languages out there, Python has stood the test of time and remains popular. You will find many development shops use Python in one form or another.