SlideShare a Scribd company logo
Python Basics
By
Guru Y
Guru Y
Page 2
Tutorial Overview
Part I
•Introduction
•Installing Python
•First steps
•Basic types: numbers, strings
•Container types: lists, dictionaries, Tuples
Part II
• Variables
•Control structures
•Functions
•Modules
Part III
•Exceptions
•Data Structures
•Files & standard library
Page 3
What is Python
Python is an interpreted, interactive, object oriented programming
language. Python can be compared to PERL, TCL or Java.
Part I Introduction
Page 4
Why is Python
Part I Introduction
1) Easy to Use and Easy to Learn
2) High Level: When you write programs in Python, you never need to bother
about the low-level details such as managing the memory used by your
program, etc.
3) Open Source Language
4) Portable : Works on Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2,
AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC
OS, VxWorks, PlayStation, Windows CE and even PocketPC.
5) Object Oriented
6) Powerful to use: It has various libraries which supports databases, network,
Internet, XML, GUI, HTML, CGI, FTP, email etc…
7) Embeddable: You can embed Python within your C/C++ programs to give
'scripting' capabilities to the users.
Finally: Batteries Included
__________________________________________________________________________________
No other language has made me more productive than Python. Python is perhaps the only one language that
focuses on making things easier for the programmer.
-- Bruce Eckel author of the famous 'Thinking in Java' and 'Thinking in C++' books.
Python has always been an integral part of Google
---Peter Norvig ( Lisp author and Director of Search Quality at Google )
Python has beaten contenders like Perl and Ruby to become the main programming that will be supported by
UserLinux -- Bruce Perens (co-founder of OpenSource.org)
Page 5
How to Use Python
Installation
Python can be installed from the following web pages.
http://www.python.org/download (Core Python)
http://www.activestate.com (Active Python)
Currently downloadable versions are –
Python 2.4
Python 2.5
Active Python :
In addition to core Python build, ActivePython includes a suite of
tools and resources to enhance Python programming productivity
1) The PyWin32 Windows Extensions interface to the Win32 API.
2) PythonCOM for integrating Python with COM and ASP.
3) Pythonwin Development Environment, for the Windows platform
Part I Introduction
Page 6
Hands on
Install Python
Part I - Installation
Page 7
Types of Interfaces
When you install python we get 2 interfaces through which we can start writing
python commands.
1) Python's interactive shell (command line).
2) Pythonwin IDLE (Integrated DeveLopment Environment)
Part I – First Steps
Types of
Interfaces
Page 8
Interactive Mode
Types of Interfaces
When you install python we get 2 interfaces through which we can
start writing python commands.
1) Python's interactive shell (command line).
2) Pythonwin IDLE (Integrated DeveLopment Environment)
When commands are read from a terminal, the interpreter is said
to be in interactive mode.
In this mode it prompts for the next command with the primary
prompt, usually three greater-than signs (">>> ")
For continuation lines it prompts with the secondary prompt, by
default three dots ("... ").
The interpreter prints a welcome message stating its version
number and a copyright notice before printing the first prompt:
Part I – First Steps
Page 9
Python's interactive shell
Part I – First Steps
Page 10
Pythonwin IDE
Part I – First Steps
Page 11
Hands On
 Use Python AS calculator
 Type statements or expressions at prompt:
>>>print "Hello, world"
Hello, world
>>> x = 12**2
>>> print x/2
72
>>> # this is a comment
>>> width=20
>>> height=5*9
>>> width* height
Part I – First Steps
Page 12
The Basic types
Numbers
•The interpreter acts as a simple calculator: you can type an
expression and it will give the results.
>>> 2+2
•A value can be assigned to several variables simultaneously
>>> x = y = z = 0 # Zero x, y and z
•There is full support for floating point
•operators with mixed type operands convert the integer operand
to floating point:
>>> 3 * 3.75 / 1.5 output7.5
>>> 7.0 / 2 output->3.5
•Complex numbers are also supported
>>> (3+1j)*3
(9+3j)
Part I – Basic Types
Page 13
Operators
Numeric Operators
Unary operators
+, - , ~ (inversion operator)
Binary operators
+ , - , * / , % , **
Binary Bitwise Operations
& (AND), | (OR), ^ (XOR)
Shifting Operators
<< , >>
for x in range(0,-10,-1): print x,~x
Other functions
• abs(x) This function takes absolute value of any integer
• divmod(a,b) This performs division and returns quotient and remainder
• pow(x,y[z]) Calculates the “power-of” (z performs modulo operation)
• Round(x,[y]) Rounds the floating point number
• min(x,y,…)
• max(x,y,..)
• cmp(x,y)
Page 14
Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" True # comparison
• "e" in "hello" True # search
Usage of “, “”, ‘’’
Escape Sequence
The Basics
Part I – Basic Types
Page 15
• Strings can be subscripted (indexed)
• Like in C, the first character of a string has subscript (index) 0.
• There is no separate character type;
• A character is simply a string of size one.
• An omitted first index defaults to zero, an omitted second index defaults
to the size of the string being sliced
>>> “hello”[:2] ‘he' # The first two characters
>>> “hello”[2:] ‘llo’ #Except the first two characters
Indices may be negative numbers, to start counting from the right. For
example:
>>> “hello”[-1] ‘0' # The last character
>>> “hello”[-2] ‘l' # Last but one character
>>> “hello”[-2:] ‘lo' # The last two characters
>>> “hello”[:-2] ‘hel' # Except the last two
characters
More on Strings
Part I – Basic Types
H E L L O
0 1 2 3 4
-5 -4 -3 -2 -1
Page 16
Variables
Variables are the identifiers which can hold any type of data.
No need to declare
Need to assign (initialize)
use of uninitialized variable raises exception
Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
Everything is a "variable":
Even functions, classes, modules
Part I – Variables
Page 17
Hands On
Part I – Hands on
Use PythonWin editor and create a Script
Use notepad to create Python script
Use Advanced Editors (Eclipse-PyDev) to create the Python Scripts
Exercise
 Write programs using
 PythonWin
 Notepad
 Eclipse
 Write a Python script to take input from the user and display the output using
 PythonWin
 Notepad
Page 18
Container Types
Python Supports several Container types
 Lists
 Tuples
 Sets
 Dictionaries
Page 19
Lists
 List is an ordered collection of zero or more elements.
 An element of a list can be any sort of object.
 These are comma seperated values enclosed in SQAURE Brackets[].
Also called as Flexible arrays
a = [99, "bottles of beer", ["on", "the", "wall"]]
Same operators as for strings
a+b, a*3, a[0], a[-1], a[1:], len(a)
Item and slice assignment
a[0] = 98
a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]
del a[-1] # -> [98, "bottles", "of", "beer"]
Part I – Container Types
Page 20
More List Operations
>>> a = range(5) # [0,1,2,3,4]
>>> a.append(5) # [0,1,2,3,4,5]
>>> a.pop() # [0,1,2,3,4]
5
>>> a.insert(0, 42) # [42,0,1,2,3,4]
>>> a.pop(0) # [0,1,2,3,4]
>>> a.reverse() # [4,3,2,1,0]
>>> a.sort() # [0,1,2,3,4]
>>> a.index(4) # 4
>>> del a[ : ]
Part I – Container Types
Page 21
Using Lists
List can be used as a stack which is based on the principle “last-in,
first-out” .
>>> stack = [3, 4, 5] >>>stack. Pop()
>>> stack.append(6) stack=[3,4,5,6]
>>> stack.append(7) >>>stack. Pop()
Stack=[3,4,5,6,7] stack=[3,4,5]
List can also be used as a queue based on the principle “first-in, first-
out”.
>>>queue=[“Eric”, ”John”, “Michael”]
>>>queue. Append (“Terry”)
queue=[“Eric”, “John”, “Michael”, “Terry”]
>>>queue. Pop(0)
queue=[“John”, “Michael”, ”Terry”]
Part I – Container Types
Page 22
Tuples
 A tuple consists of a set of values separated by commas and enclosed
by Parenthesis “()”.
 It is similar to Lists.
 The difference is that Tuples are Immutable.
>>> t =(12345, 54321, 'hello!') # parentheses optional
>>> # Tuples may be nested:
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
t = 12345, 54321, 'hello!' #tuple packing
x, y, z = t # tuple unpacking
singleton = (1,) # Note trailing comma!!!
empty = () # parentheses!
**Strings and Tuples are immutable
Part I – Container Types
Page 23
Dictionaries
 Dictionary is a Python object that cross-references keys to values.
 A Key is an immutable object such as a string
 Dictionaries are unordered set of “key-value” pairs
 Also called as "associative arrays“
d = {"duck": "eend", "water": "water"}
Lookup:
d["duck"] -> "eend"
d["back"] # raises KeyError exception
Delete, insert, overwrite:
del d["water"] # {"duck": "eend“}
d["back"] = "rug" # {"duck": "eend", "back": "rug"}
d["duck"] = "duik" # {"duck": "duik", "back": "rug"}
Part I – Container Types
Page 24
More Dictionary Ops
 Keys, values, items:
d.keys() -> ["duck", "back"]
d.values() -> ["duik", "rug"]
d.items() -> [("duck","duik"), ("back","rug")]
 Presence check:
d.has_key("duck") -> True
d.has_key("spam") -> False
 Values of any type; keys almost any
{"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
Part I – Container Types
Page 25
Hands On
Part I – Hands on
Work on the Lists, Tuples and Dictionary
Page 26
QUESTIONS
Page 27
Imagination Action Joy
End of PART-I
Ad

Recommended

Python for Beginners(v1)
Python for Beginners(v1)
Panimalar Engineering College
 
Python unit 2 is added. Has python related programming content
Python unit 2 is added. Has python related programming content
swarna16
 
Learning python
Learning python
Hoang Nguyen
 
Learning python
Learning python
Harry Potter
 
Learning python
Learning python
Tony Nguyen
 
Learning python
Learning python
Luis Goldster
 
Learning python
Learning python
James Wong
 
Learning python
Learning python
Young Alista
 
Learning python
Learning python
Fraboni Ec
 
problem solving and python programming UNIT 2.pdf
problem solving and python programming UNIT 2.pdf
rajesht522501
 
Problem Solving and Python Programming UNIT 2.pdf
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
Python Demo.pptx
Python Demo.pptx
ParveenShaik21
 
Python Demo.pptx
Python Demo.pptx
ParveenShaik21
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Lecture1_cis4930.pdf
Lecture1_cis4930.pdf
zertash1
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
ppt_pspp.pdf
ppt_pspp.pdf
ShereenAhmedMohamed
 
Python basics to advanced in on ppt is available
Python basics to advanced in on ppt is available
nexasbravo2000sep
 
Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python chapter presentation details.pptx
Python chapter presentation details.pptx
linatalole2001
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
swarna627082
 
Sessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python Workshop
Python Workshop
Assem CHELLI
 
Python-Basics.pptx
Python-Basics.pptx
TamalSengupta8
 
Unit 2 python
Unit 2 python
praveena p
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
INTRODUCTION TO POINTER IN c++ AND POLYMORPHISM
INTRODUCTION TO POINTER IN c++ AND POLYMORPHISM
M.H.Saboo Siddik Polytechnic
 
Data_Analytics_Types_Presentation12.pptx
Data_Analytics_Types_Presentation12.pptx
M.H.Saboo Siddik Polytechnic
 

More Related Content

Similar to Python Programming Basic , introductions (20)

Learning python
Learning python
Fraboni Ec
 
problem solving and python programming UNIT 2.pdf
problem solving and python programming UNIT 2.pdf
rajesht522501
 
Problem Solving and Python Programming UNIT 2.pdf
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
Python Demo.pptx
Python Demo.pptx
ParveenShaik21
 
Python Demo.pptx
Python Demo.pptx
ParveenShaik21
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Lecture1_cis4930.pdf
Lecture1_cis4930.pdf
zertash1
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
ppt_pspp.pdf
ppt_pspp.pdf
ShereenAhmedMohamed
 
Python basics to advanced in on ppt is available
Python basics to advanced in on ppt is available
nexasbravo2000sep
 
Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python chapter presentation details.pptx
Python chapter presentation details.pptx
linatalole2001
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
swarna627082
 
Sessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python Workshop
Python Workshop
Assem CHELLI
 
Python-Basics.pptx
Python-Basics.pptx
TamalSengupta8
 
Unit 2 python
Unit 2 python
praveena p
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
Learning python
Learning python
Fraboni Ec
 
problem solving and python programming UNIT 2.pdf
problem solving and python programming UNIT 2.pdf
rajesht522501
 
Problem Solving and Python Programming UNIT 2.pdf
Problem Solving and Python Programming UNIT 2.pdf
rajesht522501
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
funadamentals of python programming language (right from scratch)
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Lecture1_cis4930.pdf
Lecture1_cis4930.pdf
zertash1
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbai
vibrantuser
 
Python basics to advanced in on ppt is available
Python basics to advanced in on ppt is available
nexasbravo2000sep
 
Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python chapter presentation details.pptx
Python chapter presentation details.pptx
linatalole2001
 
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING.pptx
swarna627082
 
Sessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
ComandosDePython_ComponentesBasicosImpl.ppt
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 

More from M.H.Saboo Siddik Polytechnic (6)

INTRODUCTION TO POINTER IN c++ AND POLYMORPHISM
INTRODUCTION TO POINTER IN c++ AND POLYMORPHISM
M.H.Saboo Siddik Polytechnic
 
Data_Analytics_Types_Presentation12.pptx
Data_Analytics_Types_Presentation12.pptx
M.H.Saboo Siddik Polytechnic
 
Effective_Memorization_Techniques123.ppt
Effective_Memorization_Techniques123.ppt
M.H.Saboo Siddik Polytechnic
 
C++ Pointers , Basic to advanced Concept
C++ Pointers , Basic to advanced Concept
M.H.Saboo Siddik Polytechnic
 
Memory in Pointer,What is pointer, how memory is used in C
Memory in Pointer,What is pointer, how memory is used in C
M.H.Saboo Siddik Polytechnic
 
Introduction to Pointers in C and C++. What is pointer
Introduction to Pointers in C and C++. What is pointer
M.H.Saboo Siddik Polytechnic
 
Ad

Recently uploaded (20)

grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
resming1
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
ijab2
 
The basics of hydrogenation of co2 reaction
The basics of hydrogenation of co2 reaction
kumarrahul230759
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
最新版美国圣莫尼卡学院毕业证(SMC毕业证书)原版定制
Taqyea
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Microwatt: Open Tiny Core, Big Possibilities
Microwatt: Open Tiny Core, Big Possibilities
IBM
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
Deep Learning for Natural Language Processing_FDP on 16 June 2025 MITS.pptx
resming1
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
OCS Group SG - HPHT Well Design and Operation - SN.pdf
OCS Group SG - HPHT Well Design and Operation - SN.pdf
Muanisa Waras
 
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
VARICELLA VACCINATION: A POTENTIAL STRATEGY FOR PREVENTING MULTIPLE SCLEROSIS
ijab2
 
The basics of hydrogenation of co2 reaction
The basics of hydrogenation of co2 reaction
kumarrahul230759
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Ad

Python Programming Basic , introductions

  • 2. Page 2 Tutorial Overview Part I •Introduction •Installing Python •First steps •Basic types: numbers, strings •Container types: lists, dictionaries, Tuples Part II • Variables •Control structures •Functions •Modules Part III •Exceptions •Data Structures •Files & standard library
  • 3. Page 3 What is Python Python is an interpreted, interactive, object oriented programming language. Python can be compared to PERL, TCL or Java. Part I Introduction
  • 4. Page 4 Why is Python Part I Introduction 1) Easy to Use and Easy to Learn 2) High Level: When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc. 3) Open Source Language 4) Portable : Works on Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Windows CE and even PocketPC. 5) Object Oriented 6) Powerful to use: It has various libraries which supports databases, network, Internet, XML, GUI, HTML, CGI, FTP, email etc… 7) Embeddable: You can embed Python within your C/C++ programs to give 'scripting' capabilities to the users. Finally: Batteries Included __________________________________________________________________________________ No other language has made me more productive than Python. Python is perhaps the only one language that focuses on making things easier for the programmer. -- Bruce Eckel author of the famous 'Thinking in Java' and 'Thinking in C++' books. Python has always been an integral part of Google ---Peter Norvig ( Lisp author and Director of Search Quality at Google ) Python has beaten contenders like Perl and Ruby to become the main programming that will be supported by UserLinux -- Bruce Perens (co-founder of OpenSource.org)
  • 5. Page 5 How to Use Python Installation Python can be installed from the following web pages. http://www.python.org/download (Core Python) http://www.activestate.com (Active Python) Currently downloadable versions are – Python 2.4 Python 2.5 Active Python : In addition to core Python build, ActivePython includes a suite of tools and resources to enhance Python programming productivity 1) The PyWin32 Windows Extensions interface to the Win32 API. 2) PythonCOM for integrating Python with COM and ASP. 3) Pythonwin Development Environment, for the Windows platform Part I Introduction
  • 6. Page 6 Hands on Install Python Part I - Installation
  • 7. Page 7 Types of Interfaces When you install python we get 2 interfaces through which we can start writing python commands. 1) Python's interactive shell (command line). 2) Pythonwin IDLE (Integrated DeveLopment Environment) Part I – First Steps Types of Interfaces
  • 8. Page 8 Interactive Mode Types of Interfaces When you install python we get 2 interfaces through which we can start writing python commands. 1) Python's interactive shell (command line). 2) Pythonwin IDLE (Integrated DeveLopment Environment) When commands are read from a terminal, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (">>> ") For continuation lines it prompts with the secondary prompt, by default three dots ("... "). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt: Part I – First Steps
  • 9. Page 9 Python's interactive shell Part I – First Steps
  • 10. Page 10 Pythonwin IDE Part I – First Steps
  • 11. Page 11 Hands On  Use Python AS calculator  Type statements or expressions at prompt: >>>print "Hello, world" Hello, world >>> x = 12**2 >>> print x/2 72 >>> # this is a comment >>> width=20 >>> height=5*9 >>> width* height Part I – First Steps
  • 12. Page 12 The Basic types Numbers •The interpreter acts as a simple calculator: you can type an expression and it will give the results. >>> 2+2 •A value can be assigned to several variables simultaneously >>> x = y = z = 0 # Zero x, y and z •There is full support for floating point •operators with mixed type operands convert the integer operand to floating point: >>> 3 * 3.75 / 1.5 output7.5 >>> 7.0 / 2 output->3.5 •Complex numbers are also supported >>> (3+1j)*3 (9+3j) Part I – Basic Types
  • 13. Page 13 Operators Numeric Operators Unary operators +, - , ~ (inversion operator) Binary operators + , - , * / , % , ** Binary Bitwise Operations & (AND), | (OR), ^ (XOR) Shifting Operators << , >> for x in range(0,-10,-1): print x,~x Other functions • abs(x) This function takes absolute value of any integer • divmod(a,b) This performs division and returns quotient and remainder • pow(x,y[z]) Calculates the “power-of” (z performs modulo operation) • Round(x,[y]) Rounds the floating point number • min(x,y,…) • max(x,y,..) • cmp(x,y)
  • 14. Page 14 Strings • "hello"+"world" "helloworld" # concatenation • "hello"*3 "hellohellohello" # repetition • "hello"[0] "h" # indexing • "hello"[-1] "o" # (from end) • "hello"[1:4] "ell" # slicing • len("hello") 5 # size • "hello" < "jello" True # comparison • "e" in "hello" True # search Usage of “, “”, ‘’’ Escape Sequence The Basics Part I – Basic Types
  • 15. Page 15 • Strings can be subscripted (indexed) • Like in C, the first character of a string has subscript (index) 0. • There is no separate character type; • A character is simply a string of size one. • An omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced >>> “hello”[:2] ‘he' # The first two characters >>> “hello”[2:] ‘llo’ #Except the first two characters Indices may be negative numbers, to start counting from the right. For example: >>> “hello”[-1] ‘0' # The last character >>> “hello”[-2] ‘l' # Last but one character >>> “hello”[-2:] ‘lo' # The last two characters >>> “hello”[:-2] ‘hel' # Except the last two characters More on Strings Part I – Basic Types H E L L O 0 1 2 3 4 -5 -4 -3 -2 -1
  • 16. Page 16 Variables Variables are the identifiers which can hold any type of data. No need to declare Need to assign (initialize) use of uninitialized variable raises exception Not typed if friendly: greeting = "hello world" else: greeting = 12**2 print greeting Everything is a "variable": Even functions, classes, modules Part I – Variables
  • 17. Page 17 Hands On Part I – Hands on Use PythonWin editor and create a Script Use notepad to create Python script Use Advanced Editors (Eclipse-PyDev) to create the Python Scripts Exercise  Write programs using  PythonWin  Notepad  Eclipse  Write a Python script to take input from the user and display the output using  PythonWin  Notepad
  • 18. Page 18 Container Types Python Supports several Container types  Lists  Tuples  Sets  Dictionaries
  • 19. Page 19 Lists  List is an ordered collection of zero or more elements.  An element of a list can be any sort of object.  These are comma seperated values enclosed in SQAURE Brackets[]. Also called as Flexible arrays a = [99, "bottles of beer", ["on", "the", "wall"]] Same operators as for strings a+b, a*3, a[0], a[-1], a[1:], len(a) Item and slice assignment a[0] = 98 a[1:2] = ["bottles", "of", "beer"] -> [98, "bottles", "of", "beer", ["on", "the", "wall"]] del a[-1] # -> [98, "bottles", "of", "beer"] Part I – Container Types
  • 20. Page 20 More List Operations >>> a = range(5) # [0,1,2,3,4] >>> a.append(5) # [0,1,2,3,4,5] >>> a.pop() # [0,1,2,3,4] 5 >>> a.insert(0, 42) # [42,0,1,2,3,4] >>> a.pop(0) # [0,1,2,3,4] >>> a.reverse() # [4,3,2,1,0] >>> a.sort() # [0,1,2,3,4] >>> a.index(4) # 4 >>> del a[ : ] Part I – Container Types
  • 21. Page 21 Using Lists List can be used as a stack which is based on the principle “last-in, first-out” . >>> stack = [3, 4, 5] >>>stack. Pop() >>> stack.append(6) stack=[3,4,5,6] >>> stack.append(7) >>>stack. Pop() Stack=[3,4,5,6,7] stack=[3,4,5] List can also be used as a queue based on the principle “first-in, first- out”. >>>queue=[“Eric”, ”John”, “Michael”] >>>queue. Append (“Terry”) queue=[“Eric”, “John”, “Michael”, “Terry”] >>>queue. Pop(0) queue=[“John”, “Michael”, ”Terry”] Part I – Container Types
  • 22. Page 22 Tuples  A tuple consists of a set of values separated by commas and enclosed by Parenthesis “()”.  It is similar to Lists.  The difference is that Tuples are Immutable. >>> t =(12345, 54321, 'hello!') # parentheses optional >>> # Tuples may be nested: >>> u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) t = 12345, 54321, 'hello!' #tuple packing x, y, z = t # tuple unpacking singleton = (1,) # Note trailing comma!!! empty = () # parentheses! **Strings and Tuples are immutable Part I – Container Types
  • 23. Page 23 Dictionaries  Dictionary is a Python object that cross-references keys to values.  A Key is an immutable object such as a string  Dictionaries are unordered set of “key-value” pairs  Also called as "associative arrays“ d = {"duck": "eend", "water": "water"} Lookup: d["duck"] -> "eend" d["back"] # raises KeyError exception Delete, insert, overwrite: del d["water"] # {"duck": "eend“} d["back"] = "rug" # {"duck": "eend", "back": "rug"} d["duck"] = "duik" # {"duck": "duik", "back": "rug"} Part I – Container Types
  • 24. Page 24 More Dictionary Ops  Keys, values, items: d.keys() -> ["duck", "back"] d.values() -> ["duik", "rug"] d.items() -> [("duck","duik"), ("back","rug")]  Presence check: d.has_key("duck") -> True d.has_key("spam") -> False  Values of any type; keys almost any {"name":"Guido", "age":43, ("hello","world"):1, 42:"yes", "flag": ["red","white","blue"]} Part I – Container Types
  • 25. Page 25 Hands On Part I – Hands on Work on the Lists, Tuples and Dictionary
  • 27. Page 27 Imagination Action Joy End of PART-I