Python language examples

# =====================================================================
# strip strings
# =====================================================================

string = "Hello World"

# Strip off newline characters from end of the string
print string.strip('\n')

strip()  # removes from both ends
lstrip()  # removes leading characters (Left-strip)
rstrip()  # removes trailing characters (Right-strip)

spacious = "   xyz   "
print spacious.strip()

spacious = "   xyz   "
print spacious.lstrip()

spacious = "xyz   "
print spacious.rstrip()

# =====================================================================
# split strings
# =====================================================================

x = 'blue,red,green'
x.split(",")
['blue', 'red', 'green']

word = "This is some random text"
words2 = word.split(" ")
print words
['This', 'is', 'some', 'random', 'text']

# =====================================================================
# replace strings
# =====================================================================

string.replace("Hello", "Goodbye")

# =====================================================================
# upper/lower case strings
# =====================================================================

string = "Hello World"

print string.lower()

print string.upper()

print string.title()

# =====================================================================
# format strings
# =====================================================================

# String formatting with %
# The percent "%" character marks the start of the specifier.

%s  # used for strings
%d  # used for numbers
%f  # used for floating point

x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x,y)

# Note: Make sure to use a tuple for the values.

# String formatting using { }

fname = "Joe"
lname = "Who"
age = "24"

#Example of how to use the format() method:

print "{} {} is {} years ".format(fname, lname, age)

#Another really cool thing is that we don't have to provide the inputs in the
#same order, if we number the place-holders.

print "{0} {1} is {2} years".format(fname, lname, age)

# =====================================================================
# testing strings
# =====================================================================

my_string = "Hello World"

my_string.isalnum()         #check if all char are numbers
my_string.isalpha()         #check if all char in the string are alphabetic
my_string.isdigit()         #test if string contains digits
my_string.istitle()         #test if string contains title words
my_string.isupper()         #test if string contains upper case
my_string.islower()         #test if string contains lower case
my_string.isspace()         #test if string contains spaces
my_string.endswith('d')     #test if string endswith a d
my_string.startswith('H')   #test if string startswith H

# =====================================================================
# built-in string methods
# =====================================================================

string.upper()              #get all-letters in uppercase
string.lower()              #get all-letters in lowercase
string.capitalize()         #capitalize the first letter
string.title()              #capitalze the first letter of words
string.swapcase()           #converts uppercase and lowercase
string.strip()              #remove all white spaces
string.lstrip()             #removes whitespace from left
string.rstrip()             #removes whitespace from right
string.split()              #splitting words
string.split(',')           #split words by comma
string.count('l')           #count how many times l is in the string
string.find('Wo')           #find the word Wo in the string
string.index("Wo")          #find the letters Wo in the string
":".join(string)            #add a : between every char
" ".join(string)            #add a whitespace between every char
len(string)                 #find the length of the string
string.replace('World', 'Tomorrow') #replace string World with Tomorrow


# =====================================================================
# boolean
# =====================================================================

number = input('Enter a number between 1 and 10: ')
if number <= 10:
    if number >= 1:
        print 'Great!'
    else:
        print 'Wrong!'
else:
    print 'Wrong!'


if number <= 10 and number >= 1:
    print 'Great!'
else:
    print 'Wrong!'

# =====================================================================
# break
# =====================================================================

from math import sqrt
for n in range(99, 0, -1):
    root = sqrt(n)
    if root == int(root):
        print n
        break
# =====================================================================
# elif
# =====================================================================

num = input('Enter a number: ')
if num > 0:
    print 'The number is positive'
elif num < 0:
    print 'The number is negative'
else:
    print 'The number is zero'

# =====================================================================
# else
# =====================================================================

broke_out = 0
for x in seq:
    do_something(x)
    if condition(x):
        broke_out = 1
        break
    do_something_else(x)
if not broke_out:
    print "I didn't break out!"


from math import sqrt
for n in range(99, 81, -1):
    root = sqrt(n)
    if root == int(root):
        print n
        break
else:
    print "Didn't find it!"

# =====================================================================
# nesting
# =====================================================================

name = raw_input('What is your name? ')
if name.endswith('Gumby'):
    if name.startswith('Mr.'):
        print 'Hello, Mr. Gumby'
    elif name.startswith('Mrs.'):
        print 'Hello, Mrs. Gumby'
    else:
        print 'Hello, Gumby'
else:
    print 'Hello, stranger'

# =====================================================================
# for
# =====================================================================

words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
    print word


numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    print number

# =====================================================================
# for dictionary
# =====================================================================

d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
    print key, 'corresponds to', d[key]


d = {'x': 1, 'y': 2, 'z': 3}
for key, value in d.items():
    print key, 'corresponds to', value


girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
letterGirls = {}
for girl in girls:
    letterGirls.setdefault(girl[0], []).append(girl)
print[b + '+' + g for b in boys for g in letterGirls[b[0]]]

# =====================================================================
# in
# =====================================================================

name = raw_input('What is your name? ')
if 's' in name:
    print 'Your name contains the letter "s".'
else:
    print 'Your name does not contain the letter "s".'


# =====================================================================
# parallel
# =====================================================================

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
    print names[i], 'is', ages[i], 'years old'

# =====================================================================
# pass
# =====================================================================

if name == 'Ralph Auldus Melish':
    print 'Welcome!'
elif name == 'Enid':
    # Not finished yet...
    pass
elif name == 'Bill Gates':
    print 'Access Denied'

# =====================================================================
# while
# =====================================================================

name = ''
while not name:
    name = raw_input('Please enter your name: ')
print 'Hello, %s!' % name


# =====================================================================
# while true
# =====================================================================

word = 'dummy'
while word:
    word = raw_input('Please enter a word: ')
    # do something with the word:
    print 'The word was ' + word


while True:
    word = raw_input('Please enter a word: ')
    if not word:
        break
    # do something with the word:
    print 'The word was ' + word

# =====================================================================
# class
# =====================================================================


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


"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

# =====================================================================
# inheritance
# =====================================================================


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


class Child(Parent):  # define child class

    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

# =====================================================================
# override class methods
# =====================================================================


class Parent:        # define parent class

    def myMethod(self):
        print 'Calling parent method'


class Child(Parent):  # define child class

    def myMethod(self):
        print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method


# =====================================================================
# doc strings
# =====================================================================

"""
Assuming this is file mymodule.py, then this string, being the
first statement in the file, will become the "mymodule" module's
docstring when the file is imported.
"""


class MyClass(object):

    """The class's docstring"""

    def my_method(self):
        """The method's docstring"""


def my_function():
    """The function's docstring"""

# =====================================================================
# exceptions
# =====================================================================

import sys

print "Lets fix the previous code with exception handling"

try:
    number = int(raw_input("Enter a number between 1 - 10 \n"))

except ValueError:
    print "Err.. numbers only"
    sys.exit()

print "you entered number \n", number


# Reference: http://www.pythonforbeginners.com