CA-205 (B) Python Programming
CA-205 (B) Python Programming
CA-205 (B) Python Programming
Unit-I
The Python Programming: - Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − you can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, Smalltalk, and
UNIX shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License
(GPL).
Python is now maintained by a core development team at the institute, although Guido van Rossum still holds
a vital role in directing its progress.
Features:-Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on
UNIX, Windows, and Macintosh.
1
Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Extendable − you can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
Application:-Python is known for its general-purpose nature that makes it applicable in almost every domain of
software development. Python makes its presence in every emerging field. It is the fastest-growing programming
language and can develop any application. Here, we are specifying application areas where Python can be applied.
2
Variables: - Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or
characters in these variables.
Assigning Values to Variables:-
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator
is the value stored in the variable.
For example −
Live Demo
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This
produces the following result −
100
1000.0
John
Multiple Assignment: -
Python allows you to assign a single value to several variables simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables.
3
For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string
object with the value "john" is assigned to the variable c.
Identifier/Identifier Naming: - A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more
letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive
programming language. Thus, Manpower and manpower are two different identifiers in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
Data Types: - The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the storage method for each of them.
List
Tup
le
Dictionary
Numbers: -
Number data types store numeric values. Number objects are created when you assign a value to them. For
example
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is
4
−
del var1[,var2[,var3[ ................. ,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
long (long integers, they can also be represented in octal and hexadecimal) float
(floating point real values)
Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase
L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ]
and [:]) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −
Live Demo
5
This will produce the following result –
HelloWorld!
llo
llo World!
Lists: -
Lists are the most versatile of Python's compound data types. A list contains items separated by commas and
enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between
them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator,
and the asterisk (*) is the repetition operator. For example −
Live Demo
6
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Tuples: -
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and
size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be
thought of as read-only lists. For example −
Live Demo
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar
case is possible with lists −
7
Dictionary: -
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in
Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces
([]). For example –
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they
are simply unordered.
Comments in Python: - A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the end of the physical line are part of the comment and the Python interpreter ignores them.
8
Live Demo
You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment
A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.
The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits
for the user to take action −
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the
program ends. This is a nice trick to keep a console window open until the user is done with an application.
9
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code
block. Here is a sample snip using the semicolon −
Keywords: - The following list shows the Python keywords. These are reserved words and you cannot use them
as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
assert finally or
def if return
elif in while
else is with
Literals: - Literals in Python is defined as the raw data assigned to variables or constants while programming.
We mainly have five types of literals which includes string literals, numeric literals, boolean literals, literal
collections and a special literal None.
Type conversion: - Sometimes, you may need to perform conversions between the built-in types. To convert between
types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These functions return a
new object representing the converted value.
1
int(x [,base])
10
2
long(x [,base] )
3
float(x)
4
complex(real [,imag])
5
str(x)
6
repr(x)
7
eval(str)
8
tuple(s)
Converts s to a tuple.
9
list(s)
Converts s to a list.
10
set(s)
Converts s to a set.
11
dict(d)
12
frozenset(s)
11
13
chr(x)
14
unichr(x)
15
ord(x)
16
hex(x)
17
oct(x)
Operators and its types: - 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 operator.
Types of Operator: -
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership
Operators Identity
Operators
Let us have a look on all operators one by one.
Python Arithmetic Operators: -
12
- Subtraction Subtracts right hand operand from left hand a – b = -10
operand.
// Floor Division - The division of operands where 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 =
the result is the quotient in which the digits after -4, -11.0//3 = -4.0
the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative
infinity) −
These operators compare the values on either sides of them and decide the relation among them. They are also called
Relational operators.
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
<> If values of two operands are not equal, then (a <> b) is true. This is similar to !=
condition becomes true. operator.
> If the value of left operand is greater than the (a > b) is not true.
value of right operand, then condition becomes
true.
13
< If the value of left operand is less than the value of (a < b) is true.
right operand, then condition becomes true.
>= If the value of left operand is greater than or equal (a >= b) is not true.
to the value of right operand, then condition
becomes true.
<= If the value of left operand is less than or equal (a <= b) is true.
to the value of right operand, then condition
becomes true.
/= Divide AND It divides left operand with the right operand and
assign the result to left operand c /= a is equivalent to c = c / a
14
Python Bitwise Operators: -
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary
format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators
supported by Python language with an example each in those, we use the above two variables (a and b) as
operands −
a = 0011 1100
b = 0000 1101
~a = 1100 0011
<< Binary Left The left operands value is moved left by the
Shift number of bits specified by the right operand. a << 2 = 240 (means 1111 0000)
15
Python Logical Operators: -
There are following logical operators supported by Python language. Assume variable a holds 10 and variable b
holds 20 then
and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.
not Logical Used to reverse the logical state of its operand. Not(a and b) is false.
NOT
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two
membership operators as explained below −
not in Evaluates to true if it does not finds a variable in x not in y, here not in results in a 1 if x is not a
the specified sequence and false otherwise. member of sequence y.
Identity operators compare the memory locations of two objects. There are two Identity operators explained below −
1
**
2
~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3
* / % //
4
+-
5
>> <<
6
&
Bitwise 'AND'
7
^|
8
<= < > >=
Comparison operators
9
<> == !=
Equality operators
17
10
= %= /= //= -= += *= **=
Assignment operators
11
is is not
Identity operators
12
in not in
Membership operators
13
not or and
Logical operators
Expressions: - In Python, operators are special symbols that designate that some sort of computation should be
performed. The values that an operator acts on are called operands. A sequence of operands and operators, like
a + b – 5 is called an expression. Python supports many operators for combining data objects into expressions.
Scope of Variables: - All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are
two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope.
This means that local variables can be accessed only inside the function in which they are declared,
whereas global variables can be accessed throughout the program body by all functions. When you call a function,
the variables declared inside it are brought into scope. Following is a simple example −
18
Live Demo
Functions: - A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own
functions. These functions are called user-defined functions.
Defining a Function: -You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses (
( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function or
docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A
return statement with no arguments is the same as return None.
19
Syntax
def functionname(parameters):
"function_docstring" function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were
defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
Calling a Function: -
Defining a function only gives it a name, specifies the parameters that are to be included in the function and
structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly
from the Python prompt. Following is the example to call printme() function −
Live Demo
20
When the above code is executed, it produces the following result −
I'm first call to user defined function!
All parameters (arguments) in the Python language are passed by reference. It means if you change what a
parameter refers to within a function, the change also reflects back in the calling function. For example −
Live Demo
Here, we are maintaining reference of the passed object and appending values in the same object. So, this would
produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
21
There is one more example where argument is being passed by reference and the reference is being
overwritten inside the called function.
Live Demo
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect
mylist. The function accomplishes nothing and finally this would produce the following result −
Types of Arguments: -
Formal arguments: When a function is defined it (may) has (have) some parameters within the parentheses.
These parameters, which receive the values sent from the function call, are called formal arguments.
Actual arguments: The parameters which we use in the function call or the parameters which we use to send the
values/data during the function call are called actual arguments.
You can call a function by using the following types of formal arguments –
Required arguments
Keyword arguments
Default arguments
22
Variable-length arguments
Required arguments: -
Required arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as
follows −
Live Demo
Default Arguments: - A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument. The following example gives an idea on default arguments, it prints default age if it
is not passed −
23
Live Demo
Variable-length Arguments: - You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
function_suite
return [expression]
24
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments.
This tuple remains empty if no additional arguments are specified during the function call. Following is a simple
example −
Live Demo
10
Output is:
70
60
50
Keyword Arguments: - Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters. You can also make keyword calls to the printme()
function in the following ways −
25
Live Demo
My string
The following example gives clearer picture. Note that the order of parameters does not matter.
Live Demo
26
Built-in Functions: -
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters
with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
27
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
28
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators
Decision Making: -
if statement: -
a = 20; b = 20
if ( a == b ):
Output:
a and b are equal
If block ended
if-else statement: -
number1 = 20 ; number2 = 30
if(number1 >= number2 ):
print(“number 1 is greater than number 2”)
else:
print(“number 2 is greater than number 1”)
Output:
number 2 is greater than number 1
if-elif statement: -
print(“1. Bike”)
print(“2. Car”)
29
print(“3. SUV”)
if( choice == 1 ):
elif( choice == 2 ):
elif( choice == 3 ):
else:
print(“Wrong choice!“)
Output 1:
1. Bike
2. Car
3. SUV
Chained conditionals: -
Chained conditionals are simply a "chain" or a combination or multiple conditions. We can combine
conditions using the following three key words:
- and
- or
- not
30
Loops:
For loop: -
For loop in Python is used to iterate over a sequence of items like list, tuple, set, dictionary, string or
any other iterable objects.
Syntax
for item in sequence:
body of for loop
The Python for loop doesn’t need indexing unlike other programming languages (C/C++ or Java). It
works like an iterator and the item variable will contain an item from the sequence at each iteration.
print( item)
Output:
1
2
3
4
While loop: -
Syntax
while( condition):
Body of while
31
Code:
count = 0
print(count)
count = count + 2
Output:
0
2
4
6
8
break: -
The break statement inside a loop is used to exit out of the loop. Sometimes in a program, we need
to exit the loop when a certain condition is fulfilled.
Code:
num = 0
num +=1
32
if(num==5): break
print( num )
print("Loop ended")
Output:
1
2
3
4
Loop ended
continue: -
The continue statement is used to skip the next statements in the loop.
When the program reaches the continue statement, the
program skips the statements after continue and the flow reaches the next iteration of the loop.
Let’s take the same example –
Code:
num = 0
num +=1
if(num==5): continue
print( num )
33
print("Loop ended")
Output:
1
2
3
4
6
7
8
9
10
Loop ended
pass: -
The pass is a null statement and the Python interpreter returns a no-operation (NOP) after reading the
pass statement. Nothing happens when the pass statement is executed. It is used as a placeholder
when implementing new methods or we can use them in exception handling.
Code:
nums = [1,2,3,4]
for num in nums:
pass
print(nums)
Using else with for loop: -
In Python programming, the loops can also have an else part which will be executed once when the
loop terminates.
Code:
for i in [1, 2, 3, 4]:
print(i)
else:
print(“The loop ended”)
Output:
1
2
3
4
34
The loop ended
Using else with while loop
The while loop may also have an else part after the loop. It is executed only when the condition of
while loop becomes false. But if we break out of the loop before the condition has not reached false,
then the else block does not get executed.
Code:
num = 0
while( num<10 ):
print(num)
num += 1
if( num==5):
break
else:
print('Loop ended')
Output:
0
1
2
3
4
---------------------------------------------------**----------------------------------------------------------
Lines and Indentation: -
Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. For example −
if True:
print "True"
else:
print "False"
Multi-Line Statements: -
35
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue.
For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character.
For example −
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python: -
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are
legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Multiple Statement Groups as Suites: -
A group of individual statements, which make a single code block are called suites in Python.
Compound or complex statements, such as if, while, def, and class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed
by one or more lines which make up the suite.
For example −
if expression :
suite
elif expression :
suite
else :
suite
36