The document provides a comprehensive overview of programming in Python, covering topics such as basic syntax, data types, control structures, and functions. It includes practical examples and explanations for various programming concepts, including variables, loops, and data structures like lists, tuples, and dictionaries. Additionally, it highlights Python's features, environment setup, and applications in different fields.
Overview of Python programming provided by Rasan Samarasinghe, including topics to be covered.
High-level scripting language; features include readability, OOP support, portability, and a broad standard library.
Python's versatile applications in systems programming, GUIs, database programming, data mining, etc.
Guide on setting up Python, available on various platforms, and running scripts in different modes.
Instructions for writing and executing a simple Python 'Hello, World!' program in interactive and script modes.
Fundamentals of Python syntax including identifiers, reserved words, indentation, comments, and command-line arguments.
Key characteristics of Python variables, including dynamic typing and multiple assignment.
Overview of Python's standard data types such as Numbers, Strings, Lists, Tuples, and Dictionaries. Handling numeric data types: creation, deletion, and types of number objects in Python.Manipulation of string data: creation, accessing, updating, and common operations. Introduction to tuples, their immutable nature, creation, and accessing values.
Detailed discussion on dictionaries, their creation, accessing, updating values, and built-in functions.
Types of operators in Python: arithmetic, comparison, logical, and their precedence rules.
Control flow statements including if, else, elif, and nested if statements.
Understanding loops in Python: while and for loops, including usage of the else statement.
Introduction to control statements including break, continue, and pass.
Characteristics of number data types and their conversion methods.
Overview of math module functionalities including trigonometric and random functions.Advanced string operations including formatting, escape characters, and special operators.Detailed operations on lists, including creation, accessing, updating, and deleting elements.
Advanced operations and methods for tuples, accessing, creating, and manipulating tuples.
Concepts and operations of dictionaries including creation, accessing, and updating elements.
Handling dates and times using time and calendar modules in Python.
Overview of functions in Python, including definitions, calling methods, and different types of arguments.
Introduction to lambda functions, return statements, and variable scope within functions.
Modular programming in Python, creating modules, importing, and utilizing them.
How Python handles variable scope within different namespaces and the use of globals and locals.
Mechanisms for handling exceptions, including try-except structures and user-defined exceptions.
Fundamentals of OOP concepts in Python including classes, objects, inheritance, and encapsulation.
Programming with Python RasanSamarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
2.
Contents 1. Python Overview 2.Python Environment 3. First Python Program 4. Python Basic Syntax 5. Python Variables 6. Standard Data Types 7. Python Operators 8. Python Decision Making 9. Python Loops 10. Python Numbers 11. Python Strings 12. Python Lists 13. Python Tuples 14. Python Dictionary 15. Python Date & Time 16. Python Functions 17. Python Modules 18. Python I/O 19. Python Exceptions 20. Python OOP
3.
Python Overview • Ahigh-level, interpreted, interactive and object-oriented scripting language. • Designed to be highly readable which uses English keywords. • Fewer syntactical constructions than other languages.
4.
Features • Readability • SupportStructured / OOP Styles • Easy to learn • Easy to maintain • A broad standard library • Interactive Mode
Application of Python •Systems Programming • GUIs • Internet Scripting • Component Integration • Database Programming • Numeric and Scientific Programming • More: Gaming, Images, Data Mining, Robots, Excel..
7.
Python Environment Python isavailable on a wide variety of platforms (Windows / Linux / Mac OS) Python Official Website: http://www.python.org Install Python Setting up PATH
First Python Program Ininteractive mode programming Type and enter in Python prompt: print ("Hello, World!") Or just type and enter "Hello, World!"
10.
First Python Program Inscript mode programming Make a Python script file test.py and include code: print ("Hello, World!") In command shell run test.py file C:>python_filestest.py
11.
Python Basic Syntax PythonIdentifiers Reserved Words Lines and Indentation Multi Line Statements Quotation in Python Comments in Python Using Blank Lines Multiple Statements Command Line Arguments
12.
Python Identifiers • Identifiersare case sensitive. • Class names start with an uppercase letter • Other identifiers start with a lowercase letter. • Starting with a single leading underscore indicates private. • Starting with two leading underscores indicates strongly private. • Ends with two underscores means a language defined special name.
Lines and Indentation Blocksof code are denoted by line indentation if True: print("Good") print("Cat") else: print("Bad") print("Cat")
15.
Multi Line Statements Useof the line continuation character total = item_one + item_two + item_three
16.
Multi Line Statements Statementscontained within the [], {} or () brackets do not need to use the line continuation character. days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
17.
Quotation in Python Pythonuses quotes to denote string literals word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
18.
Comments in Python Ahash sign # that is not inside a string literal begins a comment. # first comment print ("Hello, Rasan!") # second comment
19.
Using Blank Lines •A line containing only whitespace / or comment is known as a blank line and Python totally ignores it. • In an interactive interpreter session an empty physical line used to terminate a multiline statement.
Command Line Arguments test.pyscript to access command line arguments import sys print ('Number of arguments:', len(sys.argv)) print ('Argument List:', str(sys.argv)) Run script in with arguments passed into it. C:>python_filestest.py rasan indunil samarasinghe
22.
Python Variables • Variablesdo not have to be explicitly declared to reserve memory space. • The declaration happens automatically when you assign a value to a variable.
23.
Assigning Values toVariables counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "Nuwan" # A string print (counter) print (miles) print (name)
24.
Multiple Assignment Python allowsyou to assign a single value to several variables simultaneously. a = b = c = 1 a, b, c = 1, 2, "nuwan"
Python Strings String createdwith either pairs of single or double quotes. word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
30.
Python Strings str ='Hello World!' # Prints complete string print (str) # Prints first character of the string print (str[0]) # Prints characters starting from 3rd to 5th print (str[2:5])
31.
Python Strings str ='Hello World!' # Prints string starting from 3rd character print (str[2:]) # Prints string two times print (str * 2) # Prints concatenated string print (str + "TEST")
32.
Python Lists • Alist contains items separated by commas and enclosed within square brackets []. • Lists are similar to arrays in C. • Items belonging to a list can be of different data type.
Printing Python Lists #Prints complete list print (mylist) # Prints first element print (mylist[0]) # Prints elements from 2nd till 3rd print (mylist[1:3])
35.
Printing Python Lists #Prints elements starting from 3rd print (mylist[2:]) # Prints list two times print (tinylist * 2) # Prints concatenated lists print (mylist + tinylist)
36.
Python Tuples • Consistsof a number of values separated by commas enclosed within brackets ( ). • Tuples cannot be updated.
Printing Python Tuples #Prints complete list print (mytuple) # Prints first element of the list print (mytuple[0]) # Prints elements starting from 2nd till 3rd print (mytuple[1:3])
39.
Printing Python Tuples #Prints elements starting from 3rd element print (mytuple[2:]) # Prints list two times print (tinytuple * 2) # Prints concatenated lists print (mytuple + tinytuple)
40.
Python Dictionary • Python'sdictionaries are kind of hash table type. • They work like associative arrays or hashes found in Perl and consist of key value pairs.
Print Python DictionaryValues # Prints value for 'one' key print (dic['one']) # Prints complete dictionary print (tinydic) # Prints all the keys print (tinydic.keys()) # Prints all the values print (tinydic.values())
44.
Data Type Conversion FunctionDescription int(x [,base]) Converts x to an integer. base specifies the base if x is a string. long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string. float(x) Converts x to a floating-point number. complex(real [,imag]) Creates a complex number. str(x) Converts object x to a string representation. repr(x) Converts object x to an expression string. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple.
45.
Data Type Conversion FunctionDescription list(s) Converts s to a list. set(s) Converts s to a set. dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples frozenset(s) Converts s to a frozen set. chr(x) Converts an integer to a character. unichr(x) Converts an integer to a Unicode character. ord(x) Converts a single character to its integer value. hex(x) Converts an integer to a hexadecimal string. oct(x) Converts an integer to an octal string.
Theelse Statement withWhile Loops count = 0 while count < 5: print (count, " is less than 5") count = count + 1 else: print (count, " is not less than 5")
Theelse Statement withFor Loops num = 7 for i in range(2,num): if num%i == 0: print ('%d is not a prime number' % (num)) break else: print (num, 'is a prime number')
65.
Nested for loops SYNTAX: foriterating_var in sequence: for iterating_var in sequence: statements(s) statements(s)
Python Numbers • Numberdata types store numeric values. • They are immutable data types. • Changing the value of a number data type results in a newly allocated object.
Number Type Conversion •int(x) - convert x to a plain integer. • long(x) - convert x to a long integer. • float(x) - convert x to a floating-point number.
71.
Number Type Conversion •complex(x) - convert x to a complex number with real part x and imaginary part zero. • complex(x, y) - convert x and y to a complex number with real part x and imaginary part y.
Python Strings • StringsCreated by enclosing characters in quotes. • Treats single quotes the same as double quotes. var1 = 'Hello World!' var2 = "Python Programming"
Triple Quotes Python's triplequotes allowing strings to span multiple lines. paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
84.
Raw String Raw stringsdon't treat the backslash as a special character at all. print (r'C:nowhere')
85.
Unicode String Normal stringsin Python are stored internally as 8-bit ASCII Unicode strings are stored as 16-bit Unicode. print (u'Hello, world!')
Updating Lists list =['physics', 'chemistry', 1997, 2000] print ("Value available at index 2 : ") print (list[2]) list[2] = 2001 print ("New value available at index 2 : ") print (list[2])
94.
Delete List Elements list1= ['physics', 'chemistry', 1997, 2000] print (list1) del list1[2] print ("After deleting value at index 2 : ") print (list1)
Updating Tuples tup1 =(12, 34.56) tup2 = ('abc', 'xyz') # Following action is not valid for tuples # tup1[0] = 100 # So let's create a new tuple as follows tup3 = tup1 + tup2 print (tup3)
Python Dictionary • Adictionary can store any number of Python objects. • Dictionaries consist of pairs of keys and their corresponding values. • A dictionary is mutable.
Calling a Function #Function definition def printme( str ): "This prints a passed string into this function" print (str) return # Call to printme function printme("I'm first call to user defined function!") printme("Again second call to the same function")
Pass by reference #Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]) print ("Values inside the function: ", mylist) return # Now you can call changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
129.
Pass by value #Function definition def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # assign new reference in mylist print ("Values inside the function: ", mylist) return # Call to changeme function mylist = [10,20,30] changeme( mylist ) print ("Values outside the function: ", mylist)
Required arguments # Functiondefinition def printme( str ): "This prints a passed string into this function" print (str) return # Call printme function printme(); # will generate an error
132.
Keyword arguments # Functiondefinition def printinfo( name, age ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Call printinfo function printinfo( age=50, name="miki" )
133.
Default arguments # Functiondefinition def printinfo( name, age = 35 ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return # Call printinfo function printinfo( age=50, name="miki" ) printinfo( name="miki" )
134.
Variable-length arguments # Functiondefinition def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print ("Output is: ") print (arg1) for var in vartuple: print (var) return; # Call printinfo function printinfo( 10 ); printinfo( 70, 60, 50 );
135.
Anonymous Functions • lambdakeyword used to create small anonymous functions. • Lambda forms can take any number of arguments but return just one value as an expression.
Anonymous Functions # Functiondefinition sum = lambda arg1, arg2 : arg1 + arg2; # Call sum as a function print ("Value of total : ", sum( 10, 20 )) print ("Value of total : ", sum( 20, 20 ))
138.
The return Statement •The statement return exits a function. • Optionally passing back an expression to the caller.
139.
The return Statement #Function definition def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print ("Inside the function : ", total) return total; # Call sum function total = sum( 10, 20 ); print ("Outside the function : ", total)
Scope of Variables total= 0; # This is global variable # Function definition def sum( arg1, arg2 ): total = arg1 + arg2; # Here total is local variable. print ("Inside the function local total : ", total) return total; # Call sum function sum( 10, 20 ); print ("Outside the function global total : ", total)
142.
Python Modules • Amodule allows you to logically organize your Python code. • Grouping related code into a module makes the code easier to understand and use.
143.
Creating Python Modules Codefor a module named hello normally resides in a file named hello.py hello.py file def print_func( par ): print ("Hello : ", par) return
144.
The import Statement Usinga Python file as a module by executing an import statement. SYNTAX: import module1[, module2[,... moduleN]
145.
The import Statement #Import module hello import hello # Call defined function of module as follows hello.print_func("Rasan")
The from...import *Statement Import all names from a module into the current namespace SYNTAX: from modname import *
148.
Locating Modules Sequence 1.The current directory. 2. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. 3. If all else fails, Python checks the default path. (UNIX: /usr/local/lib/python/)
149.
Namespaces and Scoping •Each function and class method has its own local namespace. • If a local and a global variable have the same name, the local variable shadows the global variable. • Therefore global statement is used to assign a value to a global variable within a function.
150.
Namespaces and Scoping Money= 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print (Money) AddMoney() print (Money)
151.
The dir( )Function The dir() function returns a sorted list of strings containing the names defined by a module. # Import built-in module math import math content = dir(math) print (content)
152.
Theglobals() and locals()Functions • A call to locals() within a function return all the names that can be accessed locally from that function. • A call to globals() within a function return all the names that can be accessed globally from that function.
153.
The reload() Function •To re-execute the top-level code in a module, you can use the reload(module_name) function. • The reload() function imports a previously imported module again.
154.
Packages in Python •A package is a hierarchical file directory structure. • It defines a single Python application environment that consists of modules and sub packages and so on.
155.
Packages in PythonExample Create 1. File Pots.py available in Phone directory having function Pots(). 2. Phone/Isdn.py file having function Isdn() 3. Phone/G3.py file having function G3()
156.
Packages in PythonExample Now, create one more file __init__.py in Phone directory __init__.py from Pots import Pots from Isdn import Isdn from G3 import G3
157.
Packages in PythonExample # Now import your Phone Package. import Phone Phone.Pots() Phone.Isdn() Phone.G3()
The raw_input Function Theraw_input() function reads one line from standard input and returns it as a string. str = raw_input("Enter your input: ") print ("Received input is : ", str) (Works only with python 2.x)
162.
The input Function input()function assumes the input is a valid Python expression and returns the evaluated result. str = input("Enter your input: "); print ("Received input is : ", str) (In Python 3.x, input() replaces raw_input())
Python Exceptions • Anexception is an event, which occurs during the execution of a program. • When a Python script encounters a situation that it can't cope with, it raises an exception.
Handling an exception SYNTAX: try: Youdo your operations here; ...................... except Exception1: If there is ExceptionI, then execute this block. except Exception2: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
178.
Except clause withno exceptions SYNTAX: try: You do your operations here; ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block.
179.
The try-finally clause SYNTAX: try: Youdo your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
180.
Argument of anException SYNTAX: try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here...
Creating Classes class Employee: 'Commonbase 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)
186.
Creating Objects # Createfirst object of Employee class emp1 = Employee("Zara", 2000) # Create second object of Employee class emp2 = Employee("Manni", 5000)
Accessing Attributes • getattr(obj,name[, default]) : access the attribute of object. • hasattr(obj,name) : check if an attribute exists or not. • setattr(obj,name,value) : set an attribute. If attribute does not exist, then it would be created. • delattr(obj, name) : delete an attribute.
189.
Built-In Class Attributes •__dict__ : Dictionary containing the class's namespace. • __doc__ : Class documentation string or None if undefined. • __name__: Class name. • __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode. • __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
190.
Destroying Objects (GarbageCollection) class Point: def __init__( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print (class_name, "destroyed")
191.
Destroying Objects (GarbageCollection) pt1 = Point() pt2 = pt1 pt3 = pt1 # prints the ids of the objects print (id(pt1), id(pt2), id(pt3)) del pt1 del pt2 del pt3
Class 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):
194.
Class Inheritance 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
195.
Class Inheritance issubclass(sub, sup): Returns true if the given subclass sub is a subclass of the superclass sup. isinstance(obj, Class) : Returns true if obj is an instance of class Class or is an instance of a subclass of Class
196.
Overriding 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
#66 for n in range(1, 100): for d in range(2, n): if n%d == 0: break else: print(n)
#67 n = 1 while n <= 100: d = 2 while d < n: if n%d == 0: break d = d+1 else: print(n) n = n+1
#74 import math x = math.acos(0.5) print(x) #------------------ import math x = math.asin(0.5) print(x)
#75 import random n = random.randrange(1,10,3) print(n) #--------------------------------------------- import random x = [5,6,4,2,6] random.shuffle(x) print(x) #--------------------------------- import random x = random.uniform(1,5) # rand between 1 and 5 print(x) #---------------------------
#182 def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception #--------------------- try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here...
#189 print(getattr(emp1, 'name')) # attribute as a string