0% found this document useful (0 votes)
253 views73 pages

Prepared By: Y. Rohita Assistant Professor Dept. of IT

The document outlines a syllabus for an introductory Python course covering topics like data types, operators, conditional statements, loops, functions, object oriented programming concepts, modules, and working with libraries like NumPy, PlotPy, SciPy and GUI programming with Tkinter. It lists two textbooks and three reference books for the course and provides details of the contents to be covered in each of the six units of the syllabus.

Uploaded by

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

Prepared By: Y. Rohita Assistant Professor Dept. of IT

The document outlines a syllabus for an introductory Python course covering topics like data types, operators, conditional statements, loops, functions, object oriented programming concepts, modules, and working with libraries like NumPy, PlotPy, SciPy and GUI programming with Tkinter. It lists two textbooks and three reference books for the course and provides details of the contents to be covered in each of the six units of the syllabus.

Uploaded by

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

Prepared By

Y. Rohita
Assistant Professor
Dept. of IT
Syllabus

Unit I : Introduction to Python


Unit II : Functions, String Manipulation, Lists, Tuple,
Dictionaries
Unit III: Modules
Unit IV : Advance Python: OOPs concept
Unit V : CGI, Python for Database
Unit VI : Working with NumPy/ PlotPy/ SciPy/ GUI
Programming, Introduction,Tkinter programming,
Tkinter widgets
Text books:
1. Think Python: How to Think Like a Computer Scientist Allen B.
Downey, O'Relly publications.
2. Learning with Python by Jeffrey Elkner, Chris Meyers Allen Downey,
Dreamtech Press

Reference books:
1. Introduction to Computation and Programming using Python,
Revised and Expanded Edition, John V. Guttag, The MIT Press.
2. Programming Python, Fourth Edition by Mark Lutz, O'Relly
3. Python Programming using problem solving approach, Reema
Thareja, Oxford Higher Education.
UNIT – I
Contents:
 Introduction to Python
 History
 Features
 Setting up path
 Working with Python Basic Syntax
 Variable and Data Types
 Operators
 Conditional Statements(If ,If- else ,Nested if-else)
 Looping( for, While Nested loops)
 Control Statements(Break , Continue ,Pass)
Introduction to Python
Python is a high-level, interpreted, interactive and object-oriented
scripting language. It is designed to be highly readable.

 Python is Interpreted: Python is processed at runtime by the


interpreter. You do not need to compile your program before
executing it .
 Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style
or technique of programming that encapsulates code within
objects.
 Python is a Beginner's Language: Python is a great language for
the beginner-level programmers and supports the development of
a wide range of applications from simple text processing to WWW
browsers to games.
History of Python

• Python was developed by


Guido Van Rossam in 1989
while working with NRI at
nether land but officially
Python language available
to the public in Feb20th1991.

Guido Van Rossam


Why the python?

At the time when he began implementing Python,


Guido van Rossum was also reading the published scripts
from "Monty Python's Flying Circus" (a BBC comedy series
from the seventies, in the unlikely case you didn't know). It
occurred to him that he needed a name that was short,
unique, and slightly mysterious, so he decided to call the
language Python.
Python is derived from many other languages

1. Functional programming from C language


2. OOP Features from C++
3. Scripting languages features from Perl and shell
4. Modular programming features from modula3.

Python syntax borrowed from C and ABC language.

Cpython, Jython, IronPython, Brython, RubyPython, PyPy etc..

Major implementations of Python are :


Python versions
There are three main versions of Python
Python 1.0 introduced in jan 1994
Python 2.0 introduced in oct 2000
Python 3.0 introduced in Dec 2008
Latest version of python:
Python 3.7.3 introduced in March 25,2019
Note:
Any new version should provide support for old version
programs. In python there is no such type of backward
compatibility.
If i can use python 3 never going to support for python 2.
print "hello" valid in python2 but invalid in python3.
Long data type is there on python2 but not in python3
Features of Python :
1. Simple and easy to learn
2. Freeware and open source
3. High level programming language
4. Platform independent
5. Portability
6. Dynamically typed
7. Both procedure oriented and Object Oriented
8. Interpreted
9. Extensible
10. Embedded
11. Extensive Library
1. Simple and easy to learn:
Python is a very easiest programming language. Any non-technical personal
can understand code that much easy to learn Python.
2. Freeware and open source
For developing a Python application you do not need to take a license.
Freeware means we do not require to pay single rupees.
Open source means we can see the code (implementation) of Python and
also we are allowed to make changes in the code and create one new version
(own version) of Python.
3. Platform independent
Python provides WORA(write once and read anywhere) feature. You can
write application one platform and run anytime on any machine.
Example:- write a program on windows and run code in Linux or any
platform.
4. Portability
Portability means moving Python program from one platform to another
without making any changes.
Example:- If you developed the application on windows machine and
windows encounters a problem then you can move to Linux machine is easy.
5. High-level programming language 
Python is human to understand the code. We write code as normal
English statement and we don’t require to worry about low-level
management.
6. Interpreted
In Python we don’t need to compile the Python code, Python
interpreter will compile the code if compilation fails Python raised a
compilation error. Once compilation success-ed Python virtual
machine executed the code. The interpreter executes the code line
by line.
7. Embedded
We can use python in other languages. Python program can be
embedded in other languages also.
8. Rich library support 
In python, there is a large number of the library available for every
requirement. We don’t require to write large code we simply import
libraries and use it in our code.
Python unique features
1. Extensible:
In Python, we can use other language programs (example: c, java)
2. Dynamically typed language
It is the most important feature of Python. In Python, we are not
required to specify the type of variable. We simply write the
variable name and assign value.
Python automatically assigns the type of variable depending on value.
Example:- x=10 Python variable without a type
Based on the type of value Python assigns into type to x variable.
3. Both procedures oriented and object-oriented language:
If you go for Python you can use both procedural and object-oriented
features. Python also supports scripting language features.
Applications of python:
Desktop application
Web applications : Django, Pyramid, Flask..etc
Data base applications
For Networking applications
Games
Data Analysis
Machine Learning applications
AI application
For IOT applications
Animation Applications

Note: for mobile based applications not that much recommended.


Which companies using python?
Limitations of python:

Performance and Speed


Incompatibility of Two Versions
Mobile applications
Installation of python
To install Python on a Windows machine, follow these steps:
1. Open a web browser and go to http://www.python.org.
2. Click the Download. The following page will appear in your browser.
3. Click the Download Python 3.7.0 button.
4. The file named python-3.7.0.exe should start downloading into your standard download
folder.
5. The file should appear as
6. Double-click the icon labelling the file python-3.7.0.exe.
7. An Open File - Security Warning pop-up window will appear.

8. Click Run.
9. A Python 3.7.0 (32-bit) Setup pop-up window will appear.

10. Ensure that the Install launcher for all users (recommended)  and
the Add Python 3.7 to PATH checkboxes at the bottom are checked.

11.If the Python Installer finds an earlier version of Python installed on


your computer, the Install Now message may instead appear
as Upgrade Now
12. Click the Yes button.
13. A new Python 3.7.0 (32-bit) Setup pop-up window will appear with
a Setup Progress message and a progress bar.
14. During installation, it will show the various components it is
installing and move the progress bar towards completion. Soon, a
new Python 3.7.0 (32-bit) Setup pop-up window will appear with
a Setup was successfully message.

15. Click the Close button.


Python should now be installed.
Setting up path in python
 To add the path to the python.exe file to the Path variable,
start the Run box and enter sysdm.cpl
 Go to the Advanced tab and click the Environment
Variables button.
 In the System variable window, find the Path variable and
click Edit.
 Position your cursor at the end of the Variable value line and
add the path to the python.exe file, preceded with the
semicolon character (;). In our example, we have added the
following value: ; C:\python 35-32;
 Close all windows. Now you can run python.exe without
specifying the full path to the file:
Working with Python Basic Syntax
There are two ways to use the Python interpreter:
1. Interactive Mode / shell mode (line by line execution):
In shell mode, you type Python expressions into the Python shell,
and the interpreter immediately shows the result.
>>> 2 + 3
5
>>> is called the Python prompt.

2. Batch Mode (entire program execution at a time):


The concept of writing group of python statements into a file,
saving that file with the extension ‘.py’ and submitting the entire file
to the python interpreter at a time is known as Batch mode.
 In order to develop the python files we use either editors or IDE’s.
 Different editors are notepad, notepad++, edit plus, vi, nano, gedit----
 Different IDE’s are pycharm, eric, netbeans, eclipse
 Open the notepad and write the following statements.
X=100
Y=20
Print(x+y)
Print(x-y)
Print(x*y)
Print(x/y)
Save the above file with demo.py in D:\foldername
Open the command prompt and execute the following commands.
D:\foldername >python demo.py
120
80
2000
5.0
Keywords in Python
1. Keywords are the reserved words in Python.
2. We can not use a keyword as variable name, function name or
any other identifier.
3. They are used to define the syntax and structure of the Python
language.
4. keywords are case sensitive.
5. There are 33 keywords in Python.
6. All the keywords except True, False and None are in lower case
and they must be written as it is.
7. You can always get the list of keywords in your current version by
typing the following in the prompt.
>>> import keyword
>>> keyword.kwlist
The list of all the keywords are given below.
Keywords in Python
True False None
and or not is
if else elif
while for break continue return in yield
try except finally raise assert
import from as class def pass global
nonlocal lambda del with
Python Identifiers :
The name which can be used for identification purpose is
known as Identifiers.
Identifier definition:- Name in python program is
Identifiers. It may be variable name, method name or class
name.
Identifiers Example

x=10 => variable name


class A{ } => Class name A
disp(){ } => Method name disp()
valid identifier in Python:
Identifiers can be a combination of letters in lowercase (a to
z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_).
Rules for Identifiers:
1. Identifier should contain Alphabet symbols (Upper or
lower case), digits ( 0 to 9), Underscore.
Example :- Cast = 10 => valid
Ca$h=10 => Invalid
2. Identifiers should not start with digits.
Example :- total123 = 10 => valid
123total=10 => Invalid
3. Python is case sensitive language.
Example :- total=10
TOTAL=10
Both variables are different
4. We cannot use keywords as Identifiers.
Example :- x=10 => Valid
def=20 => Invalid
if=15 => Invalid
5. Maximum allowed length in Identifiers :-
There is no length limit for python identifier. You can use any
number of characters.
Example :- abccccccccccc=10

6. Identifiers starts with _(underscore) then it is private.


7. Identifiers starts with __ ( double underscore ) then it is
strongly private.
8. We write Language specific identifiers as __Identifier__ (starts
and ends with double underscore)
Python Statement:

 Instructions that a Python interpreter can execute are called


statements.
For example, a = 1 is an assignment statement.

Multi-line statement:

In Python, end of a statement is marked by a newline character. But


we can make a statement extend over multiple lines with the line
continuation character (\).
For example:
a=1+2+3+\
4+5+6+\
7+8+9
Python Comments:
Comments are very important while writing a program.
It describes what's going on inside a program so that a person looking at the source code
does not have a hard time figuring it out.
# symbol to start writing a comment.
It extends up to the new line character.
 Comments are for programmers for better understanding of a program. Python
Interpreter ignores comment.
Example:
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, We can use triple quotes, either '''or """.
These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well.
Example
"""This is also a
Perfect example of
multi-line comments"""
Escape Characters:
An escape character is a special character that is preceded with a backslash
(\), appearing inside a string literal.
 When a string literal that contains escape characters is printed, the escape
characters are treated as special commands that are embedded in the string.
 Some of Python's escape characters
Escape Effect
Character
\n Causes output to be advanced to the next line.
\t Causes output to skip over to the next horizontal tab position.
\’ Causes a single quote mark to be printed.
\“ Causes a double quote mark to be printed.
\\ Causes a backslash character to be printed.
#Some example to write string using escape character.
A = "python is \"easy\" language "
B = 'python is "easy" language'
C = "python is 'easy' language "
D = '''python is 'easy' "programming " language '''
E = """python is 'easy' "programming " language """
print(A)
print(B)
print(C)
print(D)
print(E)
OUTPUT:
Python Variables:
A variable is a location in memory used to store some data(value).
The rules for writing a variable name is same as the rules for writing
identifiers in Python.
We don't need to declare a variable before using it.
In Python, we simply assign a value to a variable and it will exist.
We don't even have to declare the type of the variable.
This is handled internally according to the type of value we assign to the
variable.
Creating Variables syntax:
Syntax : Variable_name= value
Multiple Assignments Variables:
a,b,c,d,e,f=10,20,30,40,50,60
Example:
a=5
b = 3.2
c = "Hello“
Note: Every Variable in Python is a Object
Data types
A Data Type describes the characteristic of a variable.
Every value in Python has a data type. Since everything is an object
in Python programming, data types are actually classes and
variables are instance (object) of these classes.
There are various data types in Python.
The python data types are divided into 2 main types: 1.
Fundamental data types
2. Other Data types
Data types are listed below

A mutable object is an object whose state


can be modified after it is created. An
immutable object is an object whose state
cannot be modified after it is created.
1 int To represent whole number.
2 float To represent value with decimal point
3 complex To store complex values. (complex number: a+bj)
4 bool To represent logical values we use bool like True/False
5 str Collection of any sequence of character
6 bytes To store group of byte number like array. It is immutable
7 bytearray To store group of values like array. it is mutable
8 range Range data type represents sequence of values.
9 list To represent group of values where insertion order is preserved
and duplicates are allowed and it is mutable . []
10 tuple To represent group of values where insertion order is preserved
and duplicates are allowed and it is immutable. ()
11 set A groups of values as a single entity where insertion order not
preserved and duplicate values are not allowed and it is mutable.
{}
12 frozenset A groups of values as a single entity where insertion order not
preserved and duplicate values are not allowed and it is immutable
13 dict Dictionary is used to represent object as key and value pair Dict
data type is used. {}
14 None None means nothing.
integral value we represent value in 4 forms::
1. Decimal form:
2. Binary form
3. Octal form
4. Hexa form

Note: The result only display in decimal format


Base Conversions:

bin()
oct()
hexa()

Examples:
Complex data type examples:
bool data type examples:
Python provides some inbuilt functions :
1. print(): print the statement
ex: print(“hello”)
2. type( ):
It is used to identity the type of the object
Ex: a=10
print(“Type of a:”,type(a))
b=“Hello”
print(“Type of b:”, type(b))
c=[ ]
print(“Type of c:”,type(c))

Output: Type of a:<class ‘int'>


Type of b:<class ‘str’>
Type of c:<class ‘list’>
3. id (object):
 It returns identity of an object.
 It is the address of object in memory
 It will be unique and constant throughout the lifetime of an object
Ex: a=20
b=a
print (“value of a and b before incrementation”)
print(“id of a:”,id(a))
print(“id of b:”,id(b))
b=a+1
print(“Value of a and b after incrementation”)
print(“id of b: “ , id(b))
Operators:
 Operator is a symbol which is responsible to perform a specific
operation.
 The value that the operator operates on is called the operand.
 Operators are used to perform specific operations on one more
operands(variables) and provides a result

1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations
like addition, subtraction, multiplication etc.
Arithmetic operators in python
Operator Meaning Example

+ Add two operands or unary plus x+y


+2

- Subtract right operand from the left or unary minus x-y


-2

* Multiply two operands x*y

/ Divide left operand by the right one (always results x/y


into float)

% Modulus – remainder of the division of left operand x% y (remainder of x


by the right / y)

// Floor division – division that result into whole x // y


number adjusted to the left in the number line

** Exponent –left operand raised to the power of right x ** y (x to the power


of y)
Ex: x=15 Output
Y=4 x+y=19
Print(‘x+y=’,x+y) x-y=11
Print(‘x-y=’,x-y) x*y=60
Print(‘x*y=’,x*y) x/y=3.75
Print(‘x/y=’x/y) x||y=3
Print(‘x||y=’,x||y) x**y=50625
Print(‘x**y=’,x**y)
Logical operators:
Logical operators are the and, or, not operators. Based on Boolean
Algebra returns results as either True or False
Eg x=True Output

Y=False x and y is false

Print(‘x and y is’,x and y) x or y is true

Print(‘x or y is’,x or y) not x is false

Print(‘not x is ‘,not x)
Assignment operators:

 Assignment operators are used in Python to assign values to


variables. a = 5 is a simple assignment operator that assigns the
value 5 on the right to the variable a on the left.
 Multiple Assignments: Same value can be assigned to more than
one variable
Bitwise operators :
Bitwise operators converts the operands data in the form of binary
format performs operations on the binary values and gives the result in
the form of decimal format.
Operator Meaning
& bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift
<< Bitwise left shift
Ex: x=10 Output

Y=4 0

Print(x&y) 4

Print(x|y) -11

Print(x~y) 14

Print(x^y) 2

Print(x>>y) 40

Print(x<<y)
Special operators:
Python language offers some special type of operators like
1.membership operator.
2. identity operators

Membership operators:
 in and not in are the membership operators in Python.
 They are used to test whether a value or variable is found in a
sequence(string, list, tuple, set and dictionary).

Operator Description Example

in Returns to true if it finds a variable in 5 in x


given sequence else false
not in Returns to true if it does not find a 5 not in x
variable in given sequence else false
Identity Operators:

 is and is not are the identity operators in Python.


They are used to check if two values(or variables) are located on the
same part of the memory. [used to compare memory locations of
2objects]
 Two variables that are equal does not imply that they are identical.

Operator Description Example

is Returns to true if variable on either 5 in x


side of operator are referring to same
object else false
is not Returns to false if variable on either 5 not in x
side of operator e referring to same
Python Operators Precedence :
The following table lists all operators from highest precedence to
lowest.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
*/ % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Conditional Statements (if ,if- else ,Nested if-else):
 Generally Python Program execution starts from the first line,
executes each and every statement only once and stops the execution
of the program when control reached to the last line.
 These Statements are used to disturb the normal flow of execution of
the program.

Block:

 The set of statements which are following some space indentation is


known as a Block.
 Block begins when the indentation increases.
 Blocks can contain other Blocks.
 Blocks end when the indentation decreases to zero or to a containing
blocks indentation.
Python supports 3 types of conditional statements. They are
1. If
2. else
3. elif

1. if:
Condition returns true then it executes the if block otherwise if block
execution is skipped.

Syntax: if condition: statement (one statement)


Or
if condition :
Statement 1
Statement 2 (multiple statements)
--------------
EX:
Print (“begin”)
x = input (“enter a positive number”)
i= int(x)
if i<10:
print (“given number is 1 digit number”)
print (“end”)

Output 1: begin Output2: begin


enter a positive number5 enter a positive number120
Given number is 1 digit number end
end
2. else:
else block should be preceded by any one of the following blocks.
1.if 2.elif 3.while 4.for
else block preceding block condition returns false then only it will
execute the following else block.
Syntax:
if condition:
statement1
statement2
--------------
else:
statement1
statement2
--------------
Ex: print (“begin”)
x=input (“enter a positive number”)
i = int(x)
if x>10:
print (“Given number is 1 digit number”)
else:
print (“Given number is >=2 digit number”)
print (“end”)

output 1: output 2:
enter a positive number5 enter a positive number5
Given number is 1 digit number Given number is >=2 digit number
end end
3.elif:

 elif block should be preceded by either if block or another elif block.


elif block preceding block returns false then only control will go to
the elif block.
 After reaching the control block to the elif block, if condition returns
true then only it will execute elif block.
Ex: print (“begin”)
x = input(“enter a positive number”)
i = int(x)
if i<10:
print (“given number is 1 digit number”)
elif i<100:
print (“given number is 2 digit number”)
elif i<1000:
print (“given number is 3 digit number”)
else :
print(“given number is >=4 digit number”)
print (“end”)
Output1: Output2:
begin begin
enter a positive number5 enter a positive number15
given number is 1 digit number given number is 2 digit number
end end
Looping( for, while nested loops)

While:
 In python, while loop is used to execute a block of statements
repeatedly until a given a condition is satisfied.
 when the condition becomes false, the line immediately after the
loop in program is executed.

Ex: i =1 Output: 5050


sum =0
while i<=100:
sum = sum+i
i = i+1
print (“sum”)
Ex: Program for using while-else

print (“begin”) Output: begin


i =1 welcome
while i<=5: welcome
print (“welcome”) welcome
i=i+1 welcome
else: welcome
print (“in else”) in else
print (“end”) end
for:

for loop executes the given logic with respect to every element of the
iterable object

Syntax: for variable name in iterable object:


---------------------------
---------------------------
Ex

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for x in numbers:
print (x)
Control Statements(break , continue ,pass)

break :
 To interrupt the loop, to start a new iteration (one “round” of
executing the block), or to simply end the loop we use break.

EX:
print (“begin”)
i =1
while True:
print (“welcome”)
i =i+1
if i==5:
break
else:
print (“if else”)
print (“end”)
Continue:
 It causes the current iteration to end, and to “jump” to the
beginning of the next.
 It basically means “skip the rest of the loop body, but don’t end
the loop.”
EX
while True:
name = input("enter user name:")
if name!='Hema':
continue
password = input("Hello, Hema enter password")
if password=='hema':
break
print("access granted")
break
Pass:

In Python programming, pass  is a null statement.


The difference between a comment and pass statement in Python
is that, while the interpreter ignores a comment entirely, pass is not
ignored.
However, nothing happens when pass is executed. It results into
no operation (NOP).
Ex:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

You might also like