Python Guide: From Zero to Hero Part 1

This is a detailed tutorial designed for coders who need to learn the Python programming language from scratch. In this course I will try to highlight many of Python's capabilities and features. Python is an easy-to-learn programming language.

Python

Your First Program

    >>> print "Hello World"
    Hello World
    >>>

On UNIX:

    #!/usr/local/bin/python
    print "Hello World"

Expressions

Expressions are the same as with other languages as in the following:

    1 + 3
    1 + (3*4)
    1 ** 2
    ’Hello’ + ’World’

Variables

Variables are not tied to a memory location like in C. They are dynamically typed.

    a = 4 << 3
    b = a * 4.5

if-else

    # find maximum (z) of a and b
    if a < b:
    z = b
    else:
    z = a

elif statement

PS: There is no “switch” statement.

    if a == ’+’:
    op = PLUS
    elif a == ’-’:
    op = MINUS
    elif a == ’*’:
    op = MULTIPLY
    else:
    op = UNKNOWN

The while statement

    while a < b:
    # Do something
    a = a * 2

The for statement

    for i in [3, 4, 10, 25]:
    print i
    Tuples:

Tuples are like lists, but the size is fixed at the time of creation.

    f = (2,3,4,5) # A tuple of integers

Functions

    # Return a+b
    def Sum(a,b):
    s = a+b
    return s

    # Now use it
    a = Sum(2,5) # a = 7

Files

    f = open("foo","w") # Open a file for writing
    g = open("bar","r") # Open a file for reading
    "r" Open for reading
    "w" Open for writing (truncating to zero length)
    "a" Open for append
    "r+" Open for read/write (updates)
    "w+" Open for read/write (with truncation to zero length)

Examples of string processing functions

    string.atof(s) # Convert to float
    string.atoi(s) # Convert to integer
    string.atol(s) # Convert to long
    string.count(s,pattern) # Count occurrences of pattern in s.

Up Next
    Ebook Download
    View all
    Learn
    View all