SlideShare a Scribd company logo
1 of 75
Download to read offline
Introduction to Python 
Sushant Mane 
President @Walchand Linux User's Group 
sushantmane.github.io
What is Python? 
● Python is a programming language that lets you 
work quickly and integrate systems more 
effectively. 
● Interpreted 
● Object Oriented 
● Dynamic language 
● Multi-purpose
Let's be Comfortable 
● Let’s try some simple math to get 
started! 
>>>print 1 + 2 
>>>print 10 * 2 
>>>print 5 - 3 
>>>print 4 * 4
help() for help 
● To get help on any Python object type 
help(object) 
eg. To get help for abs function 
>>>help(abs) 
● dir(object) is like help() but just gives a quick list 
of the defined symbols 
>>>dir(sys)
Basic Data type's 
● Numbers 
– int 
– float 
– complex 
● Boolean 
● Sequence 
– Strings 
– Lists 
– Tuples
Why built-in Types? 
● Make programs easy to write. 
● Components of extensions. 
● Often more efficient than custom data structures. 
● A standard part of the language
Core Data Types 
Row 1 Row 2 Row 3 Row 4 
12 
10 
8 
6 
4 
2 
0 
Column 1 
Column 2 
Column 3 
Object type literals/creation 
Numbers 1234, 3.1415, 3+4j, Decimal, Fraction 
Strings 'spam', “india's", b'ax01c' 
Lists [1, [2, 'three'], 4] 
Dictionaries {'food': 'spam', 'taste': 'yum'} 
Tuples (1, 'spam', 4, 'U') 
Files myfile = open(‘python', 'r') 
Sets set('abc'), {'a', 'b', 'c'} 
Other core types Booleans, type, None 
Program unit types Functions, modules, classes
Variables 
● No need to declare 
● Need to initialize 
● Almost everything can be assigned to a variable
Numeric Data Types
int 
>>>a = 3 
>>>a 
● a is a variable of the int type
long 
>>>b = 123455L 
>>>b = 12345l 
● b is a long int 
● For long -- apeend l or L to number
float 
>>>p = 3.145897 
>>>p 
● real numbers are represented using the float 
● Notice the loss of precision 
● Floats have a fixed precision
complex 
>>c = 3 + 4j 
● real part : 3 
● imaginary part : 4 
>>c.real 
>>c.imag 
>>abs(c) 
● It’s a combination of two floats 
● abs gives the absolute value
Numeric Operators 
● Addition : 10 + 12 
● Substraction : 10 - 12 
● Division : 10 / 17 
● Multiplication : 2 * 8 
● Modulus : 13 % 4 
● Exponentiation : 12 ** 2
Numeric Operators 
● Integer Division (floor division) 
>>>10 / 17 0 
● Float Division 
>>>10.0 / 17 0.588235 
>>>flot(10) / 17 0.588235 
● The first division is an integer division 
● To avoid integer division, at least one number 
should be float
Variables 
And 
Assignment
Variables 
● All the operations could be done on variables 
>>>a = 5 
>>>b = 3.4 
>>>print a, b
Assignments 
● Assignment 
>>>c = a + b 
● c = c / 3 is equivalent to c /= 3 
● Parallel Assignment 
>>>a, b = 10, 12 
>>>c, d, red, blue = 123, 121, 111, 444
Booleans and Operations 
● All the operations could be done on variables 
>>>t = True 
>>>t 
>>>f = not True 
>>>f 
>>>f or t 
● can use parenthesis. 
>>>f and (not t)
Container Data 
Types 
i.e. Sequences
Sequences 
● Hold a bunch of elements in a sequence 
● Elements are accessed based on position in the 
sequence 
● The sequence data-types 
– list 
– tuple 
– dict 
– str
list 
● Items are enclosed in [ ] and separated by “ , ” 
constitute a list 
>>>list = [1, 2, 3, 4, 5, 6] 
● Items need not to have the same type 
● Like indexable arrays 
● Extended at right end 
● List are mutable (i.e. will change or can be changed) 
● Example 
>>>myList = [631, “python”, [331, ”computer” 
]]
List Methods 
● append() : myList.append(122) 
● insert() : myList.insert(2,”group”) 
● pop() : myList.pop([i] ) 
● reverse() : myList.reverse() 
● sort() : myList.sort([ reverse=False] ) 
– where [] indicates optional
Tuples 
● Items are enclosed in ( ) and separated by ”, ” 
constitute a list 
>>>tup = (1, 2, 3, 4, 5, 6) 
● Nesting is Possible 
● Outer Parentheses are optional 
● tuples are immutable (i.e. will never change cannot be 
changed) 
● Example 
>>>myTuple = (631, “python”, [ 331 , 
”computer” ])
Tuple Methods 
Concatenation : myTuple + (13, ”science”) 
Repeat : myTuple * 4 
Index : myTuple[i] 
Length : len( myTuple ) 
Membership : ‘m’ in myTuple
Strings
Strings . . . 
● Contiguous set of characters in between 
quotation marks 
eg. ”wceLinuxUsers123Group” 
● Can use single or double quotes 
>>>st = 'wceWlug' 
>>>st = ”wceWlug”
Strings . . . 
● three quotes for a multi-line string. 
>>> ''' Walchand 
. . . Linux 
. . . Users 
. . . Group''' 
>>> ”””Walchand 
. . . Linux 
. . . Users 
. . . Group”””
Strings Operators 
● “linux"+"Users" 'linuxUsers' # concatenation 
● "linux"*2 'linuxlinux' # repetition 
● "linux"[0] 'l' # indexing 
● "linux"[-1] 'x' # (from end) 
● "linux"[1:4] 'iu' # slicing 
● len("linux") 5 # size 
● "linux" < "Users" 1 # comparison 
● "l" in "linux" True # search
Strings Formating 
● <formatted string> % <elements to insert> 
● Can usually just use %s for everything, it will convert the 
object to its String representation. 
● eg. 
>>> "One, %d, three" % 2 
'One, 2, three' 
>>> "%d, two, %s" % (1,3) 
'1, two, 3' 
>>> "%s two %s" % (1, 'three') 
'1 two three'
Strings and Numbers 
>>>ord(text) 
● converts a string into a number. 
● Example: 
ord("a") is 97, 
ord("b") is 98, ...
Strings and Numbers 
>>>chr(number) 
● Example: 
chr(97) is 'a', 
chr(98) is 'b', ...
Python : No Braces 
● Uses indentation instead of braces to determine 
the scope of expressions 
● Indentation : space at the beginning of a line of 
writing 
eg. writing answer point-wise
Python : No Braces 
● All lines must be indented the same amount to be 
part of the scope (or indented more if part of an 
inner scope) 
● forces the programmer to use proper indentation 
● indenting is part of the program!
Python : No Braces 
● All lines must be indented the same amount to be 
part of the scope (or indented more if part of an 
inner scope) 
● forces the programmer to use proper indentation 
● indenting is part of the program!
Control 
Flow
Control Flow 
● If statement : powerful decision making 
statement 
● Decision Making And Branching 
● Used to control the flow of execution of program 
● Basically two-way decision statement
If Statement 
>>> x = 12 
>>> if x <= 15 : 
y = x + 15 
>>> print y 
● if condition : 
statements 
Indentation
If-else Statement 
● if condition : 
Statements 
else : 
Statements 
>>> x = 12 
>>> if x <= 15 : 
y = x + 13 
Z = y + y 
else : 
y = x 
>>> print y
If-elif Statement 
● if condition : 
Statements 
elif condition : 
Statements 
else : 
Statements 
>>> x = 30 
>>> if x <= 15 : 
y = x + 13 
elif x > 15 : 
y = x - 10 
else : 
y = x 
>>> print y
Looping
Looping 
● Decision making and looping 
● Process of repeatedly executing a block of 
statements
while loop 
● while condition : 
Statements 
>>> x = 0 
>>> while x <= 10 : 
x = x + 1 
print x 
>>> print “x=”,x
Loop control statement 
break Jumps out of the closest enclosing 
loop 
continue Jumps to the top of the closest 
enclosing loop
while – else clause 
● while condition : 
Statements 
else : 
Statements 
>>> x = 0 
>>> while x <= 6 : 
x = x + 1 
print x 
else : 
y = x 
>>> print y 
The optional else clause 
runs only if the loop exits 
normally (not by break)
For loop 
iterating through a list of values 
>>>for n in [1,5,7,6]: 
print n 
>>>for x in range(4): 
print x
range() 
● range(N) generates a list of numbers [0,1, ...,N-1] 
● range(i , j, k) 
● I --- start (inclusive) 
● j --- stop (exclusive) 
● k --- step
For – else clause 
● for var in Group : 
Statements 
else : 
Statements 
>>>for x in range(9): 
print x 
else : 
y = x 
>>> print y 
For loops also may have the 
optional else clause
User : Input 
● The raw_input(string) method returns a line of 
user input as a string 
● The parameter is used as a prompt 
>>> var = input(“Enter your name :”) 
>>> var = raw_input(“Enter your name & 
BDay”)
Functions
functions 
● Code to perform a specific task. 
● Advantages: 
● Reducing duplication of code 
● Decomposing complex problems into simpler 
pieces 
● Improving clarity of the code 
● Reuse of code 
● Information hiding
functions 
● Basic types of functions: 
● Built-in functions 
Examples are: dir() 
len() 
abs() 
● User defined 
Functions created with the ‘ def ’ 
keyword.
Defining functions 
>>> def f(x): 
… return x*x 
>>> f(1) 
>>> f(2) 
● def is a keyword 
● f is the name of the function 
● x the parameter of the function 
● return is a keyword; specifies what should be 
returned
Calling a functions 
>>>def printme( str ): 
>>> #"This prints a passed string into this 
function" 
>>> print str; 
>>> return; 
… 
To call function, printme 
>>>printme(“HELLO”); 
Output 
HELLO
Modules
modules 
● A module is a python file that (generally) has only 
● definitions of variables, 
● functions and 
● classes
Importing modules 
Modules in Python are used by importing them. 
For example, 
1] import math 
This imports the math standard module. 
>>>print math.sqrt(10)
Importing modules.... 
2] 
>>>from string import whitespace 
only whitespace is added to the current scope 
>>>from math import * 
all the elements in the math namespace are added
creating module 
Python code for a module named ‘xyz’ resides in a 
file named file_name.py. 
Ex. support.py 
>>> def print_func( par ): 
print "Hello : ", par 
return 
The import Statement: 
import module1[, module2[,... moduleN] 
Ex: >>>import support 
>>>support.print_func(“world!”);
Doc-Strings 
● It’s highly recommended that all functions have 
documentation 
● We write a doc-string along with the function 
definition 
>>> def avg(a, b): 
… """ avg takes two numbers as input 
and returns their average""" 
… return (a + b)/2 
>>>help(avg)
Returning multiple values 
Return area and perimeter of circle, given radius 
Function needs to return two values 
>>>def circle(r): 
… pi = 3.14 
… area = pi * r * r 
… perimeter = 2 * pi * r 
… return area, perimeter 
>>>a, p = circle(6) 
>>>print a
File 
Handling
Basics of File Handling 
● Opening a file: 
Use file name and second parameter-"r" is for 
reading, the "w" for writing and the "a" for 
appending. 
eg. 
>>>fh = open("filename_here", "r") 
● Closing a file 
used when the program doesn't need it more. 
>>>fh.close()
functions File Handling 
Functions available for reading the files: read, 
readline and readlines. 
● The read function reads all characters. 
>>>fh = open("filename", "r") 
>>>content = fh.read()
functions File Handling 
● The readline function reads a single line from the 
file 
>>>fh = open("filename", "r") 
>>>content = fh.readline() 
● The readlines function returns a list containing all 
the lines of data in the file 
>>>fh = open("filename", "r") 
>>>content = fh.readlines()
Write and write lines 
To write a fixed sequence of characters to a file: 
>>>fh = open("hello.txt","w") 
>>>fh.write("Hello World")
Write and writelines 
You can write a list of strings to a file 
>>>fh = open("hello.txt", "w") 
>>>lines_of_text = ["a line of text", 
"another line of text", "a third line"] 
>>>fh.writelines(lines_of_text)
Renaming Files 
Python os module provides methods that help you 
perform file-processing operations, such as renaming 
and deleting files. 
rename() Method 
>>>import os 
>>>os.rename( "test1.txt", "test2.txt" )
Deleting Files 
remove() Method 
>>>os.remove(file_name)
OOP 
Class
Class 
A set of attributes that characterize any object of the class. 
The attributes are data members (class variables and instance 
variables) and methods 
Code: 
class Employee: 
empCount = 0 
def __init__(self, name, salary): 
self.name = name 
self.salary = salary 
Employee.empCount += 1 
def displayCount(self): 
print "Total Employee %d" % Employee.empCount
Class 
● empCount is a class variable shared among all 
instances of this class. This can be accessed as 
Employee.empCount from inside the class or 
outside the class. 
● first method __init__() is called class constructor or 
initialization method that Python calls when a new 
instance of this class is created. 
● You declare other class methods like normal 
functions with the exception that the first 
argument to each method is self.
Class 
Creating instances 
emp1 = Employee("Zara", 2000) 
Accessing attributes 
emp1.displayEmployee()
Queries ?
thank you !

More Related Content

What's hot

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
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)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonYi-Fan Chu
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with pythonPraveen M Jigajinni
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the StyleJuan-Manuel Gimeno
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Jaganadh Gopinadhan
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming LanguageR.h. Himel
 
Python | What is Python | History of Python | Python Tutorial
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
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Fariz Darari
 
POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE teachersduniya.com
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 

What's hot (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
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)
Introduction to the basics of Python programming (part 1)
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python
PythonPython
Python
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Python ppt
Python pptPython ppt
Python ppt
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Introduction to Python Basics Programming
Introduction to Python Basics ProgrammingIntroduction to Python Basics Programming
Introduction to Python Basics Programming
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the Style
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Python | What is Python | History of Python | Python Tutorial
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
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE POWER OF PYTHON PROGRAMMING LANGUAGE
POWER OF PYTHON PROGRAMMING LANGUAGE
 
Variables in python
Variables in pythonVariables in python
Variables in python
 

Viewers also liked

03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Classes & object
Classes & objectClasses & object
Classes & objectDaman Toor
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsRanel Padon
 
2 introduction to soil mechanics
2 introduction to soil mechanics2 introduction to soil mechanics
2 introduction to soil mechanicsMarvin Ken
 
Introduction and types of soil mechanics
Introduction and types of soil mechanicsIntroduction and types of soil mechanics
Introduction and types of soil mechanicsSafiullah Khan
 
Spss lecture notes
Spss lecture notesSpss lecture notes
Spss lecture notesDavid mbwiga
 
TRANSPORTATION PLANNING
TRANSPORTATION PLANNINGTRANSPORTATION PLANNING
TRANSPORTATION PLANNINGintan fatihah
 
Make any girl want to fuck
Make any girl want to fuckMake any girl want to fuck
Make any girl want to fuckphilipss clerke
 
Soil mechanics note
Soil mechanics noteSoil mechanics note
Soil mechanics noteSHAMJITH KM
 

Viewers also liked (15)

03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Classes & object
Classes & objectClasses & object
Classes & object
 
Fun with python
Fun with pythonFun with python
Fun with python
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Human factor risk
Human factor riskHuman factor risk
Human factor risk
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
 
2 introduction to soil mechanics
2 introduction to soil mechanics2 introduction to soil mechanics
2 introduction to soil mechanics
 
Python overview
Python   overviewPython   overview
Python overview
 
Introduction and types of soil mechanics
Introduction and types of soil mechanicsIntroduction and types of soil mechanics
Introduction and types of soil mechanics
 
Spss lecture notes
Spss lecture notesSpss lecture notes
Spss lecture notes
 
TRANSPORTATION PLANNING
TRANSPORTATION PLANNINGTRANSPORTATION PLANNING
TRANSPORTATION PLANNING
 
Make any girl want to fuck
Make any girl want to fuckMake any girl want to fuck
Make any girl want to fuck
 
Soil mechanics note
Soil mechanics noteSoil mechanics note
Soil mechanics note
 

Similar to Introduction To Programming with Python

Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobikrmboya
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012Shani729
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.pptVicVic56
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming LanguageRohan Gupta
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.pptssuserd64918
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfRamziFeghali
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on PythonSumit Raj
 

Similar to Introduction To Programming with Python (20)

Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Python 101
Python 101Python 101
Python 101
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
 
Python Essentials - PICT.pdf
Python Essentials - PICT.pdfPython Essentials - PICT.pdf
Python Essentials - PICT.pdf
 
Python basics
Python basicsPython basics
Python basics
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Python
PythonPython
Python
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Python intro
Python introPython intro
Python intro
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
 
Pres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdfPres_python_talakhoury_26_09_2023.pdf
Pres_python_talakhoury_26_09_2023.pdf
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 

Recently uploaded

%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 

Recently uploaded (20)

%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Introduction To Programming with Python

  • 1. Introduction to Python Sushant Mane President @Walchand Linux User's Group sushantmane.github.io
  • 2. What is Python? ● Python is a programming language that lets you work quickly and integrate systems more effectively. ● Interpreted ● Object Oriented ● Dynamic language ● Multi-purpose
  • 3. Let's be Comfortable ● Let’s try some simple math to get started! >>>print 1 + 2 >>>print 10 * 2 >>>print 5 - 3 >>>print 4 * 4
  • 4. help() for help ● To get help on any Python object type help(object) eg. To get help for abs function >>>help(abs) ● dir(object) is like help() but just gives a quick list of the defined symbols >>>dir(sys)
  • 5. Basic Data type's ● Numbers – int – float – complex ● Boolean ● Sequence – Strings – Lists – Tuples
  • 6. Why built-in Types? ● Make programs easy to write. ● Components of extensions. ● Often more efficient than custom data structures. ● A standard part of the language
  • 7. Core Data Types Row 1 Row 2 Row 3 Row 4 12 10 8 6 4 2 0 Column 1 Column 2 Column 3 Object type literals/creation Numbers 1234, 3.1415, 3+4j, Decimal, Fraction Strings 'spam', “india's", b'ax01c' Lists [1, [2, 'three'], 4] Dictionaries {'food': 'spam', 'taste': 'yum'} Tuples (1, 'spam', 4, 'U') Files myfile = open(‘python', 'r') Sets set('abc'), {'a', 'b', 'c'} Other core types Booleans, type, None Program unit types Functions, modules, classes
  • 8. Variables ● No need to declare ● Need to initialize ● Almost everything can be assigned to a variable
  • 10. int >>>a = 3 >>>a ● a is a variable of the int type
  • 11. long >>>b = 123455L >>>b = 12345l ● b is a long int ● For long -- apeend l or L to number
  • 12. float >>>p = 3.145897 >>>p ● real numbers are represented using the float ● Notice the loss of precision ● Floats have a fixed precision
  • 13. complex >>c = 3 + 4j ● real part : 3 ● imaginary part : 4 >>c.real >>c.imag >>abs(c) ● It’s a combination of two floats ● abs gives the absolute value
  • 14. Numeric Operators ● Addition : 10 + 12 ● Substraction : 10 - 12 ● Division : 10 / 17 ● Multiplication : 2 * 8 ● Modulus : 13 % 4 ● Exponentiation : 12 ** 2
  • 15. Numeric Operators ● Integer Division (floor division) >>>10 / 17 0 ● Float Division >>>10.0 / 17 0.588235 >>>flot(10) / 17 0.588235 ● The first division is an integer division ● To avoid integer division, at least one number should be float
  • 17. Variables ● All the operations could be done on variables >>>a = 5 >>>b = 3.4 >>>print a, b
  • 18. Assignments ● Assignment >>>c = a + b ● c = c / 3 is equivalent to c /= 3 ● Parallel Assignment >>>a, b = 10, 12 >>>c, d, red, blue = 123, 121, 111, 444
  • 19. Booleans and Operations ● All the operations could be done on variables >>>t = True >>>t >>>f = not True >>>f >>>f or t ● can use parenthesis. >>>f and (not t)
  • 20. Container Data Types i.e. Sequences
  • 21. Sequences ● Hold a bunch of elements in a sequence ● Elements are accessed based on position in the sequence ● The sequence data-types – list – tuple – dict – str
  • 22. list ● Items are enclosed in [ ] and separated by “ , ” constitute a list >>>list = [1, 2, 3, 4, 5, 6] ● Items need not to have the same type ● Like indexable arrays ● Extended at right end ● List are mutable (i.e. will change or can be changed) ● Example >>>myList = [631, “python”, [331, ”computer” ]]
  • 23. List Methods ● append() : myList.append(122) ● insert() : myList.insert(2,”group”) ● pop() : myList.pop([i] ) ● reverse() : myList.reverse() ● sort() : myList.sort([ reverse=False] ) – where [] indicates optional
  • 24. Tuples ● Items are enclosed in ( ) and separated by ”, ” constitute a list >>>tup = (1, 2, 3, 4, 5, 6) ● Nesting is Possible ● Outer Parentheses are optional ● tuples are immutable (i.e. will never change cannot be changed) ● Example >>>myTuple = (631, “python”, [ 331 , ”computer” ])
  • 25. Tuple Methods Concatenation : myTuple + (13, ”science”) Repeat : myTuple * 4 Index : myTuple[i] Length : len( myTuple ) Membership : ‘m’ in myTuple
  • 27. Strings . . . ● Contiguous set of characters in between quotation marks eg. ”wceLinuxUsers123Group” ● Can use single or double quotes >>>st = 'wceWlug' >>>st = ”wceWlug”
  • 28. Strings . . . ● three quotes for a multi-line string. >>> ''' Walchand . . . Linux . . . Users . . . Group''' >>> ”””Walchand . . . Linux . . . Users . . . Group”””
  • 29. Strings Operators ● “linux"+"Users" 'linuxUsers' # concatenation ● "linux"*2 'linuxlinux' # repetition ● "linux"[0] 'l' # indexing ● "linux"[-1] 'x' # (from end) ● "linux"[1:4] 'iu' # slicing ● len("linux") 5 # size ● "linux" < "Users" 1 # comparison ● "l" in "linux" True # search
  • 30. Strings Formating ● <formatted string> % <elements to insert> ● Can usually just use %s for everything, it will convert the object to its String representation. ● eg. >>> "One, %d, three" % 2 'One, 2, three' >>> "%d, two, %s" % (1,3) '1, two, 3' >>> "%s two %s" % (1, 'three') '1 two three'
  • 31. Strings and Numbers >>>ord(text) ● converts a string into a number. ● Example: ord("a") is 97, ord("b") is 98, ...
  • 32. Strings and Numbers >>>chr(number) ● Example: chr(97) is 'a', chr(98) is 'b', ...
  • 33. Python : No Braces ● Uses indentation instead of braces to determine the scope of expressions ● Indentation : space at the beginning of a line of writing eg. writing answer point-wise
  • 34. Python : No Braces ● All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) ● forces the programmer to use proper indentation ● indenting is part of the program!
  • 35. Python : No Braces ● All lines must be indented the same amount to be part of the scope (or indented more if part of an inner scope) ● forces the programmer to use proper indentation ● indenting is part of the program!
  • 37. Control Flow ● If statement : powerful decision making statement ● Decision Making And Branching ● Used to control the flow of execution of program ● Basically two-way decision statement
  • 38. If Statement >>> x = 12 >>> if x <= 15 : y = x + 15 >>> print y ● if condition : statements Indentation
  • 39. If-else Statement ● if condition : Statements else : Statements >>> x = 12 >>> if x <= 15 : y = x + 13 Z = y + y else : y = x >>> print y
  • 40. If-elif Statement ● if condition : Statements elif condition : Statements else : Statements >>> x = 30 >>> if x <= 15 : y = x + 13 elif x > 15 : y = x - 10 else : y = x >>> print y
  • 42. Looping ● Decision making and looping ● Process of repeatedly executing a block of statements
  • 43. while loop ● while condition : Statements >>> x = 0 >>> while x <= 10 : x = x + 1 print x >>> print “x=”,x
  • 44. Loop control statement break Jumps out of the closest enclosing loop continue Jumps to the top of the closest enclosing loop
  • 45. while – else clause ● while condition : Statements else : Statements >>> x = 0 >>> while x <= 6 : x = x + 1 print x else : y = x >>> print y The optional else clause runs only if the loop exits normally (not by break)
  • 46. For loop iterating through a list of values >>>for n in [1,5,7,6]: print n >>>for x in range(4): print x
  • 47. range() ● range(N) generates a list of numbers [0,1, ...,N-1] ● range(i , j, k) ● I --- start (inclusive) ● j --- stop (exclusive) ● k --- step
  • 48. For – else clause ● for var in Group : Statements else : Statements >>>for x in range(9): print x else : y = x >>> print y For loops also may have the optional else clause
  • 49. User : Input ● The raw_input(string) method returns a line of user input as a string ● The parameter is used as a prompt >>> var = input(“Enter your name :”) >>> var = raw_input(“Enter your name & BDay”)
  • 51. functions ● Code to perform a specific task. ● Advantages: ● Reducing duplication of code ● Decomposing complex problems into simpler pieces ● Improving clarity of the code ● Reuse of code ● Information hiding
  • 52. functions ● Basic types of functions: ● Built-in functions Examples are: dir() len() abs() ● User defined Functions created with the ‘ def ’ keyword.
  • 53. Defining functions >>> def f(x): … return x*x >>> f(1) >>> f(2) ● def is a keyword ● f is the name of the function ● x the parameter of the function ● return is a keyword; specifies what should be returned
  • 54. Calling a functions >>>def printme( str ): >>> #"This prints a passed string into this function" >>> print str; >>> return; … To call function, printme >>>printme(“HELLO”); Output HELLO
  • 56. modules ● A module is a python file that (generally) has only ● definitions of variables, ● functions and ● classes
  • 57. Importing modules Modules in Python are used by importing them. For example, 1] import math This imports the math standard module. >>>print math.sqrt(10)
  • 58. Importing modules.... 2] >>>from string import whitespace only whitespace is added to the current scope >>>from math import * all the elements in the math namespace are added
  • 59. creating module Python code for a module named ‘xyz’ resides in a file named file_name.py. Ex. support.py >>> def print_func( par ): print "Hello : ", par return The import Statement: import module1[, module2[,... moduleN] Ex: >>>import support >>>support.print_func(“world!”);
  • 60. Doc-Strings ● It’s highly recommended that all functions have documentation ● We write a doc-string along with the function definition >>> def avg(a, b): … """ avg takes two numbers as input and returns their average""" … return (a + b)/2 >>>help(avg)
  • 61. Returning multiple values Return area and perimeter of circle, given radius Function needs to return two values >>>def circle(r): … pi = 3.14 … area = pi * r * r … perimeter = 2 * pi * r … return area, perimeter >>>a, p = circle(6) >>>print a
  • 63. Basics of File Handling ● Opening a file: Use file name and second parameter-"r" is for reading, the "w" for writing and the "a" for appending. eg. >>>fh = open("filename_here", "r") ● Closing a file used when the program doesn't need it more. >>>fh.close()
  • 64. functions File Handling Functions available for reading the files: read, readline and readlines. ● The read function reads all characters. >>>fh = open("filename", "r") >>>content = fh.read()
  • 65. functions File Handling ● The readline function reads a single line from the file >>>fh = open("filename", "r") >>>content = fh.readline() ● The readlines function returns a list containing all the lines of data in the file >>>fh = open("filename", "r") >>>content = fh.readlines()
  • 66. Write and write lines To write a fixed sequence of characters to a file: >>>fh = open("hello.txt","w") >>>fh.write("Hello World")
  • 67. Write and writelines You can write a list of strings to a file >>>fh = open("hello.txt", "w") >>>lines_of_text = ["a line of text", "another line of text", "a third line"] >>>fh.writelines(lines_of_text)
  • 68. Renaming Files Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files. rename() Method >>>import os >>>os.rename( "test1.txt", "test2.txt" )
  • 69. Deleting Files remove() Method >>>os.remove(file_name)
  • 71. Class A set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods Code: class Employee: empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount
  • 72. Class ● empCount is a class variable shared among all instances of this class. This can be accessed as Employee.empCount from inside the class or outside the class. ● first method __init__() is called class constructor or initialization method that Python calls when a new instance of this class is created. ● You declare other class methods like normal functions with the exception that the first argument to each method is self.
  • 73. Class Creating instances emp1 = Employee("Zara", 2000) Accessing attributes emp1.displayEmployee()