Python (basic)

Sabyasachi Moitra
Sabyasachi MoitraResearch Scholar um Techno India University, West Bengal
Python
(Basic)
Sabyasachi Moitra
Ph.D. Scholar(Techno India University)
Introduction
CompilingandInterpreting
FirstPythonProgram
OVERVIEW
Introduction
Developed by Guido van Rossum in the early 1990s.
Features:
• High-level powerful programming language
• Interpreted language
• Object-oriented
• Portable
• Easy to learn & use
• Open source
• Derived from many other programming languages
3
Introduction (2)
Uses:
• Internet Scripting
• Image Processing
• Database Programming
• Artificial Intelligence
…..
4
Compiling and Interpreting
• Many languages compile (translate) the program into a
machine understandable form.
• Python is directly interpreted into machine instructions.
5
compile execute
----------> ---------->
Source code Intermediate code Output
interpret
---------->
Source code Output
Compiling and Interpreting (2)
Compiler Interpreter
Scans the entire program and
translates it as a whole into machine
code.
Translates program one statement at a
time.
It takes large amount of time to analyze
the source code but the overall
execution time is comparatively faster.
It takes less amount of time to analyze
the source code but the overall
execution time is slower.
Generates intermediate object code
which further requires linking, hence
requires more memory.
No intermediate object code is
generated, hence are memory
efficient.
It generates the error message only
after scanning the whole program.
Hence debugging is comparatively
hard.
Continues translating the program until
the first error is met, in which case it
stops. Hence debugging is easy.
Programming language like C, C++ use
compilers.
Programming language like Python,
Ruby use interpreters.
6
First Python Program
(Hello.py)
7
Output
8
InteractiveModeProgrammingVSScriptModeProgramming
Identifiers
ReservedWords
LinesandIndentation
SomemoreBasicSyntax
BASIC SYNTAX
Interactive Mode Programming
VS Script Mode Programming
Interactive Mode Programming Script Mode Programming
Invoking the interpreter without
passing a script file as a parameter
brings up the Python prompt. Type a
python statement at the prompt and
press Enter.
Invoking the interpreter with a script
parameter, & begins execution of the
script and continues until the script is
finished. When the script is finished,
the interpreter is no longer active
(assuming that user have Python
interpreter set in PATH variable).
C:Usersmoitra>python
Python 2.7.13 (v2.7.13:a06454b1afa1,
Dec 17 2016, 20:42:59) [MSC v.1500
32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or
"license" for more information.
>>> print("Hello World")
Hello World
G:2.
DOCUMENTSPythonPrograms>pytho
n test.py
Hello World
10
Identifiers
• A Python identifier is a name used to identify a variable,
function, class, module or other object.
• An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores
and digits (0 to 9).
• Python does not allow punctuation characters such as @, $,
and % within identifiers.
• Python is a case sensitive programming language.
Manpower and manpower are two different identifiers in
Python.
11
Reserved Words
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
and exec not
12
Lines and Indentation
• Python provides no braces to indicate blocks of code for class
and function definitions or flow control. Blocks of code are
denoted by line indentation.
• The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount.
13
Correct Erroneous
if True:
print "True"
else:
print "False"
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Basic Syntax (5)
Example
Multi-Line Statements total = item_one + 
item_two + 
item_three
Comments in Python print "Hello World" # comment
Multiple Statements on a Single Line x = 'foo'; print(x + 'n')
…..
14
StandardDataTypes
OtherOperations
SomeTypeConversions
VARIABLE TYPES
Standard Data Types
Standard Data Type Example
Numbers
counter = 100
miles = 1000.0
String name = "John"
List tinylist = [123, 'john']
Tuple tinytuple = (123, 'john')
Dictionary
tinydict = {'name': 'john','code':6734,
'dept': 'sales'}
16
Other Operations
Operation Example
Multiple Assignment
a = b = c = 1
a,b,c = 1,2,"john"
Delete del var1[,var2[,var3[....,varN]]]]
17
Some Type Conversions
Function Description
int(x) Converts x to an integer number
str(x) Converts x to a string representation
list(s) Converts s to a list
tuple(s) Converts s to a tuple
dict(d) Creates a dictionary d
…..
TypesofOperator
BASIC OPERATORS
Types of Operator
Type Operators
Arithmetic Operators
+, -, *, /, %, ** (exponent), // (floor
division)
Relational Operators ==, !=, >, <, >=, <=
Assignment Operators =, +=, -=, *=, /=, %=, **=, //=
Logical Operators and, or, not
Bitwise Operators &, |, ~, ^, <<, >>
Membership Operators in, not in
Identity Operators is, not is
19
Addition of two nos.
add.py
#addition of two numbers
a=raw_input("Enter 1st no.: ")
b=raw_input("Enter 2nd no.: ")
c=int(a)+int(b)
print('The sum of {0} and {1} is {2}'.format(a, b, c))
Output
G:2. DOCUMENTSPythonPrograms>python add.py
Enter 1st no.: 1
Enter 2nd no.: 2
The sum of 1 and 2 is 3
20
Simpleifstatement
if…elsestatement
nestedifstatement
elif Statement
DECISION MAKING
Simple if statement
simple_if.py
#even no. check
a=input("Enter a no: ")
if(a%2==0):
print('{0} is even'.format(a))
Output
22
if even if not even
G:2.
DOCUMENTSPythonPrograms
>python simple_if.py
Enter a no: 10
10 is even
G:2.
DOCUMENTSPythonPrograms
>python simple_if.py
Enter a no: 11
if…else statement
if_else.py
#even-odd no. check
a=input("Enter a no: ")
if(a%2==0):
print('{0} is even'.format(a))
else:
print('{0} is odd'.format(a))
Output
23
if even if not even
G:2.
DOCUMENTSPythonPrograms
>python if_else.py
Enter a no: 10
10 is even
G:2.
DOCUMENTSPythonPrograms
>python if_else.py
Enter a no: 11
11 is odd
nested if statement (nested_if.py)
24
Output
25
elif Statement (else_if_ladder.py)
26
Output
27
while Loop
forLoop
nestedLoop
LOOPING
while Loop
while_loop.py
i=1
while(i<=5):
print(i)
i=i+1
Output
G:2. DOCUMENTSPythonPrograms>python while_loop.py
1
2
3
4
5
29
for Loop
for_loop.py
for i in range(1,6):
print(i)
Output
G:2. DOCUMENTSPythonPrograms>python for_loop.py
1
2
3
4
5
30
nested Loops (prime_factor.py)
31
Output
32
NumericalTypes
NumericFunctions
MathematicalConstants
PYTHON NUMBERS
Python Numbers (1)
• Python supports four different numerical types:
• Python also includes some predefined numeric functions:
34
int long float complex
10 51924361L 15.20 -.6545+26J
Type Function Description Example
Mathematical
pow(x, y) The value of
x**y
import math
print
"math.pow(2, 4)
: ", math.pow(2,
4)
math.pow(2, 4) : 16.0
abs(x) The absolute
value of x
print "abs(-45)
: ", abs(-45)
abs(-45) : 45
…..
Python Numbers (2)
Type Function Description Example
Random Number
choice(seq) A random item
from a list, tuple,
or string
import random
print "choice([1, 2,
3, 5, 9]) : ",
random.choice([1, 2,
3, 5, 9])
choice([1, 2, 3, 5, 9]) : 2
shuffle(lst) Randomizes the
items of a list in
place. Returns
None
import random
list = [20, 16, 10,
5];
random.shuffle(list)
print "Reshuffled
list : ", list
Reshuffled list : [16, 5, 10, 20]
…..
35
Python Numbers (3)
Type Function Description Example
Trigonometric
sin (x) Return the sine of
x radians
import math
print "sin(3) : ",
math.sin(3)
sin(3) : 0.14112000806
cox (x) Return the cosine
of x radians
import math
print “cos(3) : ",
math.cos(3)
sin(3) : 0.14112000806
…..
36
Python Numbers (4)
• Python also supports two mathematical constants:
pi
e
37
Example
Built-inStringMethods
PYTHON STRINGS
Python Strings (1)
str = 'Hello World!'
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
print "Updated String :- ", str[:6] + 'Python'
Output
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Updated String :- Hello Python
39
Python Strings (2)
40
Python includes some built-in methods to manipulate strings:
String Method Description Example
capitalize() Capitalizes first letter of
string
str = "this
is string
example....wo
w!!!";
print
"str.capitali
ze() : ",
str.capitaliz
e()
str.capitalize() : This
is string
example....wow!!!
len() Returns the length of the
string
str = "this
is string
example....wo
w!!!";
print "Length
of the
string: ",
len(str)
Length of the
string: 32
…..
Example
BasicListOperations
FunctionsVSMethods
Built-inListFunctions
Built-inListMethods
PYTHON LISTS
Python Lists (1)
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] # Prints last 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
list[0] = 'efgh'; # updating list
print list
del list[2]; # deleting list element
print list 42
Python Lists (2)
Output
['abcd', 786, 2.23, 'john', 70.2]
abcd
70.2
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
['efgh', 786, 2.23, 'john', 70.2]
['efgh', 786, 'john', 70.2]
43
Python Lists (3)
Other Basic List Operations
44
Expression Result Description
len([1, 2, 3]) 3 Length
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]:
print x,
1 2 3 Iteration
Functions VS Methods
Function Method
A function is a piece of code that is
called by name.
A method is a piece of code that is
called by name that is associated with
an object.
It can pass data to operate on (i.e., the
parameters) and can optionally return
data (the return value).
It is able to operate on data that is
contained within the class.
All data that is passed to a function is
explicitly passed.
It is implicitly passed for the object for
which it was called.
def sum(num1, num2):
return num1 + num2
class Dog:
def my_method(self):
print "I am a Dog"
dog = Dog()
dog.my_method() # Prints "I am a
Dog"
45
Python Lists (4)
Some Built-in List Functions
46
Function Description Example
max(list) Returns item from
the list with max
value.
list = [456, 700, 200]
print "Max value
element : ", max(list)
Max value element : 700
min(list) Returns item from
the list with min
value.
list = [456, 700, 200]
print "Min value
element : ", min(list)
Min value element : 200
…..
Python Lists (5)
Some Built-in List Methods
47
Method Description Example
list.append(obj) Appends a
passed obj into the
existing list.
aList = [123, 'xyz',
'zara', 'abc'];
aList.append( 2009 );
print "Updated List :
", aList
Updated List : [123, 'xyz', 'zara',
'abc', 2009]
list.count(obj) Returns count of
how many
times obj occurs in
list.
aList = [123, 'xyz',
'zara', 'abc', 123];
print "Count for 123 :
", aList.count(123)
print "Count for zara :
", aList.count('zara')
Count for 123 : 2
Count for zara : 1
…..
Example
BasicTupleOperations
Built-inTupleFunctions
ListsVSTuples
PYTHON TUPLES
Python Tuples (1)
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete tuple
print tuple[0] # Prints first element of the tuple
print tuple[-1] # Prints last element of the tuple
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints tuple two times
print tuple + tinytuple # Prints concatenated tuples
49
Python Tuples (2)
Output
('abcd', 786, 2.23, 'john', 70.2)
abcd
70.2
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
50
Python Tuples (3)
Other Basic Tuple Operations
51
Expression Result Description
len((1, 2, 3)) 3 Length
3 in (1, 2, 3) True Membership
for x in (1, 2, 3):
print x,
1 2 3 Iteration
Python Tuples (4)
Some Built-in Tuple Functions
52
Function Description Example
max(tuple) Returns item from
the tuple with max
value.
tuple = (456, 700, 200)
print "Max value
element : ", max(tuple)
Max value element : 700
min(tuple) Returns item from
the tuple with min
value.
tuple = (456, 700, 200)
print "Min value
element : ", min(tuple)
Min value element : 200
…..
Lists VS Tuples
Lists Tuples
Lists are enclosed in brackets ( [ ] ). Tuples are enclosed in parentheses ( ( )
).
Lists' elements and size can be
changed.
Tuples' elements and size cannot be
changed.
Support item deletion.
Example
list = [123, 'john']
print list
del list[1]
print list
[123, 'john']
[123]
Doesn't support item deletion.
Example
tuple = (123, 'john')
print tuple
del tuple[1]
print tuple
(123, 'john')
Traceback (most recent call last):
File "main.py", line 6, in
del tuple[1]
TypeError: 'tuple' object doesn't support item deletion
53
Introduction
Example
PropertiesofDictionaryKeys
Built-inDictionaryFunctions
Built-inDictionaryMethods
PYTHON DICTIONARY
Python Dictionary (1)
• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes found in PHP and
Perl respectively.
• It consists of key-value pairs.
• A dictionary key can be almost any Python type, but are
usually numbers or strings, & values can be any arbitrary
Python object.
• Dictionaries are enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces ([]).
55
Python Dictionary (2)
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
tinydict['name']="Peter" # update existing entry
tinydict['org']="abcd" # Add new entry
print tinydict
del dict[2]; # remove entry with key 2
print "dict: ", dict
dict.clear(); # remove all entries in dict
print "dict: ", dict
del dict ; # delete entire dictionary
print "dict: ", dict
56
Python Dictionary (3)
Output
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
{'dept': 'sales', 'code': 6734, 'name': 'Peter', 'org': 'abcd'}
dict: {'one': 'This is one'}
dict: {}
dict:
57
Properties of Dictionary Keys
• More than one entry per key not allowed, i.e., no duplicate
key is allowed. When duplicate keys encountered during
assignment, the last assignment wins.
• Keys must be immutable. Which means you can use strings,
numbers or tuples as dictionary keys but something like ['key']
is not allowed.
58
Python Dictionary (4)
Some Built-in Dictionary Functions
59
Function Description Example
len(dict) Gives the total
length of the
dictionary.
dict = {'Name': 'Zara',
'Age': 7};
print "Length : %d" %
len (dict)
Length : 2
str(dict) Produces a
printable string
representation of a
dictionary.
dict = {'Name': 'Zara',
'Age': 7};
print "Equivalent
String : %s" % str
(dict)
Equivalent String : {'Age': 7,
'Name': 'Zara'}
…..
Python Dictionary (5)
Some Built-in Dictionary Methods
60
Method Description Example
dict.clear() Removes all
elements of
dictionary dict.
dict = {'Name': 'Zara',
'Age': 7};print "Start
Len : %d" % len(dict)
dict.clear()
print "End Len : %d" %
len(dict)
Start Len : 2
End Len : 0
dict.copy() Returns a shallow
copy of
dictionary dict.
dict1 = {'Name':
'Zara', 'Age': 7};
dict2 = dict1.copy()
print "New Dictinary :
%s" % str(dict2)
New Dictinary : {'Age': 7, 'Name':
'Zara'}
…..
SomeExamples
PYTHON DATE & TIME
Python Date & Time (1)
import time; # This is required to include time module.
ticks = time.time() # returns the current system time in ticks
# since 12:00am, January 1, 1970
print "Number of ticks since 12:00am, January 1, 1970:", ticks
Output
Number of ticks since 12:00am, January 1, 1970: 1498320786.91
62
Python Date & Time (2)
import calendar
cal = calendar.month(2017, 6)
print "Here is the calendar:"
print cal
Output
Here is the calendar:
June 2017
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
63
WhatisaFunction?
Example
PassbyReference VSPass byValue
TypesofFunctionArguments
ThereturnStatement
GlobalVariableVSLocalVariable
PYTHON FUNCTION
What is a Function?
A function is a block of organized, reusable code that is used to
perform a single, related action.
Syntax
def function_name( parameters ):
#function_body
65
Example
#python function
def test(str):
print (str)
test("Hello World!!!")
Output
Hello World!!!
66
Pass by Reference VS Pass by
Value
Pass by Reference Pass by Value
# 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
Output
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
# Function definition is here
def changeme( mylist ):
# This changes a passed list into
this function"
mylist = [1,2,3,4]; # This would
# assign new reference in mylist
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
Output
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
67
Types of Function Arguments
Function Argument Description Example
Required Arguments The arguments passed to
a function in correct
positional order. The
number of arguments in
the function call should
match exactly with the
function definition.
def test(str):
print (str)
test()
Traceback (most recent call last):
File "python_func.py", line 4, in <module>
test()
TypeError: test() takes exactly 1 argument
(0 given)
Keyword Arguments When use keyword
arguments in a function
call, the caller identifies
the arguments by the
parameter name. Thus,
allowing the arguments
to place in any order.
def printinfo( name, age ):
print "Name: ", name
print "Age ", age
printinfo( age=50,
name="miki" )
Name: miki
Age 50
68
Types of Function Arguments
(2)
Function Argument Description Example
Default Arguments An argument that
assumes a default value
if a value is not provided
in the function call for
that argument.
def printinfo( name, age = 35
):
print "Name: ", name
print "Age ", age
printinfo( age=50,
name="miki" )
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
69
Types of Function Arguments
(3)
Function Argument Description Example
Variable-length
Arguments
We may need to process
a function for more
arguments than
specified while defining
the function. These
arguments are called
variable-length
arguments and are not
named in the function
definition
def printinfo( arg1,
*vartuple ):
print "Output is: "
print arg1
for var in vartuple:
print var
printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50
NOTE:
The asterisk (*) placed before the variable
vartuple holds the values of all non-
keyword variable arguments.
70
The return Statement
def add(x,y):
sum=x+y
return sum
total=add(10,20)
print total
Output
30
71
Global Variable VS Local
Variable
72
total = 0; # This is global variable
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them
total = arg1 + arg2; # Here total is local variable
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
Output
Inside the function local total : 30
Outside the function global total : 0
PYTHON RECURSION
What is Recursion?
• When function is called within the same function, it is known
as recursion.
• The function which calls the same function, is known as
recursive function.
74
Example
75
WhatisaModule?
importStatement
from…importStatement
NamespacesandScoping
SomeFunctions
PythonPackages
PYTHON MODULES
What is a Module?
• A module is a file consisting of Python code.
• A module can define functions, classes and variables. It can
also include runnable code.
• A module allows you to logically organize your Python code.
• A module is a Python object with arbitrarily named attributes
that you can bind and reference.
77
Example
tmodule.py
def print_func( par ):
print "Hello : ", par
import Statement
# Import module tmodule
import tmodule
# Now you can call defined function that
# module as follows
tmodule.print_func("Zara")
Output
Hello : Zara
78
from…import Statement
Python's from statement allows you to import specific attributes
from a module into the current namespace.
79
Syntax Example
from modname import
name1[, name2[, ...
nameN]]
tmodule.py
def print_func( par ):
print "Hello : ", par
def print_func_2(str) :
print "Good Morning
",str
from_import_module.py
from tmodule import print_func_2
print_func_2("Zara")
Output
Good Morning Zara
Namespaces and Scoping
• Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).
• A Python statement can access variables in a local namespace and in the
global namespace. If a local and a global variable have the same name,
the local variable shadows the global variable.
• Each function has its own local namespace.
• Python assumes that any variable assigned a value in a function is local.
• Therefore, in order to assign a value to a global variable within a
function, you must first use the global statement.
• The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
80
Example
Money = 2000
def AddMoney():
# Uncomment the following line
# to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
Money = 2000
def AddMoney():
# Uncomment the following line
# to fix the code:
global Money
Money = Money + 1
print Money
AddMoney()
print Money
Output
2000
Traceback (most recent call last):
File "namespace_scoping.py", line 8, in <module>
AddMoney()
File "namespace_scoping.py", line 5, in AddMoney
Money = Money + 1
UnboundLocalError: local variable 'Money' referenced
before assignment
Output
2000
2001
81
Some Functions
Function Description Example
dir( ) Returns a sorted list of
strings containing the
names defined by a
module.
import tmodule
print dir(tmodule)
Output
['__builtins__', '__doc__', '__file__',
'__name__', '__package__', 'print_func',
'print_func_2']
locals() Returns all the names
that can be accessed
locally from the function,
in which its called.
total = 0;
def sum( arg1, arg2 ):
total = arg1 + arg2;
print "locals():
",locals()
print "globals():
",globals()
sum( 10, 20 );
Output
locals(): {'arg1': 10, 'arg2': 20, 'total': 30}
globals(): {'__builtins__': <module
'__builtin__' (built-in)>, '__file__': 'loc
al_global.py', '__package__': None, 'sum':
<function sum at 0x017638F0>, '__name
__': '__main__', 'total': 0, '__doc__': None}
globals() Returns all the names
that can be accessed
globally from the
function, in which its
called.
…..
82
Python Packages
A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules
and subpackages and sub-subpackages, and so on.
G:.
└──phone
__init__.py (required to make Python treat phone as a package)
g3.py
isdn.py
pots.py
83
Example
pots.py
def pots_func():
print "I'm Pots Phone"
isdn.py
def pots_func():
print "I'm ISDN Phone"
g3.py
def pots_func():
print "I'm G3 Phone" 84
Example (contd…)
__init__.py
from pots import pots_func
from isdn import isdn_func
from g3 import g3_func
package.py
import sys
sys.path.append('G:2. DOCUMENTSPythonPrograms')
import phone
phone.pots_func()
phone.isdn_func()
phone.g3_func() 85
Output
I'm Pots Phone
I'm ISDN Phone
I'm G3 Phone
86
Introduction
Example
SomeMoreFileOperationFunctions
PYTHON FILE MANAGEMENT
Introduction
• Until now, we have been reading and writing to the standard
input and output. This works fine as long as the data is small.
• However, many real life problems involve large volumes of
data & in such situations the standard I/O operations poses
two major problems:
- It becomes cumbersome & time consuming to handle large
volumes of data through terminals.
- The entire data is lost either the program is terminated or the
computer is turned off.
• Thus, to have a more flexible approach where data can be
stored on the disks & read whenever necessary without
destroying, the concept of file is employed. 88
Introduction (2)
• Like most other languages, Python supports a number of
functions that have the ability to perform basic file operations:
- Naming a file
- Opening a file (fileobject = open(file_name [, access_mode][, buffering]))
- Reading a file (string = fileobject.read([count]))
- Writing to a file (fileobject.write(string))
- Closing a file (fileobject.close())
access_mode = r, rb, r+, rb+, w, wb, w+, wb+, a, ab,a+, ab+
buffering = <1, 0, >1
count = number of bytes to be read from the opened file
string = content to be written into the opened file 89
Example
# Open a file in write mode
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.nYeah its
great!!n");
# Close opened file
fo.close()
# Open the file in read mode
fo = open("foo.txt", "rb")
string = fo.read()
print string
# Close opened file
fo.close() 90
Output
Python is a great language.
Yeah its great!!
91
Some More File Operation
Functions
92
Function Name Description
tell() Gives the current position within the
file
seek(offset[, from]) Changes the current file position. The
offset argument indicates the number
of bytes to be moved. The from
argument specifies the reference
position from where the bytes are to
be moved.
…..
Example (tell())
93
WhatisException?
HandlinganException
try.....except.....else
try.....finally
ArgumentofanException
User-Defined Exceptions
PYTHON EXCEPTION
HANDLING
What is Exception?
• An exception is an event, which occurs during the execution of
a program that disrupts the normal flow of the program's
instructions.
• When a Python script encounters a situation that it cannot
cope with, it raises an exception.
• An exception is a Python object that represents an error.
• When a Python script raises an exception, it must either
handle the exception immediately otherwise it terminates and
quits.
95
Handling an Exception
• If you have some suspicious code that may raise an exception,
you can defend your program by placing the suspicious code in
a try: block.
• After the try: block, include an except: statement, followed by
a block of code which handles the problem as elegantly as
possible.
• After the except clause(s), you can include an else-clause. The
code in the else-block executes if the code in the try: block
does not raise an exception.
96
try.....except.....else (Syntax)
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
except ExceptionN:
If there is ExceptionN, then execute this block.
else:
If there is no exception then execute this block.
97
try.....except.....else (Example)
Example I Example II
try:
fh = open("testfile", "w")
fh.write("This is my test file
for exception handling!!")
except IOError:
print "Error: can't find file
or read data"
else:
print "Written content in the
file successfully"
fh.close()
try:
fh = open("testfile_2", "r")
string = fh.read()
except IOError:
print "Error: can't find file
or read data"
else:
print string
fh.close()
Output
Written content in the file successfully
Output
Error: can't find file or read data
98
try.....finally
• You can use a finally: block along with a try: block.
• The finally block is a place to put any code that must execute, whether the try-block raised
an exception or not.
Syntax
try:
You do your operations here;
......................
[except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
except ExceptionN:
If there is ExceptionN, then execute this block.
else:
If there is no exception then execute this block.]
finally:
This would always be executed.
......................
99
Example
Example I Example II
try:
fh = open("testfile", "w")
fh.write("This is my test file
for exception handling!!")
except IOError:
print "Error: can't find file
or read data"
else:
print "Written content in the
file successfully"
finally:
print "Closing the file"
fh.close()
try:
fh = open("testfile_2", "r")
string = fh.read()
except IOError:
print "Error: can't find file
or read data"
else:
print string
finally:
print "Closing the file"
fh.close()
Output
Written content in the file successfully
Closing the file
Output
Error: can't find file or read data
Closing the file
100
Argument of an Exception
• An exception can have an argument, which is a value that
gives additional information about the problem.
• This argument receives the value of the exception mostly
containing the cause of the exception.
Syntax
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
101
Example
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain
numbersn", Argument
# Call above function here.
temp_convert("xyz");
Output
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
102
User-Defined Exceptions
Python also allows you to create your own exceptions by
deriving classes from the standard built-in exceptions.
103
Example
# user-defined exception
class LevelError(ValueError):
def __init__(self, arg):
self.arg = arg
try:
level=input("Enter level: ")
if(level<1):
# Raise an exception with argument
raise LevelError("Level less than 1")
except LevelError, le:
# Catch exception
print 'Error: ', le.arg
else:
print level
Output
Enter level: 0
Error: Level less than 1
References
• Courtesy of YouTube – ProgrammingKnowledge. URL:
https://www.youtube.com/user/ProgrammingKnowledge,
Python Tutorial for Beginners (For Absolute Beginners)
• Courtesy of TutorialsPoint – Python Tutorial. URL:
http://www.tutorialspoint.com/python
• Courtesy of W3Resource – Python Tutorial. URL:
http://www.w3resource.com/python/python-tutorial.php
104
1 von 104

Recomendados

Python basic von
Python basicPython basic
Python basicSaifuddin Kaijar
12.3K views25 Folien
Python ppt von
Python pptPython ppt
Python pptMohita Pandey
3.8K views53 Folien
Introduction to Python von
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
36.8K views62 Folien
Presentation on python von
Presentation on pythonPresentation on python
Presentation on pythonwilliam john
2K views16 Folien
Overview of python 2019 von
Overview of python 2019Overview of python 2019
Overview of python 2019Samir Mohanty
709 views199 Folien
Introduction to the basics of Python programming (part 1) von
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
1.3K views36 Folien

Más contenido relacionado

Was ist angesagt?

Python von
PythonPython
PythonAashish Jain
1.5K views109 Folien
Beginning Python Programming von
Beginning Python ProgrammingBeginning Python Programming
Beginning Python ProgrammingSt. Petersburg College
2.1K views34 Folien
Introduction to python von
Introduction to pythonIntroduction to python
Introduction to pythonAyshwarya Baburam
1.1K views62 Folien
Python | What is Python | History of Python | Python Tutorial von
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
3.4K views32 Folien
Fundamentals of Python Programming von
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
9.8K views135 Folien

Was ist angesagt?(20)

Python | What is Python | History of Python | Python Tutorial von QA TrainingHub
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
QA TrainingHub3.4K views
Fundamentals of Python Programming von Kamal Acharya
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
Kamal Acharya9.8K views
Python Programming ppt von ismailmrribi
Python Programming pptPython Programming ppt
Python Programming ppt
ismailmrribi3.9K views
Introduction to-python von Aakashdata
Introduction to-pythonIntroduction to-python
Introduction to-python
Aakashdata6.1K views
Intro to Python Programming Language von Dipankar Achinta
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta4.4K views
Python - An Introduction von Swarit Wadhe
Python - An IntroductionPython - An Introduction
Python - An Introduction
Swarit Wadhe4.5K views
Python in 30 minutes! von Fariz Darari
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
Fariz Darari16.2K views

Similar a Python (basic)

Python von
PythonPython
PythonGagandeep Nanda
707 views118 Folien
Pythonppt28 11-18 von
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18Saraswathi Murugan
258 views65 Folien
FUNDAMENTALS OF PYTHON LANGUAGE von
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
594 views65 Folien
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx von
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptxsangeeta borde
16 views28 Folien
Python 3.pptx von
Python 3.pptxPython 3.pptx
Python 3.pptxHarishParthasarathy4
24 views47 Folien
Python programming workshop session 1 von
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
178 views37 Folien

Similar a Python (basic)(20)

2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx von sangeeta borde
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde16 views
Python programming workshop session 1 von Abdul Haseeb
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
Abdul Haseeb178 views
Hands on Session on Python von Sumit Raj
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
Sumit Raj2.7K views
01-Python-Basics.ppt von VicVic56
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
VicVic5613 views
An Overview Of Python With Functional Programming von Adam Getchell
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell656 views
Python Basics by Akanksha Bali von Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali275 views
An Intro to Python in 30 minutes von Sumit Raj
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj1.4K views
Introduction to Python Programming | InsideAIML von VijaySharma802
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
VijaySharma80220 views
Python introduction towards data science von deepak teja
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja131 views
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf von KosmikTech1
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech133 views

Más de Sabyasachi Moitra

Java (core) von
Java (core)Java (core)
Java (core)Sabyasachi Moitra
12 views136 Folien
Introduction to Database von
Introduction to DatabaseIntroduction to Database
Introduction to DatabaseSabyasachi Moitra
2.2K views18 Folien
Dependency Preserving Decomposition von
Dependency Preserving DecompositionDependency Preserving Decomposition
Dependency Preserving DecompositionSabyasachi Moitra
340 views4 Folien
Lossless Join Decomposition von
Lossless Join DecompositionLossless Join Decomposition
Lossless Join DecompositionSabyasachi Moitra
620 views5 Folien
Functional Dependency von
Functional DependencyFunctional Dependency
Functional DependencySabyasachi Moitra
286 views15 Folien
Normalization von
NormalizationNormalization
NormalizationSabyasachi Moitra
183 views21 Folien

Más de Sabyasachi Moitra(20)

Último

SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx von
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptxSURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptxNiranjan Chavan
43 views54 Folien
Meet the Bible von
Meet the BibleMeet the Bible
Meet the BibleSteve Thomason
76 views80 Folien
EILO EXCURSION PROGRAMME 2023 von
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023info33492
181 views40 Folien
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... von
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...Nguyen Thanh Tu Collection
71 views91 Folien
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37 von
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37MysoreMuleSoftMeetup
44 views17 Folien
Retail Store Scavenger Hunt.pptx von
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptxjmurphy154
52 views10 Folien

Último(20)

SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx von Niranjan Chavan
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptxSURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx
SURGICAL MANAGEMENT OF CERVICAL CANCER DR. NN CHAVAN 28102023.pptx
Niranjan Chavan43 views
EILO EXCURSION PROGRAMME 2023 von info33492
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023
info33492181 views
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... von Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37 von MysoreMuleSoftMeetup
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Retail Store Scavenger Hunt.pptx von jmurphy154
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptx
jmurphy15452 views
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice von Taste
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a ChoiceCreative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice
Taste41 views
Nelson_RecordStore.pdf von BrynNelson5
Nelson_RecordStore.pdfNelson_RecordStore.pdf
Nelson_RecordStore.pdf
BrynNelson546 views
CUNY IT Picciano.pptx von apicciano
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptx
apicciano60 views
Guess Papers ADC 1, Karachi University von Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz83 views
When Sex Gets Complicated: Porn, Affairs, & Cybersex von Marlene Maheu
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & Cybersex
Marlene Maheu108 views
Monthly Information Session for MV Asterix (November) von Esquimalt MFRC
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)
Esquimalt MFRC98 views
Parts of Speech (1).pptx von mhkpreet001
Parts of Speech (1).pptxParts of Speech (1).pptx
Parts of Speech (1).pptx
mhkpreet00143 views

Python (basic)

  • 3. Introduction Developed by Guido van Rossum in the early 1990s. Features: • High-level powerful programming language • Interpreted language • Object-oriented • Portable • Easy to learn & use • Open source • Derived from many other programming languages 3
  • 4. Introduction (2) Uses: • Internet Scripting • Image Processing • Database Programming • Artificial Intelligence ….. 4
  • 5. Compiling and Interpreting • Many languages compile (translate) the program into a machine understandable form. • Python is directly interpreted into machine instructions. 5 compile execute ----------> ----------> Source code Intermediate code Output interpret ----------> Source code Output
  • 6. Compiling and Interpreting (2) Compiler Interpreter Scans the entire program and translates it as a whole into machine code. Translates program one statement at a time. It takes large amount of time to analyze the source code but the overall execution time is comparatively faster. It takes less amount of time to analyze the source code but the overall execution time is slower. Generates intermediate object code which further requires linking, hence requires more memory. No intermediate object code is generated, hence are memory efficient. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy. Programming language like C, C++ use compilers. Programming language like Python, Ruby use interpreters. 6
  • 10. Interactive Mode Programming VS Script Mode Programming Interactive Mode Programming Script Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the Python prompt. Type a python statement at the prompt and press Enter. Invoking the interpreter with a script parameter, & begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active (assuming that user have Python interpreter set in PATH variable). C:Usersmoitra>python Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit ( Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello World") Hello World G:2. DOCUMENTSPythonPrograms>pytho n test.py Hello World 10
  • 11. Identifiers • A Python identifier is a name used to identify a variable, function, class, module or other object. • An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). • Python does not allow punctuation characters such as @, $, and % within identifiers. • Python is a case sensitive programming language. Manpower and manpower are two different identifiers in Python. 11
  • 12. Reserved Words and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield and exec not 12
  • 13. Lines and Indentation • Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation. • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. 13 Correct Erroneous if True: print "True" else: print "False" if True: print "Answer" print "True" else: print "Answer" print "False"
  • 14. Basic Syntax (5) Example Multi-Line Statements total = item_one + item_two + item_three Comments in Python print "Hello World" # comment Multiple Statements on a Single Line x = 'foo'; print(x + 'n') ….. 14
  • 16. Standard Data Types Standard Data Type Example Numbers counter = 100 miles = 1000.0 String name = "John" List tinylist = [123, 'john'] Tuple tinytuple = (123, 'john') Dictionary tinydict = {'name': 'john','code':6734, 'dept': 'sales'} 16
  • 17. Other Operations Operation Example Multiple Assignment a = b = c = 1 a,b,c = 1,2,"john" Delete del var1[,var2[,var3[....,varN]]]] 17 Some Type Conversions Function Description int(x) Converts x to an integer number str(x) Converts x to a string representation list(s) Converts s to a list tuple(s) Converts s to a tuple dict(d) Creates a dictionary d …..
  • 19. Types of Operator Type Operators Arithmetic Operators +, -, *, /, %, ** (exponent), // (floor division) Relational Operators ==, !=, >, <, >=, <= Assignment Operators =, +=, -=, *=, /=, %=, **=, //= Logical Operators and, or, not Bitwise Operators &, |, ~, ^, <<, >> Membership Operators in, not in Identity Operators is, not is 19
  • 20. Addition of two nos. add.py #addition of two numbers a=raw_input("Enter 1st no.: ") b=raw_input("Enter 2nd no.: ") c=int(a)+int(b) print('The sum of {0} and {1} is {2}'.format(a, b, c)) Output G:2. DOCUMENTSPythonPrograms>python add.py Enter 1st no.: 1 Enter 2nd no.: 2 The sum of 1 and 2 is 3 20
  • 22. Simple if statement simple_if.py #even no. check a=input("Enter a no: ") if(a%2==0): print('{0} is even'.format(a)) Output 22 if even if not even G:2. DOCUMENTSPythonPrograms >python simple_if.py Enter a no: 10 10 is even G:2. DOCUMENTSPythonPrograms >python simple_if.py Enter a no: 11
  • 23. if…else statement if_else.py #even-odd no. check a=input("Enter a no: ") if(a%2==0): print('{0} is even'.format(a)) else: print('{0} is odd'.format(a)) Output 23 if even if not even G:2. DOCUMENTSPythonPrograms >python if_else.py Enter a no: 10 10 is even G:2. DOCUMENTSPythonPrograms >python if_else.py Enter a no: 11 11 is odd
  • 24. nested if statement (nested_if.py) 24
  • 30. for Loop for_loop.py for i in range(1,6): print(i) Output G:2. DOCUMENTSPythonPrograms>python for_loop.py 1 2 3 4 5 30
  • 34. Python Numbers (1) • Python supports four different numerical types: • Python also includes some predefined numeric functions: 34 int long float complex 10 51924361L 15.20 -.6545+26J Type Function Description Example Mathematical pow(x, y) The value of x**y import math print "math.pow(2, 4) : ", math.pow(2, 4) math.pow(2, 4) : 16.0 abs(x) The absolute value of x print "abs(-45) : ", abs(-45) abs(-45) : 45 …..
  • 35. Python Numbers (2) Type Function Description Example Random Number choice(seq) A random item from a list, tuple, or string import random print "choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9]) choice([1, 2, 3, 5, 9]) : 2 shuffle(lst) Randomizes the items of a list in place. Returns None import random list = [20, 16, 10, 5]; random.shuffle(list) print "Reshuffled list : ", list Reshuffled list : [16, 5, 10, 20] ….. 35
  • 36. Python Numbers (3) Type Function Description Example Trigonometric sin (x) Return the sine of x radians import math print "sin(3) : ", math.sin(3) sin(3) : 0.14112000806 cox (x) Return the cosine of x radians import math print “cos(3) : ", math.cos(3) sin(3) : 0.14112000806 ….. 36
  • 37. Python Numbers (4) • Python also supports two mathematical constants: pi e 37
  • 39. Python Strings (1) str = 'Hello World!' 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 print "Updated String :- ", str[:6] + 'Python' Output Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST Updated String :- Hello Python 39
  • 40. Python Strings (2) 40 Python includes some built-in methods to manipulate strings: String Method Description Example capitalize() Capitalizes first letter of string str = "this is string example....wo w!!!"; print "str.capitali ze() : ", str.capitaliz e() str.capitalize() : This is string example....wow!!! len() Returns the length of the string str = "this is string example....wo w!!!"; print "Length of the string: ", len(str) Length of the string: 32 …..
  • 42. Python Lists (1) 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] # Prints last 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 list[0] = 'efgh'; # updating list print list del list[2]; # deleting list element print list 42
  • 43. Python Lists (2) Output ['abcd', 786, 2.23, 'john', 70.2] abcd 70.2 [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] ['efgh', 786, 2.23, 'john', 70.2] ['efgh', 786, 'john', 70.2] 43
  • 44. Python Lists (3) Other Basic List Operations 44 Expression Result Description len([1, 2, 3]) 3 Length 3 in [1, 2, 3] True Membership for x in [1, 2, 3]: print x, 1 2 3 Iteration
  • 45. Functions VS Methods Function Method A function is a piece of code that is called by name. A method is a piece of code that is called by name that is associated with an object. It can pass data to operate on (i.e., the parameters) and can optionally return data (the return value). It is able to operate on data that is contained within the class. All data that is passed to a function is explicitly passed. It is implicitly passed for the object for which it was called. def sum(num1, num2): return num1 + num2 class Dog: def my_method(self): print "I am a Dog" dog = Dog() dog.my_method() # Prints "I am a Dog" 45
  • 46. Python Lists (4) Some Built-in List Functions 46 Function Description Example max(list) Returns item from the list with max value. list = [456, 700, 200] print "Max value element : ", max(list) Max value element : 700 min(list) Returns item from the list with min value. list = [456, 700, 200] print "Min value element : ", min(list) Min value element : 200 …..
  • 47. Python Lists (5) Some Built-in List Methods 47 Method Description Example list.append(obj) Appends a passed obj into the existing list. aList = [123, 'xyz', 'zara', 'abc']; aList.append( 2009 ); print "Updated List : ", aList Updated List : [123, 'xyz', 'zara', 'abc', 2009] list.count(obj) Returns count of how many times obj occurs in list. aList = [123, 'xyz', 'zara', 'abc', 123]; print "Count for 123 : ", aList.count(123) print "Count for zara : ", aList.count('zara') Count for 123 : 2 Count for zara : 1 …..
  • 49. Python Tuples (1) tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints complete tuple print tuple[0] # Prints first element of the tuple print tuple[-1] # Prints last element of the tuple print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints tuple two times print tuple + tinytuple # Prints concatenated tuples 49
  • 50. Python Tuples (2) Output ('abcd', 786, 2.23, 'john', 70.2) abcd 70.2 (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') 50
  • 51. Python Tuples (3) Other Basic Tuple Operations 51 Expression Result Description len((1, 2, 3)) 3 Length 3 in (1, 2, 3) True Membership for x in (1, 2, 3): print x, 1 2 3 Iteration
  • 52. Python Tuples (4) Some Built-in Tuple Functions 52 Function Description Example max(tuple) Returns item from the tuple with max value. tuple = (456, 700, 200) print "Max value element : ", max(tuple) Max value element : 700 min(tuple) Returns item from the tuple with min value. tuple = (456, 700, 200) print "Min value element : ", min(tuple) Min value element : 200 …..
  • 53. Lists VS Tuples Lists Tuples Lists are enclosed in brackets ( [ ] ). Tuples are enclosed in parentheses ( ( ) ). Lists' elements and size can be changed. Tuples' elements and size cannot be changed. Support item deletion. Example list = [123, 'john'] print list del list[1] print list [123, 'john'] [123] Doesn't support item deletion. Example tuple = (123, 'john') print tuple del tuple[1] print tuple (123, 'john') Traceback (most recent call last): File "main.py", line 6, in del tuple[1] TypeError: 'tuple' object doesn't support item deletion 53
  • 55. Python Dictionary (1) • Python's dictionaries are kind of hash table type. • They work like associative arrays or hashes found in PHP and Perl respectively. • It consists of key-value pairs. • A dictionary key can be almost any Python type, but are usually numbers or strings, & values can be any arbitrary Python object. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). 55
  • 56. Python Dictionary (2) 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 tinydict['name']="Peter" # update existing entry tinydict['org']="abcd" # Add new entry print tinydict del dict[2]; # remove entry with key 2 print "dict: ", dict dict.clear(); # remove all entries in dict print "dict: ", dict del dict ; # delete entire dictionary print "dict: ", dict 56
  • 57. Python Dictionary (3) Output This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john'] {'dept': 'sales', 'code': 6734, 'name': 'Peter', 'org': 'abcd'} dict: {'one': 'This is one'} dict: {} dict: 57
  • 58. Properties of Dictionary Keys • More than one entry per key not allowed, i.e., no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. • Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. 58
  • 59. Python Dictionary (4) Some Built-in Dictionary Functions 59 Function Description Example len(dict) Gives the total length of the dictionary. dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict) Length : 2 str(dict) Produces a printable string representation of a dictionary. dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict) Equivalent String : {'Age': 7, 'Name': 'Zara'} …..
  • 60. Python Dictionary (5) Some Built-in Dictionary Methods 60 Method Description Example dict.clear() Removes all elements of dictionary dict. dict = {'Name': 'Zara', 'Age': 7};print "Start Len : %d" % len(dict) dict.clear() print "End Len : %d" % len(dict) Start Len : 2 End Len : 0 dict.copy() Returns a shallow copy of dictionary dict. dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = dict1.copy() print "New Dictinary : %s" % str(dict2) New Dictinary : {'Age': 7, 'Name': 'Zara'} …..
  • 62. Python Date & Time (1) import time; # This is required to include time module. ticks = time.time() # returns the current system time in ticks # since 12:00am, January 1, 1970 print "Number of ticks since 12:00am, January 1, 1970:", ticks Output Number of ticks since 12:00am, January 1, 1970: 1498320786.91 62
  • 63. Python Date & Time (2) import calendar cal = calendar.month(2017, 6) print "Here is the calendar:" print cal Output Here is the calendar: June 2017 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 63
  • 65. What is a Function? A function is a block of organized, reusable code that is used to perform a single, related action. Syntax def function_name( parameters ): #function_body 65
  • 66. Example #python function def test(str): print (str) test("Hello World!!!") Output Hello World!!! 66
  • 67. Pass by Reference VS Pass by Value Pass by Reference Pass by Value # 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 Output Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] # Function definition is here def changeme( mylist ): # This changes a passed list into this function" mylist = [1,2,3,4]; # This would # assign new reference in mylist 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 Output Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] 67
  • 68. Types of Function Arguments Function Argument Description Example Required Arguments The arguments passed to a function in correct positional order. The number of arguments in the function call should match exactly with the function definition. def test(str): print (str) test() Traceback (most recent call last): File "python_func.py", line 4, in <module> test() TypeError: test() takes exactly 1 argument (0 given) Keyword Arguments When use keyword arguments in a function call, the caller identifies the arguments by the parameter name. Thus, allowing the arguments to place in any order. def printinfo( name, age ): print "Name: ", name print "Age ", age printinfo( age=50, name="miki" ) Name: miki Age 50 68
  • 69. Types of Function Arguments (2) Function Argument Description Example Default Arguments An argument that assumes a default value if a value is not provided in the function call for that argument. def printinfo( name, age = 35 ): print "Name: ", name print "Age ", age printinfo( age=50, name="miki" ) printinfo( name="miki" ) Name: miki Age 50 Name: miki Age 35 69
  • 70. Types of Function Arguments (3) Function Argument Description Example Variable-length Arguments We may need to process a function for more arguments than specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition def printinfo( arg1, *vartuple ): print "Output is: " print arg1 for var in vartuple: print var printinfo( 10 ) printinfo( 70, 60, 50 ) Output is: 10 Output is: 70 60 50 NOTE: The asterisk (*) placed before the variable vartuple holds the values of all non- keyword variable arguments. 70
  • 71. The return Statement def add(x,y): sum=x+y return sum total=add(10,20) print total Output 30 71
  • 72. Global Variable VS Local Variable 72 total = 0; # This is global variable # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them total = arg1 + arg2; # Here total is local variable print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total Output Inside the function local total : 30 Outside the function global total : 0
  • 74. What is Recursion? • When function is called within the same function, it is known as recursion. • The function which calls the same function, is known as recursive function. 74
  • 77. What is a Module? • A module is a file consisting of Python code. • A module can define functions, classes and variables. It can also include runnable code. • A module allows you to logically organize your Python code. • A module is a Python object with arbitrarily named attributes that you can bind and reference. 77 Example tmodule.py def print_func( par ): print "Hello : ", par
  • 78. import Statement # Import module tmodule import tmodule # Now you can call defined function that # module as follows tmodule.print_func("Zara") Output Hello : Zara 78
  • 79. from…import Statement Python's from statement allows you to import specific attributes from a module into the current namespace. 79 Syntax Example from modname import name1[, name2[, ... nameN]] tmodule.py def print_func( par ): print "Hello : ", par def print_func_2(str) : print "Good Morning ",str from_import_module.py from tmodule import print_func_2 print_func_2("Zara") Output Good Morning Zara
  • 80. Namespaces and Scoping • Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). • A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable. • Each function has its own local namespace. • Python assumes that any variable assigned a value in a function is local. • Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. • The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable. 80
  • 81. Example Money = 2000 def AddMoney(): # Uncomment the following line # to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money Money = 2000 def AddMoney(): # Uncomment the following line # to fix the code: global Money Money = Money + 1 print Money AddMoney() print Money Output 2000 Traceback (most recent call last): File "namespace_scoping.py", line 8, in <module> AddMoney() File "namespace_scoping.py", line 5, in AddMoney Money = Money + 1 UnboundLocalError: local variable 'Money' referenced before assignment Output 2000 2001 81
  • 82. Some Functions Function Description Example dir( ) Returns a sorted list of strings containing the names defined by a module. import tmodule print dir(tmodule) Output ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'print_func', 'print_func_2'] locals() Returns all the names that can be accessed locally from the function, in which its called. total = 0; def sum( arg1, arg2 ): total = arg1 + arg2; print "locals(): ",locals() print "globals(): ",globals() sum( 10, 20 ); Output locals(): {'arg1': 10, 'arg2': 20, 'total': 30} globals(): {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'loc al_global.py', '__package__': None, 'sum': <function sum at 0x017638F0>, '__name __': '__main__', 'total': 0, '__doc__': None} globals() Returns all the names that can be accessed globally from the function, in which its called. ….. 82
  • 83. Python Packages A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. G:. └──phone __init__.py (required to make Python treat phone as a package) g3.py isdn.py pots.py 83
  • 84. Example pots.py def pots_func(): print "I'm Pots Phone" isdn.py def pots_func(): print "I'm ISDN Phone" g3.py def pots_func(): print "I'm G3 Phone" 84
  • 85. Example (contd…) __init__.py from pots import pots_func from isdn import isdn_func from g3 import g3_func package.py import sys sys.path.append('G:2. DOCUMENTSPythonPrograms') import phone phone.pots_func() phone.isdn_func() phone.g3_func() 85
  • 86. Output I'm Pots Phone I'm ISDN Phone I'm G3 Phone 86
  • 88. Introduction • Until now, we have been reading and writing to the standard input and output. This works fine as long as the data is small. • However, many real life problems involve large volumes of data & in such situations the standard I/O operations poses two major problems: - It becomes cumbersome & time consuming to handle large volumes of data through terminals. - The entire data is lost either the program is terminated or the computer is turned off. • Thus, to have a more flexible approach where data can be stored on the disks & read whenever necessary without destroying, the concept of file is employed. 88
  • 89. Introduction (2) • Like most other languages, Python supports a number of functions that have the ability to perform basic file operations: - Naming a file - Opening a file (fileobject = open(file_name [, access_mode][, buffering])) - Reading a file (string = fileobject.read([count])) - Writing to a file (fileobject.write(string)) - Closing a file (fileobject.close()) access_mode = r, rb, r+, rb+, w, wb, w+, wb+, a, ab,a+, ab+ buffering = <1, 0, >1 count = number of bytes to be read from the opened file string = content to be written into the opened file 89
  • 90. Example # Open a file in write mode fo = open("foo.txt", "wb") fo.write( "Python is a great language.nYeah its great!!n"); # Close opened file fo.close() # Open the file in read mode fo = open("foo.txt", "rb") string = fo.read() print string # Close opened file fo.close() 90
  • 91. Output Python is a great language. Yeah its great!! 91
  • 92. Some More File Operation Functions 92 Function Name Description tell() Gives the current position within the file seek(offset[, from]) Changes the current file position. The offset argument indicates the number of bytes to be moved. The from argument specifies the reference position from where the bytes are to be moved. …..
  • 95. What is Exception? • An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. • When a Python script encounters a situation that it cannot cope with, it raises an exception. • An exception is a Python object that represents an error. • When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits. 95
  • 96. Handling an Exception • If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. • After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. • After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. 96
  • 97. try.....except.....else (Syntax) try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... except ExceptionN: If there is ExceptionN, then execute this block. else: If there is no exception then execute this block. 97
  • 98. try.....except.....else (Example) Example I Example II try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" fh.close() try: fh = open("testfile_2", "r") string = fh.read() except IOError: print "Error: can't find file or read data" else: print string fh.close() Output Written content in the file successfully Output Error: can't find file or read data 98
  • 99. try.....finally • You can use a finally: block along with a try: block. • The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. Syntax try: You do your operations here; ...................... [except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... except ExceptionN: If there is ExceptionN, then execute this block. else: If there is no exception then execute this block.] finally: This would always be executed. ...................... 99
  • 100. Example Example I Example II try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can't find file or read data" else: print "Written content in the file successfully" finally: print "Closing the file" fh.close() try: fh = open("testfile_2", "r") string = fh.read() except IOError: print "Error: can't find file or read data" else: print string finally: print "Closing the file" fh.close() Output Written content in the file successfully Closing the file Output Error: can't find file or read data Closing the file 100
  • 101. Argument of an Exception • An exception can have an argument, which is a value that gives additional information about the problem. • This argument receives the value of the exception mostly containing the cause of the exception. Syntax try: You do your operations here; ...................... except ExceptionType, Argument: You can print value of Argument here... 101
  • 102. Example # Define a function here. def temp_convert(var): try: return int(var) except ValueError, Argument: print "The argument does not contain numbersn", Argument # Call above function here. temp_convert("xyz"); Output The argument does not contain numbers invalid literal for int() with base 10: 'xyz' 102
  • 103. User-Defined Exceptions Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. 103 Example # user-defined exception class LevelError(ValueError): def __init__(self, arg): self.arg = arg try: level=input("Enter level: ") if(level<1): # Raise an exception with argument raise LevelError("Level less than 1") except LevelError, le: # Catch exception print 'Error: ', le.arg else: print level Output Enter level: 0 Error: Level less than 1
  • 104. References • Courtesy of YouTube – ProgrammingKnowledge. URL: https://www.youtube.com/user/ProgrammingKnowledge, Python Tutorial for Beginners (For Absolute Beginners) • Courtesy of TutorialsPoint – Python Tutorial. URL: http://www.tutorialspoint.com/python • Courtesy of W3Resource – Python Tutorial. URL: http://www.w3resource.com/python/python-tutorial.php 104