Python Primer

From Training Material
Revision as of 08:38, 2 October 2017 by Ksolis (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Nobleprog.svg


Python Primer



Python Introduction

  • Python is an interpreted language
  • Compilation steps are not needed
  • This makes it less cumbersome
  • For example class files (i.e. java) are not needed
  • Python is less complex than languages such as C++ or Java
  • Makes it easier to learn and use
  • There is a tradeoff since programs cannot be as complex

Python Primer

Invoking the Interpreter

  • The Python interpreter runs the code of a program
  • It is in the Python (c:\Python34 on my computer) folder
  • The folder that was used when installing python
  • It is python.exe
  • The python folder should be in the path environment variable
  • To run the interpreter on Windows (other systems are similar) with the path set correctly
  • Open a command prompt
  • type in the command python someFileName.py
  • This runs the program specified
  • Type in python
  • This runs python in interactive mode (see References below)
  • References
Set Environment Variables Article
Invoking the python interpreter in interactive mode

Using an IDE

  • Install an Integrated Development Environment
  • PyCharm is a good one
  • Eclipse has a plugin to allow coding in Python
  • Learn how to use it
  • Create projects and files
  • Debug the projects
  • Run the projects
References
PyCharm
PyDev plugin for Eclipse
LiClipse - Eclipse with Python and other plugins

Python Variables

  • Variables keep data i.e. integers, strings, floats
  • Memory locations used to store data
  • Python does not declare variables
  • Other languages i.e. Java do declare variables
  • This makes Python simpler to code



Variable declaration and use in Java:

int integer1 = 5;
int integer2 = 6;
float float1 = 6.75;
String myString = "This is a string";
String anotherString;

integer1 = integer2 + 7;
integer2++;
anotherString = myString + " now adding to string"; integer2++;


Variable declaration and use in Python:

variable1 = 5
variable2 = "This is a string"

variable1 = variable2 + " now adding to string"


  • Variable types are assigned when data is put into them
  • Variables can be moved between types
  • The types are:
  • numbers - integer, long, float, complex
  • String - a contiguous set of characters
  • List - items of various types, enclosed in braces [], separated by commas
  • Tuple - items of various types, enclosed in parentheses, separated by commas, read-only
  • Dictionary - contains name values pairs, a hash table



Hands on Exercise
  • Start PyCharm which we installed in a prior step
  • Using PyCharm create a project called "Python Primer"
  • Create a new file called variables a py extension will be added
  • Edit the file variables.py in PyCharm
  • Create an integer, a float, and a String as variables in the file
  • Print out the variables using print(theVariableName)
Note that the parentheses are required for Python 3 and above
Print is now a function it was a statement
  • Try various operators on the integers and floats + - / * % // **
  • Try concatenating strings

Operators

  • The standard arithmetic operators are:
+ addition
- subtraction
\* multiplication
/ division
% modulus - gives the remainder of division
// integer division gives the whole number (or rounded down)
\*\* exponents
  • Comparison operators
== example x == y -- is x equal to y (gives true or false)
!= example x != y -- is x not equal to y (gives true or false)
<> example x <> y -- same as above is x not equal to y
> example x > y -- is x greater than y
< example x < y -- is x less than y
>= example x >= y -- is x greater than or equal to y
<= example x <= y -- is x less than or equal to y
  • Logical Operators
and example x and y -- both x and y must be true to give true
or example x or y -- either x or y must be true to give true
not example not(x or y) -- reverses the condition in the parentheses
  • String operators
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
  • List operators
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
  • Dictionary Operators
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values


Hands on Exercise
  • Use the documentation of lists at Python Lists for this exercise
  • Create several Lists and use the following List operations, functions and methods
  • List access operations list[0], list[1:5], to print list values
  • Update a list value using list[someIntegerIndex] = value -- then print the list
  • Delete a list value with del list[someIntegerIndex] -- then print the list
  • Find and print the length of the list
  • Use the built-in function min to find the minimum value in the list and print it
  • Append a new value to the list
  • Insert a new value into the list at location 2
  • explain what pop does to the list and print a value that has been popped from the list
References
Python Operators

Python Syntax

Indentation

  • Indentation in Python indicates code blocks rather than beginning and ending delimiters
For example in Java code blocks are delimited by braces i.e. {}
  • All statements in a block must have the same indentation
The default indentation is four spaces

Identifier naming convention (taken from TutorialsPoint.com):

  • Class names start with an uppercase letter and all other identifiers with a lowercase letter.
  • Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Multiline Statements (taken from TutorialsPoint.com)

total = item_one + \
        item_two + \
        item_three

Use of Quotes

  • Strings in Python can use single, double, or triple quotes
string1 = 'This is a string'
string2 = "This is a string"
string3 = '''This is a
multiline string'''
string4 = """This is also a
multiline string"""

Comments

  • the pound sign/hash mark "#" is used for single line comments
  • Three single or double quotes are used for multiline comments
#This is a single line comment
#This is a second single line comment

'''This is
a multiline comment'''

"""This is also
a multiline comment"""

Multiple Statement on a Single Line

  • use semicolons as the delimiter between statements
a = b+1; c = d + 2; print(str(a))

Control Structures

  • if statement - a conditional statement that can have an else clause
  • note that the sub-statements of the if statement are indented
  • the normal default for indenting is four spaces
a = 10
if (a == 10):
    print("In if statement")
a = 10
if (a == 10):
    print("In if statement")
else:
    print("In else statement")
  • while loop - a loop that continues until the loop condition has been satisfied
a = 10
while (a < 15):
    print("in while loop")
    a += 1
  • while loop with else statement
a = 10
while (a < 15):
    print("in while loop")
    a = a + 1
else:
    print("while loop has ended")
  • for loop
the general form of the for loop is
for iterating_var in sequence:
    statements(s)
Where iterating_var is the name of the variable
that represents the next item in the sequence to be
used in the statements of the for loop
  • An example of a sequence and a for loop that iterates through the sequence
animals = ['dog','cats','moose','deer','bear']

for theAnimal in animals:
    print("the animal is a " + theAnimal)
  • An example of a sequence and an iteration using the index in the list
animals = ['dog','cat','moose','deer','bear']

for index in range (len(animals)):
    print("Using an index the animal is a " + animals[index])

Hands on Exercise

  • Create a simple program using PyCharm that has a while loop and an if else statement
  • The program will do the following
The while loop will loop 10 times.
The if else statements will be in the while loops code block
The if else statements will print out "In the if statement" for the first 5 iterations
The if else statements will print out "In the else statement" for the last 5 ieterations

Functions

  • A function is a piece of reusable code
Generally it performs an identifiable action that can be reused
For example opening, writing to, or closing a file
It provides modularity for the code making it easier to understand
There are standard functions provided with Python
New functions can be defined by programmers (user-defined functions)
  • How to define a function
Functions begin with the keywork def, followed by the function name, and then a set of parentheses ()
Input parameters are placed within the parentheses ()
The first statement can be an optional documentation string (docstring)
The code block starts with a colon : and is indented
  • Example of a Function
def theFunctionName(parameters):
   "function_docstring"
   function statements
   return [expression]

Built-in and Standard Library Functions

There are a number of functions that are built-in in Python

See the Python Documentation on Build-in Functions in the References below
These are part of the Standard Library

There are also a number of other modules in the standard library

These give solutions to many everyday programming problems
  • Build-in Functions can be called directly in the code
Example of using Built-in Functions
f = open('workfile', 'w')
f.write("this is the file output")
f.close()
  • Standard Library functions must be imported
Example of using Standard Library Functions
from math import sqrt

a = sqrt(24)
print (a)


References
Built-in Functions
Standard Library Including Built-in Functions

PythonScope

  • A Variable's scope
Python has only function, global, and class scope.
It does not have block scope
For example a variable first used in a for loop can be seen outside the for loop
In many other languages such as Java, C++, and C a variable declared in a block has block scope
  • Function scope vs global scope
globalVar = "this string is global" #creates a global variable

def anotherFunction ()
    globalVar = "this string is local" #creates a variable local to the function

Importing External Modules

The import statement

  • Bring the functions within a file into the program

Example of code import

Assume that the file importFunctions.py has the following code

def print_value(parameter):
    print("the value is " + parameter)
    return

To use this code in another file it must imported then used

#import the functions from importFunctions
import importFunctions

#use the print_value function
importFunctions.print_value("Print This String")


The from import statement

  • Bring the functions within a file into the program
  • Allow the use of the functions without the leading filename

Example of the from import statement

Assume that the file importFunctions.py has the following code

def print_value(parameter):
    print("the value is " + parameter)
    return

To use this code in another file it must imported then used

#from import the functions
from importFunctions import print_value

#use the print_value function without the leading filename
print_value("Print This String")

Object Oriented Classes

  • Python has classes which makes it object oriented
Note that it also has functions so it is also a functional language
  • Overview of Object Oriented Programming (OOP)
Class - a user defined template for objects.  Contains both variables and methods.
        Classes allow libraries of well tested self contained code to be distributed.
        Each of these self contained units is a class.
Class Variable - In Python it is a variable that is shared by all instances of a class
                 Objects are instances of classes.
Data Member - A class variable or instance variable that holds data
Functions Overloading - A set of functions of the same name with varying parameter types.
                        Each function can have different code
Instance Variable - a variable defined within a method of a class.  Variables defined
                    outside of the classes methods are class variables (see above).
Inheritance - A class will inherit the methods of a class from which it is derived.
              See the section below on inheritance
Instance - A object that has been created from a class template.  It is an object of
           that class.
Instantiation - The creation of an object from a class template
Method - A special type of function that belongs to and is coded within a class
Object - A unique instance of a class.  An object has both data members and methods.

Class Definitions

  • The form of a class definition is as follows
class ClassName
   classData = "this could be any data"
   def __init__(self):
    self.someData = []
   def someFunction(self, parameter1, parameter2):
       statement1
       statement2
       ...
       return returnValue
    • self is not a keyword it is just an indication that the first argument passed into a function is a reference to the object (it is just called self for convenience).
    • The function __init__ is the constructor for the class that runs when a class instance is created
    • The statement self.someDate create a list that belongs to the instance object
    • The statement classData = "this could be any data" creates a class variable shared across instance objects of the class

Class Variable Scope

  • Class variables have a scope across all instance objects of the class
  • Instance variables have scope within an instance object of the class
Instance variable are defined within class methods (functions in the class)

See Reference Python Tutorial on Classes

Read the section on Namespaces for a better understanding of variable scope
Read the section on Class and Instance Variables for a better understanding

Example of a class

class Dog:
    kind = 'canine'         # class variable shared by all instances
    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

Use of the class to understand variable scope

dog1 = Dog('fido')
dog2 = Dog('Buddy')
print(dog1.name)    # will give name of Fido which is an instance variable
print(dog1.kind)    # will give a kind of canine which is a class variable
print(dog2.name)    # will give a name of Buddy which is an instance variable
print(dog2.kind)    # will give a kind of canine which is a class variable
  • Note that there is no concept of public and private variables
For example java has public and private keywords, Python does not
There is a convention that states:
Variables and functions that begin with an underscore (i.e. _variable1)
should be treated as private and not public

Class Inheritance

  • A class can inherit methods and data from other classes
  • The definition of the class looks like:
class DerivedClassName(BaseClassName):

    def __init__(self, etc.):
         statement1
         ...

    def function1()
        statement1
        ...
        return somevalue


Note: the class will inherit the attributes of BaseClassName

References

Python main site
Phython.org Documentation
Beginners Programming Guides
TutorialsPoint.com Python Tutorial