Python

Projected Time

1-4 Hours

Prerequisites

Motivation

Python is a widely used and very powerful programming language.

Objectives

Specific Things to Learn

Materials

Lessons

Basic Syntax

Blocks of code are indicated by line separations and indentation instead of curly braces or semi-colons like other languages.

if True:
    print "True"
else:
    print "False"

Statements in python typically end with a new line, but you can construct multi-line statements with a backslash.

total = item_one + \
        item_two + \
        item_three

Python accepts single (’), double (“) and triple (’’’ or”"") quotes to denote string literals, as long as the same type of quote starts and ends the string.

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments begin with a hashtag (#)

# This is a comment

When assigning variables, you do not need to indicate their type.

name = "Fred"
age = 31

Variables and Data Types

Python supports the following data types:

Functions

Functions in python are defined by the word “def” and return values using the return statement.

def add_one(num):
    return num + 1

Operators

-Identical: is, is not

-Membership: in, not in

String Operators

name = "Lee"
sample_string = "This is a string."
sample_low = sample_string.lower()  # "this is a string"
sample_up = sample_string.upper()  # "THIS IS A STRING"
sample_string = "This is a string."
split_string = sample_string.split()  # ['This', 'is', 'a', 'string.']

Conditionals

If Statements

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement, which has the general form:

if BOOLEAN EXPRESSION:
    STATEMENTS

A few important things to note about if statements:

If Else Statements

It is frequently the case that you want one thing to happen when a condition it true, and something else to happen when it is false. For that we have the if else statement.

if food == 'spam':
    print('Ummmm, my favorite!')
else:
    print("No, I won't have it. I want spam!")
Chained Conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

if x < y:
    STATEMENTS_A
elif x > y:
    STATEMENTS_B
else:
    STATEMENTS_C

For Loops

The for loop processes each item in a sequence, so it is used with Python’s sequence data types - strings, lists, and tuples.

Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed.

The general form of a for loop is:

for LOOP_VARIABLE in SEQUENCE:
    STATEMENTS

While Statement

Like the branching statements and the for loop, the while statement is a compound statement consisting of a header and a body. A while loop executes an unknown number of times, as long at the BOOLEAN EXPRESSION is true.

while BOOLEAN_EXPRESSION:
    STATEMENTS

Classes

Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stress on objects.

Object is simply a collection of data (variables) and methods (functions) that act on those data. And, class is a blueprint for the object.

We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.

As many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

Simple Example:

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

Common Mistakes / Misconceptions

Be very careful where you place indentations because the wrong code could get excecuted or you could have errors.

Sample:

if x == 1:
    print 'equal'
else:
    print 'not equal'
print 'always executed'

Guided Practice

Independent Practice

Challenge

Check for Understanding

Create a class with methods that utilize each of the lessons learned above.