0% found this document useful (0 votes)
4 views51 pages

Python Basics

Uploaded by

aagg4189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views51 pages

Python Basics

Uploaded by

aagg4189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Python

Introduction
Python Preliminaries
• A multi-paradigm language
▫ Procedural, Functional, Object-Oriented etc.
• Has an interpreter
• Downloadable from www.python.org
• Editor used: IDLE

• Suggested Readings:
▫ Allen Downey: Think Python – How to Think Like a
Computer Scientist, Green Tea Press.
▫ Mark Lutz: Programming Python, O’ Reilly.
In Python you can do -
• Procedural Programming
• Object-Oriented Programming
• Functional Programming
• Event-Driven Programming
• Concurrent/Parallel Programming
• Database Programming
• Network Programming
• Server-Side Scripting
• Client-Side Scripting
• Python-C Integration
Python Preliminaries
• All programming constructs are just like
C/C++
▫ If, for, while etc. except for code blocks { }
• Math Ops: + , –, *, /, %, **
• Logical Ops: and, or, not
• Comparison Ops: < , >, <=, >=, ==, !=
Python By Examples
• > print " Hello World" [= Hello World]
•>2 + 2 [= 4]
•>6 – 3 [= 3]
• > 18/3 [= 6]
• > 18/7 [= 2 integer
division]
• > 18.0/7 [ = 2.5714]
• > 18/7. does the same
thing
• > 19%2 [=1 finds
modulus]
• > 8.75%5 [ = 0.25]
• > 8**3 [= 512 ] 8 raise to
the
Python By Examples
Variables
• > x=18 [x is integer 18]
• > y=2.5
•>x + y [ = 20.5]
•>z = x + y [ z=20.5]

Input
• > g=input ("Enter a number")
[ Enter a number = 10 (user input) ---> g
becomes 10]
• > f = input() [ No message]
Python By Examples
• > pow(5,4) [54=625]
• > abs(–18) [= 18]
• > floor(18.7) Error
Message [Function reside in
modules so we have to import module]

• > import math


• > math.floor(18.7) [= 18]
• > math.sqrt(81) [= 9]

• > s = math.sqrt(81)

• > mysqrt = math.sqrt


• > mysqrt(81) [= 9]
Create and Save Programs
• File -> new window
• write program -> save as fn.py
▫ Note: Save before run [ use F5 for Run ]
Program
x = raw_input ("Enter Name:" )
print ("Hey" + x)
print ("Press Enter")
input()

▫ fn.py can be executed by clicking the file icon


Strings
• "Hey now" is same as 'Hey now'
• 'He's a boy" [incorrect]
• "He's a boy" [correct]
• 'He\'s a boy' [correct, using escape
character]
• "He said "Good bye" to me" [incorrect]
• "He said \"Good bye\" to me" [correct]
Storing Strings
• S1= "Hello"
• S2 = " There"
• S1+S2 [concatenation]
• S1, S2 [puts them in tuples like ('Hello'
, 'S2' )]
• num =18
• print "I am " + str(num)
or
• n= str(18)
• print "I am " + n
or
• print "I am " + `num`
▫ Note: we can use repr( ) function in place of str( ).
Raw Input
• input [treat input as numbers]
• raw_input [treat input as string]
• n = input() [n is a number]
• s=raw_input() [s is a string]
Sequence and Lists
creating a list
• color = ['Red' , 'green', 'blue',
'yellow']
• indexes 0 1 2 3
-4 -3 -2 -1
color[2] -> 'blue', color[-1] -> 'yellow',
color[-3] -> 'green'
• Strings can also be indexed
• str = 'Dayalbagh'
str[0] -> 'D', str[1] -> 'a'
also
str[-1] -> 'h'
str[-2] -> 'g'
Slicing
• example = [0,1,2,3,4,5,6,7,8,9]
• example[4:8] [4,5,6,7]
• example[4:9] [4,5,6,7,8]
• example[-5:-1] [5,6,7,8]
• example[-5:0] does not work
• example[-5:] till the end
• example[:7] from the start
• example[:] full list
• example[1:8:2] [1,3,5,7] 2 is the

increment
• example [10:2:-2] [9,7,5,3]
• example [ : :-2] count backwards
entire list
Editing Sequences
• [7,4,5] + [4,6,5] gives
[7,4,5,4,6,5]
• [4,6,5] + ["Hello"] Error Not same
types

• "Hello"*10

Hello Hello Hello Hello Hello Hello Hello


Hello Hello Hello

• [20]*10

[20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20]
Membership
• name = 'Dayalbagh'

• 'z' in name [false]


• 'y' in name [true]

• color = ['Red','blue','green']

• 'yellow' in color [false]


More on Lists
• number=[8,1,4,17,28,165,7]
• len(number) [7]
• min(number) [1]
• max(number) [165]
• list('dayalbagh')

['d','a','y','a','l','b','a','g','h']
converts string to list
• number[3]=77
[8,1,4,77,28,165,7]
• del(number[3]) [8,1,4,28,165,7]
More on Slicing
• ex=list('dayalbagh')
• ex[4:]=list('Singh') [d a y a S i n g
h]

• ex=[7,8,9]
• ex[1:1]=[3,3,3] [7,3,3,3,8,9]

• ex=[1,2,3,4,5]
• ex[1:3]=[8,8,8,8] [1,8,8,8,8,4,5]

• del ex[1:5] [1,4,5]


Methods
• nums=[21,18,30]
• nums.append(45)
[nums=21,18,30,45] nums is
object and append is method.
• nums=[1,2,3,3,4,3,4]
• nums.count(4) [= 2]
• nums.count(5) [= 0]
• one = [1,2,3]
• two = [4,5,6]
• one.extend(two)
[one gives
1,2,3,4,5,6]
More Methods
• color=['red','green','yellow']
• color.index('green') [ =1 ]

• color.insert(2,'cyan')

• color.pop(1) [returns element


with
index 1 and delete from
list]

• color.remove('yellow')

• color.reverse()
Sorting
• nums=[2,5,28,17,14]
• nums.sort() [ascending order]

• nums.sort(reverse=True) [for descending


order]

• sorted( 'dayalbagh') [sorted list]


Tuples
• 2,5,3,7 (2,5,3,7)
• texm=(2,5,3,7) tuple cannot be
changed
• texm[2] [gives 3]

• color=['red','green','blue']
[has to be a list]
• color2=('black')
[has to be a tuple]
• color2.join(color)

[red black green black blue black yellow


black]
Strings
• str="Hey there %s, How are you %s"
• varb=('amit','today')
• print str % varb

• str="Hey there how are you"


• str.find('there') [= 4 ]

• str="Good MORNING"
• str.lower() [good
morning]
• str="Hey there how are you there"
• str.replace('there','man' )
[Hey man how are you
Dictionary
• book={'Dad':'Bob','Mom':'Lisa','Bro':'Joe'
} [Dad is key and Bob is definition.]

• book['Dad'] ['Bob']
• book.clear() [clear all items]
• book2=book.copy() [copies dictionary]
• book.has_key('Mom') [true]
Programs: if statement
color="blue"
if color == "blue" :
print "Right Color"

if color == "blue":
print "Right Color"
else :
print "Wrong Color"

• Nesting of if / if - else is possible.


• blocking is based on indentation.
Programs: if statement
if color == "blue" :
print "Blue"
else if color == "green" :
print "Green"
else if color == "yellow" :
print "yellow"
else :
print(" Wrong Color")

n=10
if n > 3 and n < 30 :
print "Right "
if a > 10 or b < 10 :
print "big"
Comparing Lists
• one=[1,2,3]
• two=[1,2,3]
• three=[1,2,4]
• one is two [False, it will be
true only when they
refer to the same
objects.]

• one is three [False]


• three=four=[1,2,4]
• three is four [True]

• "drag" < "Cat" [False]


Programs: While Loop
b=1
while b<=10 :
print b
b=b+1 // b+=1
Programs: For Loop
color=['red','green','yellow']
for c in color :
print "I like " + c

nums=[1,2,3,4,5]
for i in nums :
print i
Programs: For Loop
Loop through dictionary book
for item in book : [item - set to
keys]
print item, book[item]

Infinite loop and break


while 1:
name=raw_input("Enter Name")
if name == 'quit' :
break
Programs: For Loop
range(4) [0,1,2,3]

num=[1,2,3,4,5]
for i in range (len(num)) :
num[i] = num[i]*2

Note: for usual for i = 0 to 9 use while


loop.
Building Functions
def hello (x) :
return "Hello " + x

>print hello ('Sanjay') [Hello


Sanjay]

def plusten(x):
return x+10

>print plusten(44) [54]


Functions - Parameters
def name(first,last) :
print "%s %s" % (first,last)

>name('Amit','Sharma') [Amit
Sharma]

def name (first='Tom',last='Smith') :


print "%s %s" % (first, last)

> name() [Tom Smith]


> name(last='Peter') [Tom Peter]
Multiple Parameters to a
Function
def list(* col) : [* signifies multiple
print col
parameters]

>list('Yellow') [Yellow]
>list('Red','Blue','Green') [Red Blue
Green]

def profile(name, *ages) :


print name
print ages

>profile('Amit',20,30,40) [Amit 20 30
Recursive Function
def sum(x) :
if x==1:
return 1
else :
return x + sum (x-1)

>print sum(10) [55]


Function Parameter -
Dictionary
def cart (**items) : [items
belongs to print items
dictionary]

>cart(apples=4,oranges=6)
[apples,oranges -> key; 4,6 ->
def]
Output =
{'apples':4,'oranges':6}

def profile(first,last,*ages,**items) :
print first, last
print ages
items
Functions – Tuples as
Parameters
def example(a,b,c) :
return a+b*c

>num=(5,7,3) [tuple]
>example(*num)
[* means tuple, ** means
dictionary]

def example2(**this) :
print this

>book = {'Dad':55,'Mom':50}
>example2(**book)
Output =
Object-Orientation in
Python
Creating Classes and Objects
• Creating a Class
class student :
name='Amit'
age=22
def sayhello(self) :
return 'Hello There'

• Creating objects
ex1=student()
ex1.name [Amit]
ex1.age [22]
ex1.sayhello() [Hello There]
Creating Classes and Objects
class className :
def createName(self, name) :
self.name=name
def displayName(self) :
return self.name
def saying(self) :
print "Hello %s" % self.name

• first=className( )
• second=className( )
• first.createName('Sanjay')
• second.createName('Amit')
• first.displayName() [Sanjay]
• first.saying() [Hello
Sanjay]
Inheritance – Subclasses and
Superclasses
class parentclass :
var1='I am var1'
var2='I am var2'

class childclass (parentclass) :


pass [means do nothing]

• PO = parentclass()
• PO.var1 ['I am
var1']
• CO = childclass()
• CO.var1 ['I am
var1']
Inheritance – Subclasses and
Superclasses
class parent :
name = "Sanjay"
rollno = 123

class child (parent) :


rollno = 456

• pob = parent()
• cob = child()
• pob.name [Sanjay]
• pob.rollno [123]
• cob.name [Sanjay]
• cob.rollno [456]
Multiple Inheritance
class Mom :
var1= "ABC"
class Dad :
var2="DEF"
class child (Mom,Dad) :
var3 = "GHI"

• cob=child()

• cob.var1 [ABC]
• cob.var2 [DEF]
• cob.var3 [GHI]
Constructors
class new :
def __init__ (self) :
print "constructor "

• obj = new() [constructor is called


here]
Files
File Operations
• fob=open('a.txt','w') [Opens a file a.txt
in
‘w’rite mode]
• fob.write('Hey there') [Write to the file]
• fob.close() [Close the file]

• fob=open('a.txt','r') [Opens a file a.txt


in
‘r’ead mode]

• fob.read(3) [reads 3 characters


from
file a.txt]
• fob.read() [Reads full file from
Reading a File Line-By-Line
• fob=open('a.txt','r')
• print fob.readline() [Reads one line
from the
file pointer]
• print fob.readlines() [Reads all the lines
from the file pointer and
puts them in a list
making each line a
separate element
in the list]
• fob.close()
• fob=open('a.txt','w')
• fob.write('this is a new line \n this is
another line \n')
Writing a File Line-By-Line
• fob=open('a.txt','r')
• listme=fob.readlines() [Reads all the lines in
listme]
• fob.close()
• listme[2]="this is a test\n"
[Changes line 2 in
listme]

• fob=open('a.text','w')
• fob.writelines(listme) [Writes all the lines
in listme to fob,
i.e., a.txt]
• fob.close()
Modules
Creating/Importing Modules
• type in a file

def testmod( ) [type as many


functions print "This works" as you like]

• save in python directory [example :


mymod.py]

• import mymod
• run it as mymod.testmod()

• Note : if we make any change in the module, if


we say <import mymod> again, it will not work.
we have to use reload(mymod)
Getting Module Info
• import math [Import a module such as
‘math’]
• dir(math) [Prints all functions that math
module contain]

• help(math) [Prints all functions that


math module contain with
details]
• math.__doc__ [info]
Thank you!

You might also like