Basic Python
Basic Python
Basic Python
(Basic)
Sabyasachi Moitra
moitrasabyasachi@hotmail.com
OVERVIEW
Introduction
Compiling and Interpreting
First Python Program
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.
compile execute
----------> ---------->
interpret
---------->
7
Output
8
BASIC SYNTAX
Interactive Mode Programming VS Script Mode Programming
Identifiers
Reserved Words
Lines and Indentation
Some more Basic Syntax
Interactive Mode Programming
VS Script Mode Programming
Interactive Mode Programming Script Mode Programming
Invoking the interpreter without Invoking the interpreter with a script
passing a script file as a parameter parameter, & begins execution of the
brings up the Python prompt. Type a script and continues until the script is
python statement at the prompt and finished. When the script is finished,
press Enter. the interpreter is no longer active
(assuming that user have Python
interpreter set in PATH variable).
C:\Users\moitra>python G:\2.
Python 2.7.13 (v2.7.13:a06454b1afa1, DOCUMENTS\PythonPrograms>pytho
Dec 17 2016, 20:42:59) [MSC v.1500 n test.py
32 bit ( Hello World
Intel)] on win32
Type "help", "copyright", "credits" or
"license" for more information. 10
>>> print("Hello World")
Hello World
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
12
and exec not
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.
Correct Erroneous
if True: if True:
print "True" print "Answer"
else: print "True"
print "False" else:
print "Answer"
print "False" 13
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
VARIABLE TYPES
Standard Data Types
Other Operations
Some Type Conversions
Standard Data Types
Standard Data Type Example
counter = 100
Numbers
miles = 1000.0
String name = "John"
List tinylist = [123, 'john']
Tuple tinytuple = (123, 'john')
tinydict = {'name': 'john','code':6734,
Dictionary
'dept': 'sales'}
16
Other Operations
Operation Example
a=b=c=1
Multiple Assignment
a,b,c = 1,2,"john"
Delete del var1[,var2[,var3[....,varN]]]]
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. DOCUMENTS\PythonPrograms>python add.py
Enter 1st no.: 1
Enter 2nd no.: 2
The sum of 1 and 2 is 3
20
DECISION MAKING
Simple if statement
if…else statement
nested if statement
elif Statement
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
24
Output
25
elif Statement (else_if_ladder.py)
26
Output
27
LOOPING
while Loop
for Loop
nested Loop
while Loop
while_loop.py
i=1
while(i<=5):
print(i)
i=i+1
Output
G:\2. DOCUMENTS\PythonPrograms>python while_loop.py
1
2
3
4 29
5
for Loop
for_loop.py
for i in range(1,6):
print(i)
Output
G:\2. DOCUMENTS\PythonPrograms>python for_loop.py
1
2
3
4
5
30
nested Loops (prime_factor.py)
31
Output
32
PYTHON NUMBERS
Numerical Types
Numeric Functions
Mathematical Constants
Python Numbers (1)
• Python supports four different numerical types:
…..
Python Numbers (2)
Type Function Description Example
import random
choice(seq) A random item print "choice([1, 2,
from a list, tuple, 3, 5, 9]) : ",
random.choice([1, 2,
or string 3, 5, 9])
choice([1, 2, 3, 5, 9]) : 2
import random
shuffle(lst) Randomizes the list = [20, 16, 10,
Random Number
items of a list in 5];
random.shuffle(list)
place. Returns print "Reshuffled
list : ", list
None
Reshuffled list : [16, 5, 10, 20]
…..
35
Python Numbers (3)
Type Function Description Example
import math
sin (x) Return the sine of print "sin(3) : ",
x radians math.sin(3)
sin(3) : 0.14112000806
import math
Trigonometric cox (x) Return the cosine print “cos(3) : ",
of x radians math.cos(3)
sin(3) : 0.14112000806
…..
36
Python Numbers (4)
• Python also supports two mathematical constants:
pi
e
37
PYTHON STRINGS
Example
Built-in String Methods
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 39
Updated String :- Hello Python
Python Strings (2)
Python includes some built-in methods to manipulate strings:
…..
40
PYTHON LISTS
Example
Basic List Operations
Functions VS Methods
Built-in List Functions
Built-in List Methods
Python Lists (1)
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
44
Functions VS Methods
Function Method
A function is a piece of code that is A method is a piece of code that is
called by name. called by name that is associated with
an object.
It can pass data to operate on (i.e., the It is able to operate on data that is
parameters) and can optionally return contained within the class.
data (the return value).
All data that is passed to a function is It is implicitly passed for the object for
explicitly passed. which it was called.
def sum(num1, num2): class Dog:
return num1 + num2 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
Function Description Example
list = [456, 700, 200]
max(list) Returns item from print "Max value
the list with max element : ", max(list)
…..
46
Python Lists (5)
Some Built-in List Methods
Method Description Example
aList = [123, 'xyz',
list.append(obj) Appends a 'zara', 'abc'];
passed obj into the aList.append( 2009 );
print "Updated List :
existing list. ", aList
Updated List : [123, 'xyz', 'zara',
'abc', 2009]
…..
47
PYTHON TUPLES
Example
Basic Tuple Operations
Built-in Tuple Functions
Lists VS Tuples
Python Tuples (1)
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
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
Expression Result Description
len((1, 2, 3)) 3 Length
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): 123 Iteration
print x,
51
Python Tuples (4)
Some Built-in Tuple Functions
Function Description Example
tuple = (456, 700, 200)
max(tuple) Returns item from print "Max value
the tuple with max element : ", max(tuple)
…..
52
Lists VS Tuples
Lists Tuples
Lists are enclosed in brackets ( [ ] ). Tuples are enclosed in parentheses ( ( )
).
Lists' elements and size can be Tuples' elements and size cannot be
changed. changed.
Support item deletion. Doesn't support item deletion.
Example Example
list = [123, 'john'] tuple = (123, 'john')
print list print tuple
del list[1] del tuple[1]
print list print tuple
53
PYTHON DICTIONARY
Introduction
Example
Properties of Dictionary Keys
Built-in Dictionary Functions
Built-in Dictionary Methods
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'}
58
Python Dictionary (4)
Some Built-in Dictionary Functions
Function Description Example
dict = {'Name': 'Zara',
len(dict) Gives the total 'Age': 7};
length of the print "Length : %d" %
len (dict)
dictionary. Length : 2
…..
59
Python Dictionary (5)
Some Built-in Dictionary Methods
Method Description Example
dict = {'Name': 'Zara',
dict.clear() Removes all 'Age': 7};print "Start
elements of Len : %d" % len(dict)
dict.clear()
dictionary dict. print "End Len : %d" %
len(dict)
Start Len : 2
End Len : 0
dict1 = {'Name':
dict.copy() Returns a shallow 'Zara', 'Age': 7};
copy of dict2 = dict1.copy()
print "New Dictinary :
dictionary dict. %s" % str(dict2)
…..
60
PYTHON DATE & TIME
Some Examples
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 63
26 27 28 29 30
PYTHON FUNCTION
What is a Function?
Example
Pass by Reference VS Pass by Value
Types of Function Arguments
The return Statement
Global Variable VS Local Variable
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 # Function definition is here
def changeme( mylist ): def changeme( mylist ):
# This changes a passed list into # This changes a passed list into
this function" this function"
mylist.append([1,2,3,4]); mylist = [1,2,3,4]; # This would
print "Values inside the # assign new reference in mylist
function: ", mylist print "Values inside the
return function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30]; # Now you can call changeme function
changeme( mylist ); mylist = [10,20,30];
print "Values outside the function: changeme( mylist );
", mylist print "Values outside the function:
", mylist
Output
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Output
Values outside the function: [10, 20, 30, [1, 2, 3, 4]] Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
67
Types of Function Arguments
Function Argument Description Example
def test(str):
Required Arguments The arguments passed to print (str)
a function in correct test()
positional order. The
number of arguments in Traceback (most recent call last):
the function call should File "python_func.py", line 4, in <module>
test()
match exactly with the TypeError: test() takes exactly 1 argument
(0 given)
function definition.
def printinfo( name, age ):
Keyword Arguments When use keyword print "Name: ", name
arguments in a function print "Age ", age
69
Types of Function Arguments
(3)
Function Argument Description Example
def printinfo( arg1,
Variable-length We may need to process *vartuple ):
Arguments a function for more print "Output is: "
print arg1
arguments than for var in vartuple:
print var
specified while defining
printinfo( 10 )
the function. These printinfo( 70, 60, 50 )
arguments are called Output is:
variable-length 10
Output is:
arguments and are not 70
60
named in the function 50
definition 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
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;
Output
Inside the function local total : 30
Outside the function global total : 0
72
PYTHON MODULES
What is a Module?
import Statement
from… import Statement
Namespaces and Scoping
Some Functions
Python Packages
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.
Example
tmodule.py
def print_func( par ):
print "Hello : ", par
74
import Statement
# Import module tmodule
import tmodule
Output
Hello : Zara
75
from…import Statement
Python's from statement allows you to import specific attributes
from a module into the current namespace.
Syntax Example
from modname import tmodule.py
def print_func( par ):
name1[, name2[, ... print "Hello : ", par
print_func_2("Zara")
Output
Good Morning Zara
76
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).
Output Output
2000 2000
Traceback (most recent call last): 2001
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
78
Some Functions
Function Description Example
import tmodule
dir( ) Returns a sorted list of
strings containing the print dir(tmodule)
G:.
└──phone
__init__.py (required to make Python treat phone as a package)
g3.py
isdn.py
pots.py
80
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" 81
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. DOCUMENTS\PythonPrograms')
import phone
phone.pots_func()
phone.isdn_func()
phone.g3_func() 82
Output
I'm Pots Phone
I'm ISDN Phone
I'm G3 Phone
83
PYTHON FILE MANAGEMENT
Introduction
Example
Some More File Operation Functions
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. 85
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())
88
Some More File Operation
Functions
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.
…..
89
Example (tell())
90
PYTHON EXCEPTION
HANDLING
What is Exception?
Handling an Exception
try.....except.....else
try.....finally
Argument of an Exception
User-Defined Exceptions
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.
92
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.
93
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.
94
try.....except.....else (Example)
Example I Example II
try: try:
fh = open("testfile", "w") fh = open("testfile_2", "r")
fh.write("This is my test file string = fh.read()
for exception handling!!") except IOError:
except IOError: print "Error: can\'t find file
print "Error: can\'t find file or read data"
or read data" else:
else: print string
print "Written content in the fh.close()
file successfully"
fh.close()
Output Output
Written content in the file successfully Error: can't find file or read data
95
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. 96
......................
Example
Example I Example II
try: try:
fh = open("testfile", "w") fh = open("testfile_2", "r")
fh.write("This is my test file string = fh.read()
for exception handling!!") except IOError:
except IOError: print "Error: can\'t find file
print "Error: can\'t find file or read data"
or read data" else:
else: print string
print "Written content in the finally:
file successfully" print "Closing the file"
finally: fh.close()
print "Closing the file"
fh.close()
Output Output
Written content in the file successfully Error: can't find file or read data
Closing the file Closing the file
97
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...
98
Example
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain
numbers\n", Argument
Output
The argument does not contain numbers
99
invalid literal for int() with base 10: 'xyz'
User-Defined Exceptions
Python also allows you to create your own exceptions by
deriving classes from the standard built-in exceptions.
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 100
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
101