This document provides an overview of the Python programming language tutorial presented over multiple pages. It covers:
1) An introduction to Python, its features, and why it is useful including that it is easy to use, portable, object oriented, and has many standard libraries.
2) An explanation of the different parts of the tutorial covering basic concepts like variables, data types, control structures, functions and exceptions as well as data structures and files.
3) Hands-on examples of using Python's basic types like numbers, strings, lists, tuples and dictionaries along with operations on each and how to use the interactive shell and IDE interfaces.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
The core of extensible programming is defining functions. Python allows mandatory and optional arguments, keyword arguments, and even arbitrary argument lists
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
The core of extensible programming is defining functions. Python allows mandatory and optional arguments, keyword arguments, and even arbitrary argument lists
INTRODUCTION TO PYTHON
Python is an interpreted, object-oriented, high-level programming language
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
A standard distribution includes many modules
Dynamic typed Source can be compiled or run just-in-time Similar to perl, tcl, ruby
Why Python
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way
Python Interfaces
IDLE : a cross-platform Python development
Python Win: a Windows only interface to Python
Python Shell running 'python' from the Command Line opens this interactive shell
IDLE — Development Environment
IDLE helps you program in Python by
color-coding your program code
debugging ' auto-indent ‘
interactive shell Python Shell
Auto indent
Example python
Print (“Hello World”)
output:
Hello World
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:
if 5 > 2: print("Five is greater than two!")
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code
Example
#This is a commentprint("Hello, World!")
Python Variables
Variables are containers for storing data values
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it
Example
x = 5y = "John"print(x)print(y)
Python - Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
Legal variable names:
myvar = "John"my_var = "John"_my_var = "John"myVar = "John"MYVAR = "John"myvar2 = "John
Python Variables - Assign Multiple Values
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"print(x)print(y)print(z)
Python - Output Variables
Python output variable function are print()
Example
x = "Python is awesome"print(x)
Python - Global Variables
Variables that are created outside of a function (as in all
Gurukul Skills Schedule for the Month of March
Time Cohort-10 Cohort-11 Cohort-12
8.00 to 09.25 Revision Revision Revision
5 Minutes Short Break
9.30 to 11.30 Chartered Accountants Chartered Accountants ENGLISH/SOFT SKILLS
15 Minutes Short Break
11.45 to 01.45 ICT ENGLISH/SOFT SKILLS R&A
45 Minutues Lunch Break
2.30 to 04.30 ENGLISH/SOFT SKILLS R&A ICT
15 Minutes Short Break
4.45 to 06.30 R&A ICT ACCOUNTS
5 Minutes Short Break
6.35 to 08.00 Assingments Assingments Assingments
INTRODUCTION TO PYTHON
Python is an interpreted, object-oriented, high-level programming language
Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
A standard distribution includes many modules
Dynamic typed Source can be compiled or run just-in-time Similar to perl, tcl, ruby
Why Python
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way
Python Interfaces
IDLE : a cross-platform Python development
Python Win: a Windows only interface to Python
Python Shell running 'python' from the Command Line opens this interactive shell
IDLE — Development Environment
IDLE helps you program in Python by
color-coding your program code
debugging ' auto-indent ‘
interactive shell Python Shell
Auto indent
Example python
Print (“Hello World”)
output:
Hello World
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:
if 5 > 2: print("Five is greater than two!")
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code
Example
#This is a commentprint("Hello, World!")
Python Variables
Variables are containers for storing data values
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it
Example
x = 5y = "John"print(x)print(y)
Python - Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
Legal variable names:
myvar = "John"my_var = "John"_my_var = "John"myVar = "John"MYVAR = "John"myvar2 = "John
Python Variables - Assign Multiple Values
Python allows you to assign values to multiple variables in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"print(x)print(y)print(z)
Python - Output Variables
Python output variable function are print()
Example
x = "Python is awesome"print(x)
Python - Global Variables
Variables that are created outside of a function (as in all
Gurukul Skills Schedule for the Month of March
Time Cohort-10 Cohort-11 Cohort-12
8.00 to 09.25 Revision Revision Revision
5 Minutes Short Break
9.30 to 11.30 Chartered Accountants Chartered Accountants ENGLISH/SOFT SKILLS
15 Minutes Short Break
11.45 to 01.45 ICT ENGLISH/SOFT SKILLS R&A
45 Minutues Lunch Break
2.30 to 04.30 ENGLISH/SOFT SKILLS R&A ICT
15 Minutes Short Break
4.45 to 06.30 R&A ICT ACCOUNTS
5 Minutes Short Break
6.35 to 08.00 Assingments Assingments Assingments
2. Page 1
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 2
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 3
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 4
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
7. Page 6
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 7
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
11. Page 10
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 11
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 output7.5
>>> 7.0 / 2 output->3.5
•Complex numbers are also supported
>>> (3+1j)*3
(9+3j)
Part I – Basic Types
13. Page 12
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)
15. Page 14
• 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 15
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 16
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
19. Page 18
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 19
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 20
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 21
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 22
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 23
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