Getting start with python
In this post we are going the basics stones such as Data types, variables, classses, Objects , Lists, Models, , functions, comment, etc in Python programming, and my assumption is you have a basic knowledge from other computer languages as well.
Standard Data Types
Python has five standard data types −
- Numbers
- String
- List
- Tuple
- Dictionary
Python supports four different numerical types
- int (signed integers)
- long
- float (floating point real values)
- complex (complex numbers)
Strings in Python
Strings in Python are identified in the quotation marks. either pairs of single or double quotes.
mystr = 'Hello World!' or mystr = "Hello World!"
Python Lists
A list in Python contains items separated by commas and enclosed within square brackets ([]). The items belonging to a list can be of different data type.
mylist = [ 'stg', 786 , 2.23, 'Peter', 70.2 ]
Python Tuples
A tuple is similar to the list. A tuple consists of a number of values separated by commas and enclosed within parentheses.
The differences between lists and tuples are: Lists are enclosed in brackets ” [ ] ” and elements and size in the list can be changed, while tuples are enclosed in parentheses ” ( ) ” and value cannot be changed. You can think Tuples are as read-only lists.
mytuple = ( 'xyz', 286 , 20.2, 'Stockholm', 70.2 )
mydict = {}
mydict['1'] = "one"
dict[2] = "two"
mytinydict = {'city': 'Stockholm','code':26734, 'country': 'Sweden'}
Python Dictionary
Dictionaries in Python are kind of hash table type, and consist of key-value pairs. A dictionary key can be any Python type, but are usually numbers or strings. Values, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces { } and values can be assigned and accessed using square braces [].
Variables assignment
Python variables do not need explicit declaration . The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
Comment in Python is # ( ex: # my comment).
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example:
# integer
number = 70
# floating
distance = 70.0
# string
city = "Stockholm"
Assignment of multiple variables
Python allows you to assign a single value to several variables simultaneously. For example −
x = y = z = w= 10
Here, an integer object is created with the value 10, and all four variables are assigned to the same memory location.
It is possible to assign multiple objects to multiple variables.
x,y,z = 10,20.0,"Stockholm"
Here, one integer object with values 10, one float, with value 20.0 and one string are assigned to variables x and y and z.
Conversion of Data Types
To convert between data types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
functions return a new object representing the converted value.
- int(x [,base]) : Converts x to an integer. base specifies the base if x is a string
- long(x [,base] ): Converts x to a long integer
- float(x): Converts x to a floating-point number
- complex(real [,imag]): Creates a complex number
- str(x) : Converts object x to a string representation.
- repr(x): Converts object x to a string representation.
- eval(str): Evaluates a string and returns an object.
- tuple(s): Converts s to a tuple.
- list(s) : Converts s to a list.
- set(s): Converts s to a set.
- dict(d): Creates a dictionary. d must be a sequence of (key,value) tuples
- frozenset(s): Converts s to a frozen set.
- chr(x): Converts an integer to a character.
- unichr(x): Converts an integer to a Unicode character.
- ord(x): Converts a single character to its integer value.
- hex(x) : Converts an integer to a hexadecimal string.
- oct(x): Converts an integer to an octal string.
Types of Operator in Python
Python language supports the following types of operators and these operators are similar in C, C#, etc.
- Arithmetic Operators : these are : +, -, *, /, %, **, //
- Comparison (Relational) Operators : ==, !=, <>, <, >, <=, >=,
- Assignment Operators : =, +=, -=, *=, /=, %=, **=, //=
- Logical Operators: and (AND), or (OR), not (NOT)
- Bitwise Operators: &, !, ^ Binary XOR, ~ Binary Ones Complement, << Binary Left Shift, >> Binary Right Shift ,
- Membership Operators: in, not in
- Identity Operators: is, is not
Condition in Python
As other languages: if statment and if or else statment.
var = 10
if ( var == 10 ) : print "Value is 10"
else: print "Value is not 10"
Functions in Python
A function is a block of code that is used to perform an action.
There are two variant of functions in Python:
- built-in functions: like print()
- user defined functions: developer defines it
Defining a Function user defined functions
- Function blocks begin with the keyword def followed by the function name and parentheses ( ) .
- Any input parameters or arguments should be placed within these parentheses. Y
- The first statement of a function can be an optional statement – the documentation string of the function or docstring.
- The code block within every function starts with a colon (:) and is indented.
- The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Example:
def printname( name ):
"This prints a string name into this function"
print name
return
Calling a Function
A function can be called from another function or directly from the Python prompt. Following is the example to call prinname() function.
# Function printname: definition
def printme( name ):
"This prints a name string into this function"
print name
return;
# call of function printname.
printname("my name is Barak!")
printme("my last name is Obama ")
Function Arguments
You can call a function by using the following types of arguments −
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct order. Number of arguments in the function call should match exactly with the function definition.
To call the function printname(), you need to pass one argument, otherwise it gives a syntax error as follows:
#Function definition
def printname( name ):
"This prints a name string into this function" print name return;
# Now call this function printname without parameteres.
printname()
# this shall give you Error:TypeError: printme() takes exactly 1 argument (0 given)Error: printme() takes exactly 1 argument (0 given)
Keyword arguments
When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
# Function definition is here
def printname( name ):
"This prints a name string into this function"
print name
return;
# call printname function with keyword
printme( name = "Barak Obama")
with execution of the above code, gives result −
Barak Obama
Another example:
# Function definition
def printmyinfo( name, age ):
"This prints a passed my info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printmyinfo function
printmyinfo( age=50, name="Obama" )
Result of above code execution:
Name: Obama Age 50
Default arguments
The default argument is assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments:
# Function definition
def printmyinfo( name, age = 50 ):
"This prints a passed myinfo into this function"
print "Name: ", name
print "Age ", age
return;
# call printmyinfo function
printmyinfo( age=50, name="Obama" )
printmyinfo( name="Obama" )
Output is
Name: Obama Age 50 Name: Obama Age 35 # output of default parameter
Variable-length arguments
giving more argumentswith calling than it is specified with definition of function. These arguments are called variable-length arguments and are not named in the function definition, otherwise required and default arguments.
Syntax
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
The “*” is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if with calling of this function no additional arguments are specified.
# Function definition
def printsomeinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
# call printsomeinfo function
printsomeinfo( 100 )
printsomeinfo( 700, 600, 500 )
Output of above code:
Output is: 100 Output is: 700 600 500
Anonymous Functions
Functions are called anonymous because are not declared in the standard way by using the def keyword. You can use the lambda keyword to create small anonymous functions.
- Lambda forms can take any number of arguments but return just one value in the form of an expression.
- These cannot be a direct call to print because lambda requires an expression
- Lambda functions have their own local namespace and they cannot access variables other than those in their parameter list and those in the global namespace.
- Lambda’s are a one-line version of a function, whose purpose is by passing function stack allocation during invocation for performance reasons.
syntax of lambda functions contains only a single statement
lambda [arg1 [,arg2,.....argn]]:expression
Example :
# Function definition
sum = lambda arg1, arg2: arg1 + arg2;
# call the function
print "The total value : ", sum( 100, 200 )
print "The total value : ", sum( 202, 202 )
Output:
Value of total : 300 Value of total : 400
Return Statement in function
The return exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
# Function definition
def sum( param1, param2 ):
# Add the parameters and return them."
total = param1 + param2
print "Inside the function : ", total
return total;
# call function
total = sum( 101, 201 );
print "Outside the function : ", total
Output:
Inside the function : 302 Outside the function : 302
Scope of Variables in Python
- Global variables : global variables can be accessed throughout the program body by all functions.
- Local variables : Variables that are defined inside a function body have a local scope, and those:
total = 10; # here total is global variable.
# Function definition is here
def sum( param1, param2 ):
# Add both the parameters and return them."
total = param1 + param2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 1, 2 );
print "Outside the function global total : ", total
Output:
Inside the function local total : 3 Outside the function global total : 10
Modules in Python
Module in Python is a file consisting of Python code. A module can define functions, classes and variables, can also include runnable code
Module is organization of your Python code logically. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
The Python module should have name (file name) filename. py (example support.py)
def print_myfunc( param ): print "Hello : ", par return
Importing a Module to other Module
You can import a module (source file) to another module in Python, by using import statement in the destination module source file.
The import module should be present in the search path.
import module1[, module2[,... moduleN]
Here we imports several modules to the current module that we are woring.
Exmple:
Module: main.py:
# import support module to this module
import support
# call function print_func from support module as follow
support.print_func("calling from support module")
Importing from a module
You can import specific attributes (such as function) from a module into the current namespace. The from…import has the following syntax −
from modname import func1[, func2[, ... funcN]]
Example, to import the function calculate from the module num,
from num import calculate
It is possible to import all attributes from a module into the current namespace by using the following import statement −
from modname import *
Locating Modules
With importing of a module, the Python interpreter searches for the module in the following way −
- The current directory.
- If the module isn’t found, then searches each directory in the shell variable PYTHONPATH.
- If all else fails, it checks the default path. On Linux/Unix, default path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.
set PYTHONPATH = c:\python20\lib;
Namespaces and Scoping
In Python variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their values.
A Python statement can access variables in a local namespace and in the global namespace.
Python should know whether variables are local or global. It assumes that any variable assigned a value in a function is local.
To assign a value to a global variable within a function, you should first use the global statement ( global VariableName ) this tells Python that VaribaleName is a global variable:
Salary = 15000 # global scop
def IncreaseSalary():
# We say that Salary is a golobal variable NOT local
global Salary
Salary = Salary + 500
print Salary
IncreaseSalary()
print Salary
Here first print 1500 and in the second print is 2000
The dir( ) Function
The dir() is a built-in function and it returns list of modules names and all variables, functions that are defined in the modules.
# Import built-in module math import math content = dir(math) print content
Output:
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
The globals() and locals() Functions
you can use globals() and locals() as functions to return the names in the global and local namespaces depending on the location from where they are called.
If you call locals() from a function, it will return all the names that can be accessed locally from this function.
If you call globals() from a function, it will return all the names that can be accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.
Function reload()
When the module is imported into a script, the code in the top-level portion of a module is executed only once.
With reexecuting of the top-level code in a module, you should use the reload() function. The reload() function imports a previously imported module again.
reload(module_name)
Python packages
In Python a package is a file directory structure that defines a single Python application environment which consists of modules and subpackages and sub-subpackages, and so on.
Python classes
Python is an object-oriented language because of this, creating and using classes and objects objects are easy. In this part we are assumed that you have some knowledge of OOP (Object Oriented Programing) such as class, class variables, Data member, Function overloading , etc.
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows the keyword class
class ClassName: 'Optional class documentation string' class_suite
- every class has a documentation , which can be accessed via ClassName.__doc__.
- The class_suite consists of all the component statements defining class members, data attributes and functions.
Example
class Employee:
'Common base class for all employees'
empNumber = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empNumber += 1
def displayNumber(self):
print "Total Employee %d" % Employee.empNumber
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
- Variable empNumber is a class variable its value is shared in all instances of a this class. it is accessed as Employee.empNumber from inside the class or outside the class.
- The first method __init__() is class constructor or initialization method that Python calls when you create a new instance of this class.
- Other class methods are normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list of parameters ; you needn’t to include it when call of methods.
Creating Instance Objects in Python
To create instances of a class, by using class name and pass in whatever arguments in __init__ method accepts.
"first instance of Employee class" emp1 = Employee("Mery", 3000) "Second instance of Employee class" emp2 = Employee("Joe", 5500)
Accessing Attributes Python Object
To access the object’s attributes use the dot operator with object. Class variable would be accessed by using class name:
emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empNumber
You can use following functions −
- getattr(obj, name[, default]) − to access the attribute of object.
- hasattr(obj,name) − to check if an attribute exists or not.
- setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created.
- delattr(obj, name) − to delete an attribute.
Example:
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'
Python built-In Class Attributes
All Python classes keeps following built-in attributes and they can be accessed using dot operator: −
- __dict__ − Dictionary containing the class’s namespace.
- __doc__ − Class documentation string or none, if undefined.
- __name__ − Class name.
- __module__ − Module name in which the class is defined. This attribute is “__main__” in interactive mode.
- __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
For the above class:
!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
Destroying Objects (Garbage Collection) in Python
Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.
A class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.
Class Inheritance in Python
Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name.
Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite
Example:
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
# define child class
class Child(Parent):
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
Output when code is executed
Calling child constructor Calling child method Calling parent method
Conclusion
In this post I have described about the basic stones of Python programming, such as modules, classes, inheritance , functions, variables.
In my next post I will explain programming in Python
This post is part of python-step-by-step
Back to home page
Recommended: