Basics of Python

This is a basic python tutorial (basic enough to let you start with OpenStack)

Topics covered

  1. Introduction
  2. Basic Syntax
  3. Data types and variables
  4. Loops and conditionals
  5. Functions and Methods
  6. Classes and objects
  7. Python Specifics

Introduction

  1. Python is an easy to learn, powerful programming language
  2. Dynamic type
  3. Interpreted
  4. Can be extended using C or C++
  5. Comes with a large standard library that covers areas such as string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystems, TCP/IP sockets).
  6. Standard modules and packages from : http://pypi.python.org/pypi
  7. Download and install from here: http://www.python.org/download/releases/2.7.3/
  8. FAQ on python: http://docs.python.org/2/faq/general.html
  9. Python Success Stories: http://www.python.org/about/success/

Basic Syntax

  1. Files should have the extension “.py”. They are called modules
    e.g.
    my_first_program.py
  2. The file can have any name, any number of classes and methods.
  3. There are no braces {} or semicolons ; in python. It is a very high level language. Instead of braces, blocks are identified by having the same indentation.
  4. The program execution starts from main.
  5. if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value ”__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.
  6. Comments start with ‘#’ symbol, and there no block comments in python
  7. e.g.

Data types and variables

  1. Variables do not need to be declared and their data-types are inferred from the assignment statement.
  2. e.g.

  3. Python supports the following data types:
    • Boolean:
      • True
      • False
    • Integer
    • long
    • float
    • String
    • List:
      • A list is a mutable sequence of mixed data type.
      • mix = [1, 2, "solaris", (1, 2, 3)]
    • Tuple:
      • A tuple is an immutable sequence of mixed data type.
      • mix = (1, 2, "solaris", (1, 2, 3))
      • return (3 + 7)# This is an expression
      • return (3 + 7, ) # This is a tuple
    • Set:
      • A set is an unordered collection of data with no duplicate elements.
      • A set supports operations like union, intersection or difference.
      • set1 = set([‘a’, ‘b’, ‘c’, ‘c’, ‘d’])
      • set2 = set([‘a’, ‘b’, ‘x’, ‘y’, ‘z’])
      • set supports operations like union, intersection or difference. Similar as in Mathematics.
    • Dictionary:
      • A Python dictionary is a group of key-value pairs. The elements in a dictionary are indexed by keys. Keys in a dictionary are required to be unique.
      • Diction = {1: 'cat', 2:'apple'}
    • Object
    • None

Loops and conditionals

  1. if:
    if expr: statement
  2. if-else:

    if expr: statement1
    else: statement2
    if-elseif: if expr: statement1
    elif expr: statement2
    else: statement3
  3. Multiple elifs can be included in the same if statement. There is no switch or case statement so multiple elifs must be used instead. While parenthesis are not required around the expression, they can be used.
  4. Loops
    • For:
      for var in range(start [,stop [,inc]]): statements
      var can be any variable. The range statement can take start and stop values, and an increment.
    • while:

      while expr: statements

      Executes statements while the expression is true.
    • continue: continue
      Skips the rest of the body of the loop for the current iteration and continue execution at the beginning of the next iteration.
    • break: break
      Ends the execution of the current loop.
    • else: else
      for and while loops can both have else clauses, which are executed after the loop terminates normally by falsifying the conditional, but else clauses are not executed when a loop terminates via a break statement.
    • foreach: for x in array: statements
      Loops over the array given by array. On each iteration, the value of the current element is assigned to x and the internal array pointer is advanced by one.

Functions

    1. Definition: Functions in Python are defined with the following syntax:

      def myfunct(arg_1, arg_2, ..., arg_n):
      return value
    2. Any Python code, including other function and class definitions, may appear inside a function. Functions may also be defined within a conditional, but in that case the function’s definition must be processed prior to its being called.
    3. Python does not support function overloading but does support variable number of arguments, default arguments, and keyword arguments.
    4. Return types are not specified by functions.
    5. Arguments: Function arguments are passed by value so that if you change the value of the argument within the function, it does not get changed outside of the function. If you want the function to be able to modify non-local variables, you must declare them as global in the first line of the function. Note that if you declare any variables as global, that name cannot be reused in the argument list, i.e. this would cause an error:
    6. Default Arguments: A function may define default values for arguments. The default must be a constant expression or array and any defaults should be on the right side of any non-default arguments.

      def person_name(n = 'Abhi'):
      return n + " Rocks!!"

      If this function is called with person_name(), it will return Abhi Rocks!!, Otherwise, if it is called with person_name(“John”), it will return John Rocks!!
    7. Variable length argument lists: Variable length arguments are supported by being wrapped up in a tuple. Before the variable number of arguments, zero or more normal arguments may occur:The special syntax, *args and **kwargs in function definitions is used to pass a variable number of arguments to a function. The single asterisk form (*args) is used to pass a non-keyworded, variable-length argument list, and the double asterisk form is used to pass a keyworded, variable-length argument list.
    8. e.g.

    9. Return: Values are returned from the function with the return command: return var. You can’t return multiple values, but that can be achieved by returning an array or object.

Return immediately ends execution of the function and passes control back to the line from which it was called.

  1. Variable Functions: Python supports the concept of variable functions. That means that if a variable can point to a function instead of a value. Objects within a method can be called similarly.

Classes and Objects

  1. The simplest form of class definition looks like this:
    class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>
  2. The class instantiation calls the __init__ method of the class which can be over written:
  3. The argument self tells that method is a class method
  4. Inheritance:class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

Python Specifics

  1. Packages
    • Packages are a way of structuring Python’s module namespace by using “dotted module names”.
    • Every package has __init__.py module which is empty bydefault.
    • The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.
  2. Importing * From a Package: Will import only those modules which have been listed in __all__ variable in the __init__.py module of the package.
    e.g. __all__ = ['mod1', 'mod2']
  3. Decorators:
    • Decorators allow you to inject or modify code in functions or classes.
    • The actual method is compiled with the decoration and is substituted
    • A simple e.g. to illustrate decorator
Advertisements

About Abhishek Srivastava
A coder, a gamer, a guitarist, an opensource enthusiast...

One Response to Basics of Python

  1. Dina says:

    You Sir/Madam are the enemy of confusion eveehwyerr!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: