Ge3151 - Python - Unit 2
Ge3151 - Python - Unit 2
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.
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.
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 instruction as
Compiler Takes Entire program as input
input
No Intermediate Object Code
Intermediate Object Code is Generated
is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More (Since Object Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time
converted into lower-level program
Errors are displayed after Errors are displayed for every
entire program is checked instruction interpreted (if any)
Example: C Compiler Example: PYTHON
Advantages:
Drawback:
We cannot save the statements and have to retype all the statements once again tore-run
them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter
code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the
result is the words.
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.
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different
datatypes.)
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 integers, floating point numbers and complex numbers. They are
defined as,
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
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Creating a string >>> s="good morning" Creating the list with elements ofdifferent
data types.
Indexing >>>print(s[2]) Accessing the item in the position 0
o Accessing the item in theposition 2
>>>print(s[6])
o
Slicing ( ending >>> print(s[2:]) - Displaying items from 2nd till last.
position -1) od morning
Slice operator is >>> print(s[:4]) - Displaying items from 1st position till 3rd
used to extractpart Good
of a string.
2.2.2 Lists
List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square
brackets [ ].
Items in the lists can be of different data types.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
2.2.4Tuple:
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.
Basic Operations:
Creating a tuple >>>t=("python", 7.79 101 Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) Accessing the item in the
python position 0
>>> t[2] Accessing the item in the
101 position 2
Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>>t[0]=’a’
Trace back(most recent call last):
File “<stdin>”, line1, in <module>
Type Error: ‘tuple’ object does not support item assignment.
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
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 (also known as hashes). 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 unordered
key-value-pairs (The association of a key and a value is called a key-value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings,
tuples and lists.
If you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
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.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>> a,b,c=2,4,"ram"
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.
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 (Ato 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.
Example:
Names like myClass, var_1, and this_is_a_long_variable
COMMENTS:
DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method
definition. We must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname doc.
Example:
def double(num):
"""Function to double the value"""
return 2*num
>>> print(double. doc )
Function to double the value
Example:
-It is useful to swap the values of two variables. With conventional assignment
statements,we have to use a temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked’into the
variables/names on the right:
4.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
Consider theexpression4 + 5 = 9. Here,4 and 5 are called operands and + is
called operator
Types of Operators:
-Python language supports the following types of operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction,
multiplication etc. Assume, a=10 and b=5
- Subtraction Subtracts right hand operand from left hand a–b = -10
operand.
* Multiplies values on both side of the operator a * b = 200
Multiplication
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
Examples Output:
a=10 a+b= 15
b=5 a-b= 5
print("a+b=",a+b) a*b= 50
print("a-b=",a-b) a/b= 2.0
print("a*b=",a*b) a%b= 0
print("a/b=",a/b) a//b= 2
print("a%b=",a%b) a**b= 100000
print("a//b=",a//b)
print("a**b=",a**b)
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.
>= If the value of left operand is greater than or equal to the value (a >= b) is
of right operand, then condition becomes true. not true.
<= If the value of left operand is less than or equal to the value of (a <= b) is
right operand, then condition becomes true. true.
Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a<b=> False
print("a<b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a<=b=> False
print("a<=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
+= Add AND It adds right operand to the left operand and assign the c += a is
result to left operand equivalent
to c = c + a
/=Divide AND It divides left operand with the right operand and c /= a is
assign the result to left operand equivalent to
c = c / ac
Example Output
a = 21 Line 1 - Value of c is 31
b = 10 Line 2 - Value of c is 52
c=0 Line 3 - Value of c is 1092
c=a+b Line 4 - Value of c is 52.0
print("Line 1 - Value of c is ", c) Line 5 - Value of c is 2
c += a Line 6 - Value of c is 2097152
print("Line 2 - Value of c is ", c) Line 7 - Value of c is 99864
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c=2
c %= a
print("Line 5 - Value of c is ",
c) c **= a
print("Line 6 - Value of c is ",
c) c //= a
print("Line 7 - Value of c is ", c)
Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False x or y is True
print ('a and b is', a and b) not x is False
print ('a or b is', a or b)
print ('not a is', not a)
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of
individual bits
Example: Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line 3 - Value of c is 49
c = a & b; # 12 = 0000 1100 Line 4 - Value of c is -61
print "Line 1 - Value of c is ", c Line 5 - Value of c is 240
c = a b; # 61 = 0011 1101 Line 6 - Value of c is 15
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.
Let, x=[5,3,6,4,1].To check particular item in list or not, in and not in operators are
used.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators:
They are used to check if two values (or variables) are located on the same partof the
memory.
Example
x=5 Output
y=5 False
x2 = 'Hello' True
y2=’Hello’
print(x1 is not y1)
print(x2 is y2)
5. OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
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
Flow of Execution:
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.
Function Prototypes:
OUTPUT: OUTPUT:
enter a 5 enter a 5
enter b 10 enter b 10
15 15
Parameters And Arguments:
Parameters:
Parameters are the value(s) provided in the parenthesis when we write function header.
These are the values required by function to work.
If there is more than one value required, all of them will be listed in parameter
listseparated by comma.
Example: def my_add(a,b):
Arguments:
Arguments are the value(s) provided in function call/invoke statement.
List of arguments should be supplied in same way as parameters are listed.
Bounding of parameters to arguments is done 1:1, and so there should be same
number and type of arguments as mentioned in parameter list.
Example: my_add(x,y)
RETURN STATEMENT:
The return statement is used to exit a function and go back to the place from
whereit was called.
If the return statement has no arguments, then it will not return any values. But exits
from function.
Syntax:
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
ARGUMENTS TYPES:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
Required Arguments: The number of arguments in the function call shouldmatch
exactly with the function definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56
Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
Output:
Name: george
Age 56
Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40
Variable length Arguments
If we want to specify more arguments than specified while defining the function, variable
length arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal",
ärjun")
Output:
rajan rahul micheal ärjun
MODULES:
A module is a file containing Python definitions, functions, statements and
instructions.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the
module.
Once we import a module, we can reference or use to any of its functions or
variables in our code.
O There is large number of standard modules also available in python.
O Standard modules can be imported the same way as we import our user-
defined modules.
O Every module contains many function.
O To access one of the function , you have to specify the name of the module
and the name of the function separated by dot .This format is called dot
notation.
Syntax:
import module_name
module_name.function_name(variable)
ILLUSTRATIVE PROGRAMS
Program for SWAPPING (Exchanging ) of Output
alues
a = int(input("Enter a value ")) Enter a
b = int(input("Enter b value ")) value 5
c =a Enter b
a=b value 8
b=c a=8
print("a=",a,"b=",b,) b=5
31
Find greatest of three numbers utput
a=eval(input(“enter the value of a”)) enter the value of a 9
b=eval(input(“enter the value of b”)) enter the value of a 1
c=eval(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Programs on for loop
Print n natural numbers Output
print(i)
Print n odd numbers Output
for i in range(1,10,2):
13579
print(i)
for i in range(1,5,1): 1 4 9 16
print(i*i)
for i in range(1,5,1): 1 8 27 64
print(i*i*i)
Programs on while loop
Print n natural numbers Output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
5
Print n odd numbers Output
i=2 2
while(i<=10): 4
print(i) 6
i=i+2 8
10
Print n even numbers Output
i=1 1
while(i<=10): 3
print(i) 5
i=i+2 7
9
Print n squares of numbers Output
i=1 1
while(i<=5): 4
print(i*i) 9
i=i+1 16
25
34
check the no divisible by 5 or not Output
def div(): enter n value10
n=eval(input("enter n value")) the number is divisible by5
if(n%5==0):
print("the number is divisible by 5")
else:
print("the number not divisible by 5")
div()
35
program for basic calculator Output
def add(): enter a value 10
a=eval(input("enter a value")) enter b value 10
b=eval(input("enter b value")) the sum is 20
c=a+b enter a value 10
print("the sum is",c) enter b value 10
def sub(): the diff is 0
a=eval(input("enter a value")) enter a value 10
b=eval(input("enter b value")) enter b value 10
c=a-b the mul is 100
print("the diff is",c) enter a value 10
def mul(): enter b value 10
a=eval(input("enter a value")) the div is 1
b=eval(input("enter b value"))
c=a*b
print("the mul is",c)
def div():
a=eval(input("enter a value"))
b=eval(input("enter b value"))
c=a/b
print("the div is",c)
add()
sub()
mul()
div()
Debugging
Programming is error –prone, programming errors are called bugs and process of
tracking them is called debugging.Three kinds of error can occur in a program:
o Syntax Error o Runtime Error o Semantic error.
Syntax error:
Syntax refers to the structure of a program and rules about the structure. Python can only
execute a program if the syntax is correct otherwise the interpreter displays an error message.
Runtime Error:
The error that occurs during the program execution is called run time error.
Semantic Error:
The computer will not generate any error message but it will not do the right thing since
the meaning of the program is wrong.