Unit 1 - Python Programming - Notes
Unit 1 - Python Programming - Notes
1. Introduction to python:
Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. It was created by Guido van Rossum
during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000.
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.
1.1. Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The
structure of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So,
there is no need to compile a program before executing it. You can
simply run the program.
Extensible: Programmers can embed python within their C,C++,Java
script
,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source
code, and edit it.
High Level Language: When writing programs, programmers
concentrate on solutions of the current problem, no need to worry
about the low level details.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
1.2. Applications:
Bit Torrent file sharing
Google search engine, youtube
Intel, Cisco, HP, IBM
i–Robot
NASA
Facebook, Drop box
1.3. Python interpreter:
Interpreter: To execute a program in a high-level language by translating
it one line at a time.
Compiler: To translate a program written in a high-level language into a
low-level language all at once, in preparation for later execution.
Compiler Interpreter
Interpreter Takes Single
Compiler Takes Entire program as
instruction as
input
input
No Object Cod
Intermediate Object Code is Generated Intermediate is
e
Generated
Conditional Control Statements Conditional Statemen are
are Executes faster ts
Control Executes
slower
Memory Requirement is More(Since
Memory Requirement is Less
Object Code is Generated)
Every time higher level
Program need not be compiled every
program is
time
converted into lower level
program
Errors are displayed after Errors are displayed for every
entire instruction interpreted (if any)
program is checked
Example : C Compiler Example : PYTHON
Advantages:
Python, in interactive mode, is good enough to learn, experiment or
explore.
Working in interactive mode is convenient for beginners and for
testing small pieces of code
Drawback:
We cannot save the statements and have to retype all the
statements once again to re-run them.
In interactive mode, you type Python programs and the interpreter
displays the result:
Script mode:
In script mode, we type python program in a file and then use
interpreter to execute the content of the file.
Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with .py
Save the code with filename.py and run the interpreter in script
mode to execute the script.
Interactive mode Script mode
A way of using the Python A way of using the Python
interpreter by typing commands interpreter to read and execute
and expressions at the statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
If we want to experiment with the If we are very clear about the code,
code, we can use interactive mode. we can use script mode.
we cannot save the statements for we can save the statements for
further use and we have to retype further use and we no need to
all the statements to re-run them. retype
all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
Values:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
data types.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those
values. Python has four standard data types:
Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports following number types
1. integers
2. floating point numbers
3. Complex numbers.
2.1 integer:
Integers are the whole numbers consisting of +ve or –ve sign.
Example:
a=10
a=eval(input(“enter a
value”))
a=int(input(“enter a
value”))
2.2 Float:
it has decimal part and fractional part.
Example:
a=3.15
a=eval(input(“enter a
value”))
a=float(input(“enter a
value”))
2.3. Complex:
It is a combination of real and imaginary part.
Example:
2+5j
a+bi
Sequence:
A sequence is an ordered collection of items, indexed by positive
integers.
It is a combination of mutable (value can be changed) and immutable
(values cannot be changed) data types.
There are three types of sequence data type available in Python, they
are
1. Strings
2. Lists
3. Tuples
2.4. Strings:
String is defined as a continues set of characters represented in
quotation marks (either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a subscript
(index).
The subscript should always be an integer (positive or negative).
A subscript starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be
changed after it is created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can
be treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
create a list >>> a=[2,3,4,5,6,7,8,9,10] in this way we can
>>> print(a) create a list at compile
[2, 3, 4, 5, 6, 7, 8, 9, 10] time
Indexing >>> Accessing the item in
print(a[0]) 2 the position 0
>>> Accessing the item in
print(a[8]) 10 the position 8
>>> print(a[-1]) Accessing a last
10 element
using negative indexing.
Slicing >>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:]) printing a part of the
[2, 3, 4, 5, 6, 7, 8, 9, 10] string.
>>>
print(a[:8]) [2,
3, 4, 5, 6, 7, 8,
9]
>>>b=[20,30] Adding and printing
Concatenation >>> print(a+b) the items of two
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, lists.
30]
>>> print(b*3) Create a multiple
Repetition [20, 30, 20, 30, 20, 30] copies of the same
string
>>>
print(a[2]) 4 Updating the list
Updating the list >>> a[2]=100 using index
>>> print(a) value
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Inserting an >>> a. insert(0,"apple") Inserting an element in
element >>> print(a) 0th position
a=[“apple”,2,3,4,5,6,7,8,9,10]
Removing an >>> a. remove(“apple”) Removing an
element >>> print(a) element
a=[2,3,4,5,6,7,8,9,10] by giving the
element directly
2.6. Tuple:
A tuple is same as list, except that the set of elements is enclosed in
parentheses
instead of square brackets.
A tuple is an immutable list. i.e. once a tuple has been created, you
can't add elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple
can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
Creating the tuple
Creating a tuple >>>a=(20,40,60,”apple”,”bal with elements
l”) of different data
types.
>>>print(a[0]) Accessing the item in
Indexing 20 the position 0
>>> a[2] Accessing the item in
60 the
position 2
Slicing >>>print(a[1: Displaying items from
3]) (40,60) 1st till 2nd.
Concatenation >>> b=(2,4) Adding tuple elements
>>>print(a+b) at the end of another
>>>(20,40,60,”apple”,”ball”, tuple elements
2,4)
Repetition >>>print(b*2) repeating the tuple in n
>>>(2,4,2,4) no of times
updating a tuple >>>a[2]=100 Altering the tuple data
Type Error: 'tuple' object type leads to error.
does not support item
assignment
2.7. Boolean:
Boolean data type have two values either it can take 0 or 1.
0 means False
1 means True
True and False is a keyword.
Example:
>>> 3==5
False
>>>
True+True 2
>>>
False+True 1
>>>
False*True 0
2.8. Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered
sets.
Dictionary is created by using curly brackets. i,e. { }
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array. Any key of the dictionary is
associated (or mapped) to a value.
The values of a dictionary can be any Python data type. So
dictionaries are key- value-pairs
Dictionaries don't support the sequence operation of the sequence
data types like strings, tuples and lists.
2.9. Sets:
Set is an unordered collection of values of any data type with no
duplicate entry.
In set every element is unique.
Elements are separated by”,” enclosed with { }
Example:
a={1,2,3,4,5,6,7,6,7}
print(a)
a={1,2,3,4,5,6
,7}
3. VARIABLES:
A variable allows us to store a value by assigning it to a name,
which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are
meaningful.
It can be of any length. No space is allowed.
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.
Example:
a=5 // single assignment
a,b,c=2,3,4 // multiple
assignment
a=b=c=2 //assigning one value to multiple variables
4. KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name
or any other identifier.
They are used to define the syntax and structure of the Python
language.
Keywords are case sensitive.
5. IDENTIFIERS:
Identifier is the name given to entities like class, functions,
variables etc. 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 (_).
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like !, @, #, $, % etc. in our identifier.
Identifier can be of any length.
6. STATEMENTS
Instructions that a Python interpreter can executes are called
statements.
A statement is a unit of code like creating a variable or displaying a
value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.
There are two types of statements available
1. single line statements
2. multi line statements
Single line statements:
single line statements are end with newline
Examples:
a=1
b=2
c=a+
b
Multiline statements:
python allows the user to write multi line statement using line
continuation character (\) to denote that the line should continue.
Example:
total=mark1+\
mark2
+\
mark3
7. INPUT AND
OUTPUT INPUT:
Input is a data entered by user in the program.
In python, input () function is available for input.
Syntax:
variable = input (“data”)
Example:
a=input("enter the name:")
OUTPUT:
Output can be displayed to the user using Print statement.
Syntax:
print (expression/constant/variable)
Example:
print ("Hello") //
Hello print(5) //5
print(3+5) //8
Print(c)
8. COMMENTS:
Comments are used to provide more details about the program like
name of the program, author of the program, date and time, etc.
Types of comments:
1. single line comments
2. multi line comments
Example:
“”” This program is created by
Robert in Dell lab on
12/12/12
based on newtons method”””
Example:
a=
3
b=
1
if a>b:
print("a is
greater") else:
print("b is greater")
11. OPERATORS:
Operators are the constructs which can manipulate the value of
operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands
and + is called
Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Operator Description Example
a=10,b=20
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Operator Description Example
Logical Operators:
Logical operators are and, or, not operators.
Bitwise Operators:
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of
string, list, tuple, dictionary or not.
Identity Operators:
They are used to check if two values (or variables) are located on the same
part of the memory.
Example
x=5
y=5
a=
'Hello' b
=
'Hello'
print(x is not y) //
False print(a is
b)//True
Operator Precedence:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
12. Expressions:
>>> 42
42
>>> a=2
>>>
a+3+2 7
>>> z=("hi"+"friend")
>>>
print(z)
hifriend
a=9-12/3+3*2-1 A=2*3+4%5-
a=? 3/2+6 find m=?
A=6+4%5-
3/2+6
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+ m=1
a=10 6
A=15
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1
PART A
1. What is interpreter?
2. What are the two modes of python?
3. List the features of python.
4. List the applications of python
5. List the difference between interactive and script mode
6. What is value in python?
7. What is identifier? and list the rules to name identifier.
8. What is keyword?
9. How to get data types in compile time and runtime?
10.What is indexing and types of indexing?
11.List out the operations on strings.
12.Explain slicing?
13.Explain below operations with the
example (i)Concatenation
(ii)Repetition
14.Give the difference between list and tuple
15.Differentiate Membership and Identity operators.
16.Compose the importance of indentation in python.
17.Evaluate the expression and find
the result (a+b)*c/d
a+b*c/d
18.Write a python program to print ‘n’ numbers.
19.Give the various data types in Python
20.Assess a program to assign and access variables.
21.Select and assign how an input operation was done in python.
22.Discover the difference between logical and bitwise operator.
23.Give the reserved words in Python.
24.Give the operator precedence in python.
25.Point out the uses of default arguments in python
25. Give the syntax for variable length arguments.
Part B
1. Explain in detail various data types in Python with an example.
2. Explain the different types of operators in python with an example.
3. Discuss the need and importance of function in python.
4. Explain in detail function prototypes in python.
5. Discuss the various type of arguments in python.
6. Explain the flow of execution in a user-defined function with an example.
7.Illustrate a program to display different data types using variables
and literal constants.
8. Explain in detail the various operators in python with suitable
examples.
9. Discuss the difference between tuples and list
10.Discuss the various operation that can be performed on a
tuple and Lists (minimum 5) with an example program
11.What are membership and identity operators?
12.Write a program to perform addition, subtraction,
multiplication, integer division, floor division and modulo
division on two integers and float.
13.Write a program to convert degrees Fahrenheit to Celsius
14.Discuss the need and importance of function in python.
15.Illustrate a program to exchange the value of two variables
with temporary variables
16.Analyze the difference between local and global variables.
17.Explain with an example program to circulate the values of n
variables
18.Analyze with a program to find out the distance between two points
using python.
19.Do the Case study and perform the following operation in tuples i)
Maxima minima iii) sum of two tuples iv) duplicate a tuple v) slicing
operator vi) obtaining a list from a tuple vii) Compare two tuples
viii) Printing two tuples of different data types