Академический Документы
Профессиональный Документы
Культура Документы
Functions:
Syntax of a function :
'Function documentation'
function_body
return <value>
def square(x):
return x**2
There are many built-in functions Python offers. Here are some of them listed.
Sample Iterator
x = [6, 3, 1]
s = iter(x)
print(next(s)) # -> 6
print(next(s)) # -> 3
print(next(s)) # -> 1
print(next(s)) # -> StopIteration Error
List Comprehensions
Alternative to for loops.
Used to:
Example
x = [6, 3, 1]
Example
x = [6, 3, 1]
print(next(g)) # -> 36
Python does not allow non key word arguments after keyword arguments. A
combination of keyword and non keyword arguments can be passed to a fuction
non keyword variables are stored in tuple where as keywords variables are stored in
dictionary
Introduction to OOP
Object-oriented programming can model real-life scenarios and suits developing
large and complex applications.
Object
In real life, an object is something that you can sense and feel. For example Toys,
Bicycles, Oranges and more.
Defining Classes
Class
Syntax
class_body
Example
class Person:
pass
Creating Objects
An object is created by calling the class name followed by a pair of parenthesis.
class Person:
pass
The output of print on object p1, tell you what class it belongs to and hints on
memory address it is referenced to.
Setting Attributes
You can set attributes, one a time, to an instantiated object and access it using
the dot notation.
class Person:
pass
p1 = Person()
p1.fname = 'Jack'
p1.lname = 'Simmons'
You can also set multiple attributes, at once, by defining the initializer method,
__init__, inside the class.
It takes values passed inside the parenthesis, during an object creation, as it's
arguments.
It also takes self as the first argument, which refers to the current object.
class Person:
self.fname = fname
self.lname = lname
p1 = Person('George', 'Smith')
class Person:
self.fname = fname
self.lname = lname
p1 = Person('George', 'Smith')
print(p1.fname, '-', p1.lname) # -> 'George - Smith'
Understanding a Class
Once documented, you can load the script into an interactive interpreter and run
help command on Person class.
>>>help(Person)
class Person(builtins.object)
| Represents a person.
To create a child class, specify the parent class name inside the pair of
parenthesis, followed by it's name.
Example
class Child(Parent):
pass
Every child class inherits all the behaviours exhibited by their parent class.
In Python, every class uses inheritance and is inherited from object by default.
Definition 1
class MySubClass:
pass
####Definition 2
class MySubClass(object):
pass
Inheritance in Action
class Person:
self.fname = fname
self.lname = lname
class Employee(Person):
all_employees = []
self.empid = empid
Employee.all_employees.append(self)
p1 = Person('George', 'smith')
Output
George - smith
Jack - 456342
John - 123656
In above example, Employee class utilises __init __ method of parent class Person,
to create it's object.
The following example extends list and creates EmployeesList, which can identify
employees, having a given search word in their first name.
Example 2
class EmployeesList(list):
matching_employees = []
if name in employee.fname:
matching_employees.append(employee.fname)
return matching_employees
class Employee(Person):
all_employees = EmployeesList()
self.empid = empid
Employee.all_employees.append(self)
Example
class Employee(Person):
all_employees = EmployeesList ()
self.empid = empid
Employee.all_employees.append(self)
def getSalary(self):
def getBonus(self):
class ContractEmployee(Employee):
def getSalary(self):
def getBonus(self):
print(e1.getBonus())
print(e2.getBonus())
Output
Encapsulation allows binding data and associated methods together in a unit i.e
class.
A good example is a television set. We don�t need to know the inner workings of a
TV, in order to use it. All we need to know is how to use the remote control (i.e
the interface for the user to interact with the TV).
class Employee(Person):
all_employees = EmployeesList()
self.__empid = empid
Employee.all_employees.append(self)
def getEmpid(self):
return self.__empid
print(e1.fname, e1.lname)
print(e1.getEmpid())
print(e1.__empid)
Output
Jack simmons
456342
Exceptions
An exception is an error that occurs during execution of a program.
Python allows a programmer to handle such exceptions using try ... except clauses,
thus avoiding the program to crash.
Some of the python expressions, though written correctly in syntax, result in error
during execution. Such scenarios have to be handled.
In Python, every error message has two parts. The first part tells what type of
exception it is and second part explains the details of error.
Handling Exception
Python handles exceptions using code written inside try ... except blocks.
The code to be handled is written inside try clause and the code to be executed
when an exception occurs is written inside except clause.
Raising Exceptions
raise keyword is used when a programmer wants a specific exception to occur.
Example 2
try:
a = 2; b = 'hello'
c = a**b
except TypeError as e:
print(e)
Output
Python also allows a programmer to create custom exceptions, derived from base
Exception class.
Example 1
class CustomError(Exception):
self.value = value
def __str__(self):
return str(self.value)
User Defined Exceptions
Example 1 continued ...
try:
a = 2; b = 'hello'
c = a**b
except CustomError as e:
print(e)
Output
All the statements under finally clause are executed irrespective of exception
occurrence.
Example 1
def divide(a,b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Dividing by Zero.")
finally:
print('First call')
print(divide(14, 7))
print('Second call')
print(divide(14, 0))
Output
First call
In finally clause.
2.0
Second call
Dividing by Zero.
In finally clause.
None
Statements under else clause are executed only when no exception occurs in try
clause.
Example 2
try:
a = 14 / 7
except ZeroDivisionError:
print('oops!!!')
else:
print('First ELSE')
try:
a = 14 / 0
except ZeroDivisionError:
print('oops!!!')
else:
print('Second ELSE')
Output
First ELSE
oops!!!
Introduction to a Module
Any file containing logically organized Python code can be used as a module.
A module generally contains any of the defined functions, classes and variables. A
module can also include executable code.
Any Python source file can be used as a module by using an import statement in some
other Python source file.
Usage of a Module
seed is an importance feature associated with random experiments. The seed is set
in order to reproduce the output of a random experiment at a later stage.