Python Lesson #2

One of the first things you are probably going to want to do is use modules.

For example to print out pi, we use the math module as below

import math
math.pi

3.141592653589793

When we import modules they generally come with same namespace, i.e. calling pi function with prefix namespace of math. For performance, etc we can also just import the specific functions we want to use. This puts the function in the global name space. For example:

from math import pi
pi

It is also possible to use a alias – such as

import math as m
m.pi

You can also create your own modules simply by storing functions in filenames with .py extension. So for example we create a file called mymodule.py with following content

# mymodule.py
def double(number):
—>return 2 * number

Then we invoke with following .. if you get an error try import sys;print sys.path for folders searched for modules. Also you can use PYTHONPATH system variable to include other paths

import mymodle
double(65)
>> 130

Python Intro

I have been working with Python and spent many hours of study, but best way to learn is to teach 🙂

As per my other guides into PHP, Perl, etc .. I will gradually write some intro, intermediate and advanced topics.

As a quick warm up 🙂

$ python -c 'print("Hi World")'
Hi World

$ python -c 'print(type("test"))'
<type 'str'>

$ python -c 'print(3**7)'
2187

Quick bit of OO – defining method

class Car:      # class attrib     category = "Vehicle"      # instance attrib     def __init__(self,name,make,model):         self.name=name         self.make=make         self.model=model      # instance method     def desc(self):         return "Name: {} is made by {} and is the {} body shape".format(self.name,self.make,self.model)

Then creating an object from this class and calling methods

fordLaser=Car("Ford Laser","Ford","Hatchback")
print(fordLaser.desc())