Introduction to Python Programming
Introduction to Python Programming
MODULE I
SYLLABUS
Module I: Introduction to Python - Features of Python - Identifiers - Reserved Keywords - Variables
Comments in Python – Input , Output and Import Functions - Operators – Data Types and Operations –
int, float, complex, Strings, List, Tuple, Set, Dictionary - Mutable and Immutable Objects – Data Type
Conversion
INTRODUCTION TO PYTHON
Python was developed by Guido van Rossum at the National Research Institute for Mathematics
and Computer Science in Netherlands during 1985-1990. Python is derived from many other languages,
including ABC, Modula-3, C, C++, Algol-68, SmallTalk, Unix shell and other scripting languages.
Rossum was inspired by Monty Python's Flying Circus, a BBC Comedy series and he wanted the name of
his new language to be short, unique and mysterious. Hence he named it Python. It is a general-purpose
interpreted, interactive, object-oriented, and high-level programming language. Python source code is
available under the GNU General Public License (GPL) and it is now maintained by a core development
team at the National Research Institute.
FEATURES OF PYTHON
a) Simple and easy-to-learn - Python is a simple language with few keywords, simple structure and
its syntax is also clearly defined. This makes Python a beginner's language.
b) Interpreted and Interactive - Python is processed at runtime by the interpreter. We need not
compile the program before executing it. The Python prompt interact with the interpreter to
interpret the programs that we have written. Python has an option namely interactive mode which
allows interactive testing and debugging of code.
c) Object-Oriented - Python supports Object Oriented Programming (OOP) concepts that
encapsulate code within objects. All concepts in OOPs like data hiding, operator overloading,
inheritance etc. can be well written in Python. It supports functional as well as structured
programming.
d) Portable - Python can run on a wide variety of hardware and software platforms , and
has the same interface on all platforms. All variants of Windows, Unix, Linux and
Macintosh are to name a few.
e) Scalable - Python provides a better structure and support for large programs than shell
scripting. It can be used as a scripting language or can be compiled to bytecode (intermediate
code that is platform independent) for building large applications.
f) 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. It can be easily integrated
with C, C++, COM, ActiveX, CORBA, and Java.
g) Dynamic - Python provides very high-level dynamic data types and supports dynamic type
checking. It also supports automatic garbage collection.
h) GUI Programming and Databases - Python supports GUI applications that can created
and ported to many libraries and windows systems, such as Windows Microsoft
Foundation Classes (MFC), Macintosh, and the X Window system of Unix. Python also
provides interfaces to all major commercial databases.
1
CS1543: PYTHON PROGRAMMING Module 1
i) Broad Standard Library - Python's library is portable and cross platform compatible, on
UNIX, Linux, Windows and Macintosh. This helps in the support and development of a wide
range of applications from simple text processing to browsers and complex games.
You can start Python from Unix, DOS, or any other system that provides you
command-line interpreter or shell window. Get into the command line of Python. For Unix
/Linux, you can get into interactive mode by typing $ python or python%.
For Windows/Dos it is c. >pyt ho n.
Invoking the interpreter without passing a script file as a parameter brings up the following
prompt.
$ p yt hon
Type the following text at the Python prompt and press the Enter: >>>
print("Programming in Python!")
Programming in Python!
>>>
b)Script from the Command Line
This method invokes the interpreter with a script parameter which begins the execution of
the script and continues until the script is finished. When the script is finished, the interpreter is
no longer active. A Python script can be executed at command line by invoking the interpreter on
your application, as follows.
For Unix/Linux it is $python script .pyor python% script . py. For Windows/ Dos it is c : >pyt ho n scr ip t .py
Let us write a simple Python program in a script. Python files have extension .py. Type the following
source code in a first . py file.
print("Programming in Python!")
Now, try to run this program as follows.
$ p yt h o n f i r s t . p y
Programming in Python!
2
CS1543: PYTHON PROGRAMMING Module 1
c) Integrated Development Environment
You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI
application on your system that supports Python. IDLE is the Integrated Development Environment (IDE)
for UNIX and PythonWin is the first Windows interface for Python.
IDENTIFIERS
A Python identifier is a name used to identify a variable, function, class, module or any other
object. Python is case sensitive and hence uppercase and lowercase letters are considered distinct. The
following are the rules for naming an identifier in Python.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Eg: Person
Starting an identifier with a single leading underscore indicates that the identifier is private.
Eg: _sum
Starting an identifier with two leading underscores indicates a strongly private
identifier. Eg: _sum
If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name. foo__
RESERVED KEYWORDS
These are keywords reserved by programming language and prevent the user or the
programmer from using it as an identifier in a program. There are 33 keywords in python.
This number can vary with different versions. To retrieve the keywords in python the
following code can be given at the prompt. All keywords except True, False and None are in
lowercase. The following list in Table 1.1 shows the python keywords.
>>> print([Link])
3
CS1543: PYTHON PROGRAMMING Module 1
[ ‘False’, ‘None’, ‘True’, 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global', ' if', 'import', 'in', 'is', 'lambda', ’nonlocal’,
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
VARIABLES
Variables are reserved memory locations to store values. 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.
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.
Example Program
print(a)
print(b)
print(name)
Here, 100, 1000.0 and "John" are the values assigned to a, b, and name variable respectively.
This produces the following result.
100
1000.0
John
4
CS1543: PYTHON PROGRAMMING Module 1
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. For example,
a,b,c=1,2,”Tom”
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "Tom" is assigned to the variable c.
COMMENTS IN PYTHON
Comments are very important while writing a program. It describes what the source code has
done. Comments are for programmers for better understanding of a program. In Python, we use the
hash (#) symbol to start writing a comment. 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. It
extends up to the newline character. Python interpreter ignores comment.
Example Program
>»#Display Hello
>»print("Hello")
For multiline comments one way is to use (#) symbol at the beginning of each line. The following
example shows a multiline comment. Another way of doing this is to use triple quotes, either '" or """.
Example 1
>>>#Three lines
Example 2
5
CS1543: PYTHON PROGRAMMING Module 1
INDENTATION IN PYTHON
Most of the programming languages like C, C++ and Java use braces { } to define a block of code.
Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and ends
with the first unindented line. The amount of indentation can be decided by the programmer, but it must
be consistent throughout the block. Generally four whitespaces are used for indentation and is preferred
over tabspace. For example
if True:
print("Correct”)
else:
print("Wrong”)
But the following block generates error as indentation is not properly followed.
if True:
print("Answer")
print("Correct")
else:
print("Answer")
print("Wrong")
MULTI-LINE STATEMENTS
Instructions that a Python interpreter can execute are called statements. For example a=1 is an
assignment statement. if statement, for statement, while statement etc. are other kinds of statements.
In Python, end of a statement. is marked by a newline character. But we can make a statement extend
over multiple line with the line continuation character(\). For example:
second item + \
third item
Statements contained within the [],{ }or () brackets do not need to use the lin e
We could also put multiple statements in a single line using semicolons, as follows a = 1 ; b
= 2; c = 3
6
CS1543: PYTHON PROGRAMMING Module 1
MULTIPLE STATEMENT GROUP (SUITE)
A group of individual statements, which make a single code block is called a suite Python.
Compound or complex statements, such as if, while, def, and class require a head line and a suite.
Header lines begin the statement (with the keyword) and terminate with
colon ( : ) and are followed by one or more lines which make up the suite. For example if
expression :
suite
elif expression
suite
else :
suite
QUOTES IN PYTHON
Python accepts single (‘), double (") and triple ("' or “””) quotes to denote string literals. The same type
of quote should be used to start and end the string. The triple quotes, are used to span the string across
multiple lines. For example, all the following are legal.
The function used to print output on a screen is the print statement where you can pass zero or
more expressions separated by commas. The print function converts the expressions you pass into a
string and writes the result to standard output.
Example 1
7
CS1543: PYTHON PROGRAMMING Module 1
Example 2
›››a=2
›››print ( "The value of a is" , a)
The value of a is 2
By default a space is added after the text and before the value of variable a. The syntax of print
function is given below.
Here, objects are the values to be printed. Sep is the separator used between the values. Space
character is the default separator. end is printed after printing all the values. The default value for
end is the new line. file is the object where the values are printed and its default value is sys .
stdout (screen). Flush determines whether the output stream needs to be flushed for any waiting
output. A True value forcibly flushes the stream. The following shows an example for the above
syntax.
Example
>>>print(1,2,3,4)
>>>print(1,2,3,4,sep= ‘+')
1234
1+2+3+4
1+2+3+4%
The output can also be formatted to make it attractive according to the wish of a user.
8
CS1543: PYTHON PROGRAMMING Module 1
Example
Output
E nt e r yo ur na me : C o l l i n
M a r k Yo u r na me is : Co l l i n
Mark
input function
The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a
valid Python expression and returns the evaluated result to you.
Example 1
Output
E nt e r a nu mb e r : 5
T h e nu mb e r is : 5
Example 2
n = i np u t ( " E nt e r a n e xp r e s s io n: " ) ;
p r i n t ( " T h e r e s u l t i s : “, eval(n))
Output
E nt e r a n e xp re ssio n : 5* 2
T he r e su lt is : 10
Import function
When the program grows bigger or when there are segments of code that is frequently used, it can
be stored in different modules. A module is a file containing Python definitions and statements. Python
modules have a filename and end with the extension .py. Definitions inside a module can be imported to
another module or the interactive interpreter in Python. We use the import keyword to do this. For
example, we can import the math module by typing in import math.
9
CS1543: PYTHON PROGRAMMING Module 1
>>> import math
>>> print([Link] )
3.141592653589793
OPERATORS
Operators are the constructs which can manipulate the value of operands. Consider the expression a =
b + c. Here a, b and c are called the operands and +, = , are called the operators. There are different types
of operators. The following are the types of operators supported by Python.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Arithmetic operators are used for performing basic arithmetic operations. The following are the arithmetic operators
supported by Python. Table 1.2 shows the arithmetic operators in Python.
Example Program
a, b, c = 10, 5, 2
print("Sum.",(a+b))
print("Difference=",(a-b))
10
CS1543: PYTHON PROGRAMMING Module 1
p r i nt ( " P r o d u c t =” , ( a * b) )
print ( "Quotient=”,(a/b) )
Output
Sum= 15
Difference= 5
pro duct = 50
Quo t ie nt = 2
Remainder= 1
E xpo nent = 25
F lo o r D i v is io n= 2
Comparison operators
These operators compare values on either sides of them and decide the relation among them. They are also
called relational operators. Python supports the following relational operators. Python supports the
following relational operators. Table 1.3 shows the comparison or relational operators in python.
Operator Description
== If the values of two operands are equal, then the condition becomes true.
!= If the values of two operands are not equal, then the condition becomes true.
> If the value of left operand is greater than the value of right operand, then the condition
becomes true.
< If the value of left operand is less than the value of right operand, then the condition
becomes true.
>= If the value of left operand is greater than or equal to the value of right operand, then the
condition becomes true.
<= If the value of left operand is less than or equal to the value of right operand, then the
condition becomes true.
Example Program
a, b=10,5
output
Assignment Operators
Python provides various assignment operators. Various shorthand operators for addition,
subtraction, multiplication, division, modulus, exponent and floor division are also supported by Python.
Table 1.4 provides the various assignment operators.
Operator Description
*= It multiplies right operand with the left operand and assign the result to left operand.
/= It divides left operand with the right operand and assign the result to left operand.
%= It takes modulus using two operands and assign the result to left operand.
**= Performs exponential (power) calculation on operators and assign value to the left
operand.
//= It performs floor division on operators and assign value to the left operand.
The assignment operator = is used to assign values or values of expressions to a variable. Example:
a = b+ c. For example c+=a is equivalent to c=c+a. Similarly c-=a is equivalent to c=c-a, c*=a is
equivalent to c=c*a, c/=a is equivalent to c=c/a, c%=a is equivalent to c=c%a, c**=a is equivalent to
c=c**a and c//=a is equivalent to c=c//a.
12
CS1543: PYTHON PROGRAMMING Module 1
Example Program
a, b=10, 5
a+=b
print(a)
a, b =10,5
a- =b
print(a)
a, b =10,5
a*=b
print(a)
a, b =10,5
a/=b
print(a)
b, c = 5, 2
b%=c
print(b)
b, c = 5, 2
b**=c
print(b)
b, c = 5, 2
b//=c
print(b)
output
15
50
13
CS1543: PYTHON PROGRAMMING Module 1
25
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. The following are the bit wise operators
supported by python. Table 1.5 gives a description of bitwise operators in python.
» Binary Right The left operand's value is moved right by the number of bits specified by
Shift the right operand.
Example Program
a, b = 60, 2
print(a&b)
print(a|b)
print(a^b)
print(~a)
print(a>>b)
print(a<<b)
output
62
14
CS1543: PYTHON PROGRAMMING Module 1
62
-61
15
240
b=0000 0010
Logical Operators
Table 1.6 shows the various logical operators supported by Python language.
and Logical AND If both the operands are true then condition becomes true.
or Logical OR If any of the operands are true then condition becomes true.
not Logical NOT Used to reverse the logical state of its operand.
Example Program
a, b, c, d=10, 5, 2, 1
Output
True
True
False
Membership operators
Python’s membership operators test for membership in a sequence, such as strings, lists or tuples. There are
two membership operators.
15
CS1543: PYTHON PROGRAMMING Module 1
Table 1.7 shows the various membership operators supported by Python language.
Operator Description
Example Program
s=’abcde’
print(‘a’ in s)
print(‘f’ in s)
print(‘f’ not in s)
Output
True
False
True
Identity Operators
Identity operators compare the memory locations of two objects. There are two identity operators as given
below.
Operator Description
is It is evaluated to be true if the variables present on either sides of the operator point
to the same object and false otherwise.
is not It is evaluated to be false if the variables on either side of the operator point to the
same object and true otherwise.
Example Program
a,b,c=10,10,5
print(a is b)
print(a is c)
16
CS1543: PYTHON PROGRAMMING Module 1
print(a is not b)
Output
True
False
False
Operator Precedence
The following table lists all operators from highest precedence to lowest precedence. Operator
associativity determines the order of evaluation, when they are of the same precedence, and are not
grouped by parenthesis. An operator may be left-associative or right associative. In left associative, the
operator falling on the left side will be evaluated first, while in right- associative, operator falling on the
right will be evaluated first. In Python, ‘=’ and ‘**’ are right associative while all other operators are
left associative. The precedence of the operators is important to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in python is given below.
Operator Description
** The exponent operator is given priority over all the others used in the expression.
~, +, - The negation(complement), unary plus and minus.
*, /, %, // The multiplication, divide, modules, reminder, and floor division.
+, - Binary plus and minus
>>, << Left shift and right shift
& Binary AND
^, | Binary XOR and OR
<=, < >, >= Comparison operators (less then, less then equal to, greater then, greater then
equal to).
<>, == ,!= Equality operators.
= ,%= ,/= ,//= Assignment operators
,-= ,+=
*= **=
is, is not Identity operators
in ,not in Membership operators
not , or and Logical operators
Numbers.
String
17
CS1543: PYTHON PROGRAMMING Module 1
List ·
Tuple
Set
Dictionary
NUMBERS
Number data types store numeric values. Number objects are created when you assign a value to them. For
example a = 1, b = 20. You can also delete the reference to a number object by using the del statement.
The syntax of the del statement is as follows.
You can delete a single object or multiple objects by using the del statement. For example
del a
del a,b
Python supports four different numerical types.
Integers can be of any length, it is only limited by the memory available. A floating point number is
accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is
integer, 1.0 is floating point number. Complex numbers are written in the form, x + yj , where x is the
real part and y is the imaginary part.
Example Program
Output
a=1
b= 1.5
c= 231456987
d= (2+9j)
Mathematical Functions
Python provides various built-in mathematical functions to perform mathematical calculations. The
following Table 2.1 provides various mathematical functions and its purpose. For using the below
18
CS1543: PYTHON PROGRAMMING Module 1
functions, all functions except abs(x), max(x1,x2,... xn), min(x1,x2,...xn), round(x[n]) and pow(x,y)
need to import the math module because these functions reside in the math module. The math module
also defines two mathematical constants pi and e.
Function Description
abs(x) Returns the absolute value of x.
sqrt(x) Finds the square root of x.
ceil(x) Finds the smallest integer not less than x.
floor(x) Finds the largest integer not greater than x
pow(x,y) Finds x raised to y
exp(x) Returns ex ie exponential of x.
fabs(x) Returns the absolute value of x.
log(x) Finds the natural logarithm of x for x>0.
log10(x) Finds the logarithm to the base 10 for x0.
max(x1,x2,...xn) Returns the largest of its arguments
min(x1,x2, ... xn) Returns the smallest of its arguments
round(x,[n]) In case of decimal numbers, x will be rounded to n digits.
modf(x) Returns the integer and decimal part as a tuple. The integer
part is returned as a decimal
Example Program
import math
print("Absolute value of -120:", abs (-120))
print("Square root of 25:", [Link] (25))
print("Ceiling of 12.2:", [Link](12.2))
print("Floor of 12.2:", [Link] (12.2))
print("2 raised to 3:", pow (2,3))
print("Exponential of 3:", [Link] (3))
print("Absolute value of -123:", [Link] (-123))
print("Natural Logarithm of 2:", [Link](2))
print("Logarithm to the Base 10 of 2:", math.log10 (2))
print("Largest among 10, 4, 2:", max (10,4,2))
print("Smallest among 10,4, 2:",min(10,4,2))
print("12.6789 rounded to 2 decimal places:", round (12.6789,2))
print("Decimal part and integer part of 12.090876:", [Link]
(12.090876))
Output
19
CS1543: PYTHON PROGRAMMING Module 1
Ceiling of 12.2: 13
Floor of 12.2: 12
2 raised to 3: 8
Exponential of 3: 20.085536923187668
Absolute value of -123: 123.0
Natural Logarithm of 2: 0.69314 71805599453
Logarithm to the Base 10 of 2: 0.3010299956639812
Largest among 10, 4, 2: 10
Smallest among 10,4, 2: 2
12.6789 rounded to 2 decimal places: 12.68
Decimal part and integer part of 12.090876: (0.09087599999999973,
12.0)
Trigonometric Functions
There are several built in trigonometric functions in Python. The function names and its purpose are
listed in Table 2.2
Function Description
sin(x) Returns the sine of x radians
cos(x) Returns the cosine of x radians
tan(x) Returns the tangent of x radians
asin(x) Returns the arc sine of x, in radians.
acos(x) Returns the arc cosine of x, in radians.
atan(x) Returns the arc tangent of x, in radians.
atan2(y,x) Returns atan(y/x ), in radians
hypot(y) Returns the Euclidean form, sqrt(x*x + y*y)
degrees(x) Converts angle x from radians to degrees
radians() Converts angle x from degrees to radians
Example Program
import math
print("Sin (90):", [Link](90))
print("Cos (90):", [Link](90))
print("Tan (90):", math. tan(90))
print("asin(1):", [Link](1))
print("acos (1):", [Link] (1))
print("atan(l):",[Link](1))
print("atan2 (3,2):",math.atan2 (3,2))
print("Hypotenuse of 3 and 4:", [Link] (3,4))
print("Degrees of 90:", math. degrees (90))
20
CS1543: PYTHON PROGRAMMING Module 1
print("Radians of 90: , [Link] (90))
Output
Sin(90): 0.893996663601
Cos (90): -0.448073616129
Tan (90): -1.99520041221
asin(l): 1.57079632679
acos (1): 0.0
atan(1): 0.785398163397
atan2 (3,2): 0.992793723247
Hypotenuse of 3 and 4: 5.0
Degrees of 90: 5156.62015618
Radians of 90: 1.57079632679
There are several random number functions supported by Python. Random numbers have applications
in research games, cryptography, simulation and other applications. Table 2.3 shows the commonly
used random number functions in Python. For using the random number functions, we need to import
the module random because all these functions reside in the random module.
Function Description
choice (sequence) Returns a random value from a sequence like list, tuple, string etc
shuttle(list) Shuttles the items randomly in a list. Returns none.
random() Returns a random floating point number which lies between 0 and i
randrange([start,] Returns a randomly selected number from a range where start shows the
stop[,step]) starting of the range, stop shows the end of the range and step decides the
number to be added to decide a random number
seed([x]) Gives the starting value for generating a random number. Returns none.
This function is called before calling any other random module function.
uniform(xy) Generates a random floating point number n such that n>x and n<y
Example Program
import random
S=’abcde'
print("choice (abcde):", [Link](s))
list = [10,2,3,1, 8, 19]
print("shuffle (list):", [Link](list))
print ("[Link](20):", [Link](20))
print("random():", [Link]())
21
CS1543: PYTHON PROGRAMMING Module 1
print("uniform (2,3):", [Link](2,3))
print("randrange (2,10,1):", [Link] (2,10,1))
Output
choice(abcde): b
shuffle (list): None
[Link] (20): None
random(): 0.905639676175
uniform (2,3): 2.68625415703
randrange (2,10,1): 8
STRINGS
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 ending at -1. The plus
(+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. The %
operator is used for string formatting.
Example Program
Escape Characters
An escape character is a character that gets interpreted when placed in single or double quotes. They
are represented using backslash notation. These characters are non printable. The following Table 2.4
shows the most commonly used escape characters and their description.
22
CS1543: PYTHON PROGRAMMING Module 1
This operator is unique to strings and is similar to the formatting operations of the printf() function of the
C programming language. The following Table 2.5 shows various format symbols and their conversion.
23
CS1543: PYTHON PROGRAMMING Module 1
print("%x is the hexadecimal equivalent of %d" %(10,10)) #usage of %X
print("%e is the exponential equivalent of %f"
(10.98765432,10.98765432)) #usage of %e and %f
print("%E is the exponential equivalent of %f"
(10.98765432,10.98765432)) #usage of %E and %f
print ( “%.2f”, %(32.1274)) #usage of %f for printing upto two decimal
places
Output
The first letter of apple is a
The sum=-12
The sum=-12
The sum-12
10 is the octal octal equivalent of 8
a is the hexadecimal equivalent of 10
2. lower() - Returns a copy of the string in which all uppercase alphabets in a string are converted to
lowercase alphabets.
Example Program
#Demo of lower()
S='Learning Python is fun!’
print([Link]())
Output
learning python is fun!
24
CS1543: PYTHON PROGRAMMING Module 1
[Link]() - Returns a copy of the string in which all lowercase alphabets in a string are converted to
uppercase alphabets.
Example Program
#Demo of upper()
S='Learning Python is fun!’
print([Link]())
Output
LEARNING PYTHON IS PUN !
4. Swapcase() - Returns a copy of the string in which the case of all the alphabets are swapped. ie. all the
lowercase alphabets are converted to uppercase and vice versa.
Example Program
#Demo of swapcase ()
S="LEARNing PYTHON is fun!”
print([Link]())
Output
learnING Python IS FUN!
5. capitalize() - Returns a copy of the string with only its first character capitalized.
Example Program
#Demo of capitalize()
s=' learning Python is fun!’
print([Link]())
Output
Learning python is fun!
[Link]()- Returns a copy of the string in which first character of all the words are capitalized
Example Program
#Demo of title()
s=’ learning Python is fun!’
print([Link]())
Output
Learning Python Is Fun!
[Link]() - Returns a copy of the string in which all the characters have been stripped(removed) from the
beginning. The default character is whitespaces.
Example Program
#Demo of lstrip()
25
CS1543: PYTHON PROGRAMMING Module 1
s=’ learning Python is fun!'
print([Link]())
s=’*********learning Python is fun!'
print([Link] (**))
Output
learning Python is fun!
learning Python is fun!
8. rstrip()- Returns a copy of the string in which all the characters have been stripped(removed) from the
right end. The default character is whitespaces.
Example Program
#Demo of rstrip
S='learning Python is fun! ’
print([Link]())
S='learning Python is fun! ******’
print([Link]('*'))
Output
learning Python is fun!
learning Python is fun!
9. strip()- Returns a copy of the string in which all the characters have been stripped(removed) from the
beginning and end. It performs both lstrip() and rstrip (). The default character is whitespaces.
Example Program
#Demo of strip()
s=' learning Python is fun!’
print([Link]())
s='******learning Python is fun! ******’
print([Link] ('*'))
Output
learning Python is fun!
learning Python is fun!
Example Program
#Demo of max(str)
s=’learning Python is fun!’
print("Maximum character is , max(s))
Output
Maximum character is : y
26
CS1543: PYTHON PROGRAMMING Module 1
11. min(str) - Returns the minimum alphabetical character from string str
Example Program
#Demo of min(str)
s=' learning-Python-is-fun’
print("Minimum character is :', min(s))
Output
Minimum character is : -
12. replace(old, new [,max] )- Returns a copy of the string with all the occurrences of substring old is
replaced by new. The max is optional and if it is specified, the first occurrences specified in max are
replaced.
Example Program
# Demo of replace (old, new [,max])
s="This is very new. This is good”
print([Link]('is', 'was'))
print([Link]('is', 'was', 2))
Output
Thwas was very new. Thwas was good
Thwas was very new. This is good
13. center(width, fillchar) - Returns a string centered in a length specified in the width variable. Padding
is done using the character specified in the fillchar. Default padding is space.
Example Program
# Demo of center (width, fillchar)
s="This is Python Programming"
print([Link] (30, '*'))
print([Link] (30)
Output
**This is Python Programming**
This is Python Programming
14. ljust(width[,fillchar]) - Returns a string left-justified in a length specified in the width variable.
Padding is done using the character specified in the fillchar. Default padding is space.
Example Program
# Demo of ljust (width[, fillchar))
s="This is Python Programming"
print(s. ljust (30,'*'))
print([Link] (30))
Output
This is Python Programming ****
This is Python Programming
27
CS1543: PYTHON PROGRAMMING Module 1
15. rjust(width[,fillchar]) - Returns a string right-justified in a length specified in the width variable.
Padding is done using the character specified in the fillchar. Default padding is space.
Example Program
# Demo of rjust (width[, fillchar])
s="This is Python Programming"
print([Link] (30, *'))
print([Link] (30))
Output
****This is Python Programming
This is Python Programming
16. zfill(width) - The method zfill() pads string on the left with zeros to fill width.
Example Program
# Demo of zfill(width)
S="This is Python Programming"
print([Link](30))
Output
0000 This is Python Programming
17. count(str,beg=0,end=len(string)) - Returns the number of occurrences of str in the range beg and end.
Example Program
# Demo of count (str, beg=0, end=len(string))
S="This is Python Programming"
print([Link]('i', 0,10))
print([Link]('i', 0,25))
Output
18. find(str, beg=0,end=len(string)) - Returns the index of str if str occurs in the range beg and end and
returns -1 if it is not found.
Example Program
# Demo of find (str, beg=0, end=len(string) )
S="This is Python Programming"
print([Link]('thon', 0,25))
print([Link]('thy))
Output
10
-1
28
CS1543: PYTHON PROGRAMMING Module 1
Example Program
# Demo of rfind (str, beg=0, end=len(string))
S="This is Python Programming"
print([Link]('thon',0,25))
print([Link]('thy'))
Output
10
-1
20. index(str, beg=0,end=len(string)) - Same as that of find but raises an exception if the item is not
found
Example Program
# Demo of index (str, beg=0, end=len (string))
S="This is Python Programming"
print([Link] ('thon', 0,25))
print([Link] ('thy'))
Output
10
Traceback (most zecent call last):
File "[Link]", line 4, in <module>
print s. index ('thy')
ValueError: substring not found
Example Program
# Demo of rindex (str, beg=0, end=len (string))
S="This is Python Programming"
print([Link] ('thon', 0,25))
print([Link] ('thy'))
Output
10
Traceback (most recent call last):
File "[Link]", line 4, in <module>
print [Link] ('thy')
ValueError: substring not found
22. startswith(suffix, beg=0,end=len(string))- It returns True if the string begins with the specified
suffix, otherwise return false.
29
CS1543: PYTHON PROGRAMMING Module 1
Example Program
# Demo of start with(suffix, beg=0, end=len (string))
s=”Python programming is fun”
print([Link]('is', 10, 21))
s="Python programming is fun"
print([Link]('is',19,25))
Output
False
True
23. endswith(suffix, beg=0,end=len(string))- It returns True if the string ends with the specified suffix,
otherwise return false.
Example Program
# Demo of endswith(suffix, beg=0, end=len(string)
S="Python programming is fun"
print([Link]('is',10,21))
S="Python programming is fun"
print([Link]('is', 0,25))
Output
True
False
24. isdecimal() - Returns True if a unicode string contains only decimal characters and False otherwise.
To define a string as unicode string, prefix 'u' to the front of the quotation marks.
Example Program
# Demo of isdecimal()
S="This is Python 1234"
print([Link]())
s=u"123456"
print([Link]())
Output
False
True
25. Isalpha() - Returns True if string has at least 1 character and all characters are alphabetic and False
otherwise.
Example Program
# Demo of isalpha()
s="This is Python1234"
print([Link]())
S="Python"
print([Link]())
30
CS1543: PYTHON PROGRAMMING Module 1
Output
False
True
26. isalnum()- Returns True if string has at least 1 character and all characters are alphanumeric and False
otherwise.
Example Program
# Demo of isalnum ()
S=”**** Python1234"
print([Link]())
S=”Python1234"
print([Link]())
Output
False
True
[Link]()- Returns True if string contains only digits and False otherwise
Example Program
# Demo of isdigit()
S*****Python1234"
print([Link]())
S="123456"
print(s. isdigit())
Output
False
True
28. islower() - Returns True if string has at least 1 cased character and all cased characters are in
lowercase and False otherwise.
Example Program
# Demo of islower)
S="Python Programming"
print([Link]())
s="python programming"
print([Link]())
Output
False
True
[Link]() - Returns True if string has at least one cased character and all cased characters are in
uppercase and False otherwise.
Example Program
# Demo of isupper()
31
CS1543: PYTHON PROGRAMMING Module 1
S="Python Programming
print([Link]())
S="PYTHON PROGRAMMING
print([Link]())
Output
False
True
30. isnumeric()- Returns True if a unicode string contains only numeric characters and False otherwise.
Example Program
# Demo of isnumeric()
s="Python Programming1234"
print([Link]())
s="12345"
print([Link]())
Output
False
True
31. isspace() - Returns True if string contains only whitespace characters and False otherwise.
Example Program
# Demo of isspace()
s="Python Programming"
print([Link]())
s=“ “
print ([Link]())
Output
False
True
32. istitle() - Returns True if string is properly "titlecased" and False otherwise. Title case means each
word in a sentence begins with uppercase letter.
Example Program
#Demo of istitle()
$="Python programming is fun"
print([Link]())
S="Python Programming Is Fun"
print([Link]())
Output
False
True
32
CS1543: PYTHON PROGRAMMING Module 1
33. expandtabs(tabsize=8) - It returns a copy of the string in which tab characters ie.'\t are expanded
using spaces using the given tabsize. The default tabsize is 8.
Example Program
[Link](seq) - Returns a string in which the string elements of sequence have been joined by a separator.
Example Program
# Demo of join(seg)
s=”-“
seq= ("Python", "Programming")
print([Link](seq))
s="*”
seq= ("Python", "Programming")
print([Link](seq))
Output
Python-Programming
Python*Programming
35. split(str="", num=[Link](str)) - Returns a list of all the words in the string, using str as the
separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
Example Program
#Demo of split(str="", num=[Link] (str))
S="Python programming is fun"
print([Link](‘ ‘))
s="Python*programming*is*fun"
print([Link]('*'))
s=”Python*programming*is*fun"
print([Link]('*’,2))
Output
[‘Python', 'programming', 'is', 'fun’ ]
[‘Python', 'programming', 'is', 'fun']
['Python', 'programming', 'is*fun']
36. Splitlines(num=[Link]('\n') - Splits string at all (or num) NEWLINEs and returns a list of each
line with NEWLINEs removed. If num is specified, it is assumed that line breaks need to be included in
the lines.
33
CS1543: PYTHON PROGRAMMING Module 1
Example Program
#Demo of splitlines (num=[Link]('\n')
S="Python\nprogramming\nis\nfun“
print([Link]())
print([Link] (0))
print([Link] (1) )
Output
LIST
List is an ordered sequence of items. It is one of the most used data type in Python and is very flexible. All
the items in a list do not need to be of the same type. Items separated by commas are enclosed within
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 indices starting at 0 in the beginning of the list and ending with -1. The
plus (+) sign is the list concatenation operator and the asterisk (*) is the repetition operator.
Example Program
first_list = ['abcd', 147, 2.43, 'Tom', 74.9]
small_list = [111,'Tom']
We can update lists by using the slice on the left hand side of the assignment operator.
Updates can be done on single or multiple elements in a list.
Example Program
#Demo of List Update
34
CS1543: PYTHON PROGRAMMING Module 1
list = ['abcd', 147, 2.43,'Tom', 74.9]
print("Item at position 2", list[2] )
list[2]=500
print("Item at position 2", list[2])
print("Item at Position 0 and 1 is", list [0],list[1])
list[0]=20; list[1] ='apple'
Output
Item at position 2= 2.43
Item at position 2=500
Item at Position 0 and 1 is abcd 147
Item at Position 0 and 1 is 20 apple
To remove an item from a list, there are two methods. We can use del statement or remove() method.
Example Program
*Demo of List Deletion
list = ['abcd', 147, 2.43, 'Tom', 74.9]
print (list)
del list [2]
print("List after deletion:", list)
Output
['abcd', 147, 2.43. Tom]
List after deletion: ['abcd', 147, 'Tom', 74.9]
Example Program
#Demo of len(list)
list1=['abcd', 147, 2.43, 'Tom']
print(len(list1))
Output
Example Program
#Demo of max (list)
list1= [1200, 147, 2.43, 1.12]
list2 = [213, 100, 289]
print("Maximum value in: ", list1, "is", max(list1))
print("Maximum value in: , list2, "is", max(list2))
Output
35
CS1543: PYTHON PROGRAMMING Module 1
Maximum value in: [1200, 147, 2.43, 1.12] is 1200
Maximum value in: [213, 100, 289] is 289
Example Program
#Demo of min(list)
list1=[1200, 147, 2.43, 1.12]
list2 = [213, 100, 289]
5. map(aFunctionaSequence)-One of the common things we do with list and other sequences is applying
an operation to each item and collect the result. The map(aFunction, aSequence) function applies a passed-
in function to each item in an iterable object and returns a list containing all the function call results.
Example Program
str=input("Enter a list (space separated) :")
lis=list (map (int, [Link]()))
print(lis)
Output
Enter a list (space separated) : 1 2 3 4
[1, 2, 3, 4]
In the above example, a string is read from the keyboard and each item is converted into int using
map(aFunction, aSequence) function.
Example Program
#Demo of [Link](obj)
list = ['abcd', 147, 2.43, 'Tom']
36
CS1543: PYTHON PROGRAMMING Module 1
print("old List before Append:", list)
[Link](100)
print("New List after Append :", list)
Output
old List before Append: ['abcd', 147, 2.43, 'Tom']
New List after Append: ["abcd', 147, 2.43, 'Tom', 100]
2. [Link](obj) - Returns how many times the object obj appears in a list:
Example Program
#Demo of [Link] (obj)
List = ['abcd', 147, 2.43, 'Tom', 147,200, 147]
Example Program
#Demo of [Link](obj)
list1 = ['abcd', 147, 2.43, 'Tom']
[Link]( 'Tom')
print (list1)
Output
['abcd', 147, 2.43]
4. [Link](obj) - Returns index of the object obj if found, otherwise raise an exception indicating that
value does not exist.
Example Program
#Demo of [Link] (obj)
list1 = ['abcd', 147, 2.43, 'Tom']
print ([Link] (2.43))
Output
Example Program
#Demo of [Link](seg)
list1 = ['abcd', 147, 2.43,’Tom']
37
CS1543: PYTHON PROGRAMMING Module 1
list2 = ['def', 100]
[Link](list2)
print(list1)
Output
Example Program
#Demo of [Link]()
listl = ['abcd', 147, 2.43, 'Tom']
[Link]()
print(list1)
Output
7. [Link](index,obj) - Returns a list with object obj inserted at the given index
Example Program
#Demo of [Link] lindex, obj)
8. [Link]([Key=None, Reverse=False]) - Sorts the items in a list and returns the list. If a function is
provided, it will compare using the function provided.
Example Program
#Demo of [Link] ( [Key=None, Reverse=Falsel)
list1=[890, 147, 2.43, 100]
print("List before sorting:", list1)
[Link]()
print("List after sorting in ascending order:", list1)
Output
List before sorting: [840, 147, 2.43, 100]
List after sorting in ascending order: [2.43, 100, 147,840]
The following example illustrates how to sort the list in descending order.
38
CS1543: PYTHON PROGRAMMING Module 1
Example Program
9. [Link]([index]) - Removes or returns the last object obj from a list. We can even pop out any item in a
list with the index specified.
Example Program
#Demo of [Link]([index])
list1= ['abcd', 147, 2.43, 'Tom']
print("List before poping", list1)
[Link](-1)
print("List after poping :", list1)
item=[Link](-3)
print("Popped item: ", item)
print("List after poping:", list1)
Output
List before poping ['abcd', 147, 2.43, 'Tom']
List after poping: ['abcd', 147, 2.43]
Example Program
#Demo of [Link]()
list1 = ['abcd', 147, 2.43, 'Tom']
print("List before clearing:", list1)
[Link]()
print("List after clearing:", list1)
Output
List before clearing: ['abcd', 147, 2.43, 'Tom']
Example Program
#Demo of [Link] ()
list1 = ['abcd', 147, 2.43, Tom']
39
CS1543: PYTHON PROGRAMMING Module 1
print("List before clearing:", list1)
list2=[Link] ()
[Link]()
print("List after clearing:", list1)
print("Copy of the list:", list2)
Output
List before clearing: ['abcd', 147, 2.43, 'Tom']
List after clearing: [ ]
Copy of the list: ['abcd', 147, 2.43, 'Tom']
Example Program
#Demo of List as Stack
stack=[10,20,30,40,50]
[Link](60)
print ("Stack after appending:", stack)
[Link]()
print("Stack after poping:" , stack)
Output
Stack after appending: [10, 20, 30, 40, 50, 60]
Stack after poping: [10, 20, 30, 40, 50 ]
It is also possible to use a list as a queue, where the first element added is the first element retrieved.
Queues are First In First Out (FIFO) data structure. But lists are not efficient for this purpose. While
appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow
since all of the other elements have to be shifted by one.
To implement a queue, Python provides a module called collections in which a method called deque is
designed to have fast appends and pops from both ends.
Example Program
#Demo of List as Queue
from collections import deque
queue = deque (["apple", "orange", "pear"])
queue. append("cherry") # cherry arrives
[Link]( "grapes") # grapes arrives
[Link]() # The first to arrive now leaves
[Link]() # The second to arrive now leaves
print (queue) # Remaining queue in order of arrival
40
CS1543: PYTHON PROGRAMMING Module 1
Output
deque (['pear', 'cherry', 'grapes'])
TUPLE
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. The main differences between lists and tuples are lists are enclosed in square
brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be considered as read-only lists.
Example Program
first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9)
small_tuple = (111, 'Tom')
print(first_tuple) # Prints complete tuple
print(first_tuple[0]) # Prints first element of the tuple
print(first tuple[1:3]) # Prints elements starting from 2nd till 3rd
print(first_tuple[2:]) # Prints elements starting from 3rd element
print(small_tuple * 2) # Prints tuple two times
print(first_tuple + small tuple) # Prints concatenated tuples
Output
('abcd', 147, 2.43, Tom', 74.9)
abcd
(147, 2.43)
(2.43, 'Tom', 74.9)
(111, Tom', 111, 'Tom')
('abcd', 147, 2.43, Tom'. 74.9, 111, 'Tom')
The following code is invalid with tuple whereas this is possible with lists
first_list =['abcd', 147, 2.43,'Tom', 74.9]
first_tuple = ('abcd', 147, 2.43, 'Tom', 74.9)
first_tuple [2] = 100 # Invalid syntax with tuple
first_list [2] = 100 # Valid syntax with list
To delete an entire tuple we can use the del statement. Example del tuple. It is not possible to remove
individual items from a tuple. However it is possible to create tuples which contain mutable objects, such
as lists.
Example Program
#Demo of Tuple containing Lists
t=([1,2,3],['apple', 'pear', 'orange'])
print(t)
Output
([1, 2, 3], ['apple', 'pear', 'orange'])
41
CS1543: PYTHON PROGRAMMING Module 1
It is possible to pack values to a tuple and unpack values from a tuple. We can create tuples even without
parenthesis. The reverse operation is called sequence unpacking and works for any sequence on the right-
hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign
as there are elements in the sequence.
Example Program
#Demo of Tuple packing and unpacking
t="apple",1, 100
print (t)
x, y, z= t
print(x)
print(y)
print(2)
Output
('apple', 1, 100)
apple
1
100
Example Program
#Demo of len (tuple)
tuplel = ('abcd', 147, 2.43, 'Tom')
print(len(tuplel))
Output
4
Example Program
#Demo of min (tuple)
42
CS1543: PYTHON PROGRAMMING Module 1
tuplel = (1200, 147, 2.43, 1.12)
tuple2 = (213, 100, 289)
print("Minimum value in: ", tuplel, "is", min(tuple1))
print("Minimum value in: ", tuple2, "is", min(tuple2))
Output
Minimum value in: (1200, 147, 2.43, 1.12) is 1.12
Minimum value in: (213, 100, 289) is 100
Example Program
#Demo of tuple (seg)
list = ['abcd', 147, 2.43, Tom']
print("Tuple:", tuple(list))
Output
SET
Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces
{ }. It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
Items in a set are not ordered. Since they are unordered we cannot access or change an element of set
using indexing or slicing. We can perform set operations like union, intersection, difference on two sets.
Set have unique values. They eliminate duplicates. The slicing operator [ ] does not work with sets. An
empty set is created by the function set( ).
Example Program
# Demo of Set Creation
sl={1,2,3} #set of integer numbers
print (s1)
{ 1, 2, 3}
{1, 3, 2.4, "apple', 'Tom' }
{1, 2, 3, 4}
43
CS1543: PYTHON PROGRAMMING Module 1
Built-in Set Functions
1. len(set) - Returns the length or total number of items in a set.
Example Program
#Demo of len(set)
set1= {'abcd', 147, 2.43, 'Tom'}
print(len (set1))
Output
Example Program
#Demo of max (set)
set1 ={1200, 147, 2.43, 1.12} .
set2 = {213, 100, 289}
print ("Maximum value in: ", set1, "is", max (set1))
print("Maximum value in: ", set2, "is", max(set 2))
Output
Maximum value in: {1200, 1.12, 2.43, 147} is 1200
Maximum value in: {289, 100, 213} is 289
Example Program
#Demo of min(set)
set1 = {1200, 147, 2.43,1.12}
set2 = {213, 100, 289}
print("Minimum value in: ", set1, "is", min(set1))
print ("Minimum value in: ", set2, "is", min(set2))
Output
Minimum value in: {1200, 1.12, 2.43, 147} is 1.12
Minimum value in: {289, 100, 213} is 100
Example Program
#Demo of sum(set)
set1={147, 2.43}
set2 = {213, 100, 289}
print("Sum of elements in", set1, "is", sum(set1))
print("Sum of elements in", set2,"is", sum(set2))
44
CS1543: PYTHON PROGRAMMING Module 1
Output
Sum of elements in {147, 2.43} is 149.43
Sum of elements in {289, 100, 213) is 602
[Link](set)- Returns a new sorted list. The set does not sort itself.
Example Program
#Demo of sorted (set)
set1= {213, 100, 289, 40, 23,1, 1000}
set2 = sorted (set1)
print("Sum of elements before sorting:”,set1)
print("Sum of elements after sorting:", set 2)
Output
Sum of elements before sorting:{1, 100, 289, 1000, 40, 213, 23}
Sum of elements after sorting: [1, 23, 40, 100, 213, 289, 1000]
[Link](set) - Returns an enumerate object. It contains the index and value of all the items of set as a
pair.
Example Program
#Demo of enumerate (set)
set1 = {213, 100, 289, 40, 23, 1, 1000}
print ("enumerate (set):” enumerate (set1))
Output
enumerate (set): <enumerate object at 0x7f0a73573690>
7. any(set) - Returns True, if the set contains at least one item, False otherwise.
Example Program
#Demo of any (set)
set1 = set( )
set2={1,2,3,4}
print("any (set):", any (set 1))
print("any (set):", any (set 2))
Output
any (set): False
any (set) : True
8. all(set) - Returns True, if all the elements are true or the set is empty.
Example Program
#Demo of all(set)
setl =set()
set 2={1,2,3,4}
print("all(set):", all(set1))
45
CS1543: PYTHON PROGRAMMING Module 1
print("all(set):", all (set1))
Output
all (set) : True
all (set) : True
Example Program
#Demo of [Link](obj)
set1={3, 8, 2, 6}
print("Set before addition:", set 1)
[Link] (9)
print("Set after addition:", set1)
Output
Set before addition:{8, 2, 3, 6}
Set after addition:{8, 9, 2, 3, 6}
2. [Link](obj) - Removes an element obj from the set. Raises KeyError if the set is empty
Example Program
#Demo of [Link](obj)
set1={3,8,2,6}
print("Set before deletion:", set1)
[Link](8)
print("Set after deletion:", set1)
Output
Set before deletion:{8, 2, 3, 6}
Set after deletion:{2, 3, 6}
3. set discard(obj) - Removes an element obj from the set. Nothing happens if the element to be deleted is
not in the set.
Example Program
#Demo of set. discard (obj)
setl={3, 8, 2, 6}
print("Set before discard:, set1)
[Link](8)
print("Set after discard:",setl) # Element is present
[Link](9)
print("Set after discard:", setl) #element is not present
Output
Set before discard: {8, 2, 3, 6}
Set after discard: {2, 3, 6}
46
CS1543: PYTHON PROGRAMMING Module 1
4 [Link]() - Removes and returns an arbitrary set element. Raises KeyError if the set is empty.
Example Program
#Demo of [Link]()
set1={3, 8, 2, 6}
print("Set before pop:", set1)
[Link]()
print("Set after poping:", set1)
Output
Set before pop:{8, 2, 3, 6}
Set after poping: {2, 3, 6}
Example Program
#Demo of [Link](set2)
setl={3, 8, 2,6}
print("Set 1:", set1)
set2={4,2,1,9}
print("Set 2:", set2)
set3=[Link](set 2) #unique values will be taken
print("Union:", set3)
Output
Set1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Union:{1, 2, 3, 4, 6, 8, 9}
6. [Link](set2) - Update a set with the union of itself and others. The result will be stored in set1.
Example Program
#Demo of [Link] (set2)
setl={3,8,2,6}
print("Set 1:", set 1)
set2={4,2,1,9}
print("Set 2:", set2)
[Link](set 2) #Unique values will be taken
print("Update Method.", set1)
Output
Set1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Update Method:{1, 2, 3, 4, 6, 8, 9}
47
CS1543: PYTHON PROGRAMMING Module 1
7. [Link](set2) - Returns the intersection of two sets as a new set
Example Program
#Demo of [Link](set 2)
set1={3, 8, 2,6}
print("Set1:".set1}
set2= {4,2,1,9}
print("Set 2:", set 2)
set3 = [Link] (set 2)
print("Intersection:", set3)
Output
Set1: (8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Intersection:{2}
8. set1.intersection_update() - Update the set with the intersection of itself and another. The result will be
stored in setl.
Example Program
#Demo of set1.intersection_update (set 2)
set1={3, 8, 2,6}
print("Set 1:", set1)
set2={4,2,1,9}
print("Set 2:", set 2)
set1.intersection_update(set 2)
print("Intersection:", set1)
Output
Set1:{8, 2, 3, 6}
Set 2: {9, 2, 4, 1}
Intersection_update:{8, 2, 3, 6}
9. [Link](set2) - Returns the difference of two or more sets into a new set
Example Program
#Demo of [Link] (set 2)
set1={3, 8, 2,6}
print("Set1: , set1)
set 2= {4,2,1,9}
print("Set 2:", set2)
set3 = [Link] (set2)
print("Difference:", set 3)
Output
Set1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Difference: {8, 3, 6}
48
CS1543: PYTHON PROGRAMMING Module 1
10.set1.difference_update(set2) - Remove all elements of another set set2 from set1 and the result is
stored in set1.
Example Program
#Demo of set1.difference_update (set 2)
set1={3, 8, 2,6}
print("Set 1:",set1}
set 2={4,2,1,9}
print("Set 2:", set 2)
set1.difference_update (set 2)
print("Difference Update:", set1)
Output
Set 1:{8, 2, 3, 6}
Set 2:{9, 2, 4, 1}
Difference Update: {8, 3, 6)
49
CS1543: PYTHON PROGRAMMING Module 1
[Link](set2) :Returns True if two sets have a null intersection
Example Program
Example Program
#Demo of [Link](set 2)
setl={3,8}
print("Set 1:",set1)
set2={3,8,4,7,1,9}
print("Set 2:", set2)
print("Result of [Link](set2):", [Link](set 2))
Output
Set 1:{8, 3}
Set 2:{1, 3, 4, 7, 8, 9}
Result of [Link](set2): True
Example Program
#Demo of [Link] (set 2)
set1={3,8, 4,6}
print("Set 1:",set1)
set2={3,8}
print("Set 2:",set2)
print("Result of [Link](set2):" [Link](set2)
Output
Set 1:{8, 3, 4, 6)
Set 2:{8, 3}
Result of [Link] (set2): True
FROZENSET
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets. Sets being mutable are
50
CS1543: PYTHON PROGRAMMING Module 1
unhashable, so they can’t be used as dictionary keys. On the other hand, frozensets are hashable and can
be used as keys to a dictionary
Frozensets can be created using the function frozenset(). This datatype supports methods like difference(),
intersection(), isdisjoint() issubset(), issuperset(), symmetric_difference() and union(). Being immutable it
does not have methods like add(), remove(), update(),difference_update(), intersection_update(),
symmetric_difference_update() etc.
Example Program
#Demo of frozenset()
set1= frozenset({3, 8, 4,6})
print ("Set 1:", set1)
set 2=frozenset({3,8})
print("Set 2:", set2)
print("Result of [Link] (set2):", [Link] (set 2))
Output
Set1: frozenset({8, 3, 4, 6})
Set 2: frozenset({8, 3})
Result of [Link] (set2): frozenset((8, 3})
DICTIONARY
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount
of data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces { }
with each item being a pair in the form key:value. Key and value can be of any type. Keys are usually
numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are
sometimes found in other languages as "associative memories" or "associative arrays".
Dictionaries are enclosed by curly braces ({}) and values can be assigned and accessed using square
braces ([ ]).
Example Program
dict={}
dict['one']= "This is one"
dict [2] ="This is two"
tinydict={'name': 'john', 'code': 6734, ‘dept':’ sales’}
studentdict={'name': 'john', 'marks': [35,80,90]}
print (dict['one')) # Prints value for 'one' key
print (dict [2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict. keys ()) # Prints all the keys
print ([Link]()) # Prints all the values
print (studentdict) #Prints studentdict
51
CS1543: PYTHON PROGRAMMING Module 1
Output
This is one
This is two
Example Program
#Demo of updating and adding new values to dictionary
dict1= { 'Name': 'Tom', 'Age':20, 'Height' :160}
print (dict1)
dict1['age'] =25 #updating existing value in Key-Value pair
print("Dictionary after update:", dict1)
dict1[ 'Weight']=60 #Adding new Key-value pair
print("Dictionary after adding new Key-value pair:", dict1)
Output
{'Age': 20, 'Name': Tom', 'Height': 160}
Dictionary after update: {'age': 25, 'Age': 20, 'Name': ‘Tom',
'Height': 160}
Dictionary after adding new Key-value pair: {'age': 25, 'Age': 20,
'Name': 'Tom', ‘Weight’: 60, 'Height': 160}
We can delete the entire dictionary elements or individual elements in a dictionary. We can use del
statement to delete the dictionary completely. To remove entire elements of a dictionary, we can use the
clear() method.
Example Program
#Demo of Deleting Dictionary
dict1= {'Name':'Tom', 'Age' :20, 'Height': 160}
print(dict1)
del dict1['Age'] #deleting Key-value pair 'Age':20
print("Dictionary after deletion:", dict1)
[Link]() #Clearing entire dictionary
print(dict1)
Output
{'Age' : 20, 'Name': 'Tom', 'Height': 160}
Dictionary after deletion: { 'Name': 'Tom', 'Height: 160}
{}
3. type(variable) - The method type() returns the type of the passed variable. If passed variable is
dictionary then it would return a dictionary type. This function can be applied to any variable type like
number, string, list, tuple etc.
Example Program
#Demo of type (variable)
dict1= { 'Name': 'Tom', 'Age' :20, 'Height’:160}
print(dict1)
print("Type (variable).", type (diet))
s="abcde"
print("Type (variable)-", type(s))
list1= [1, 'a', 23,' Tom']
print("Type (variable) -", type(list1))
Output
{'Age': 20, 'Name': Tom', 'Height: 160}
Type (variable) = <class 'dict'>
Type (variable) <class 'str'>
Type (variable)- <class 'list'>
Example Program
#Demo of [Link] ()
dictl= { 'Name': 'Tom', 'Age' :20, 'Height' :160}
print(dict1)
dict2=[Link]()
print(dict2)
Output
{'Age': 20, 'Name': Tom', 'Height': 160}
{'Age': 20, 'Name': Tom', 'Height': 160}
Example Program
#Demo of [Link] ()
dict1= { 'Name': Tom', 'Age :20, 'Height':160}
print(dict1)
print("Keys in Dictionary:", [Link]())
Output
{‘Age': 20, 'Name': 'Tom', 'Height’: 160}
Keys in Dictionary: ['Age'. 'Name', 'Height’]
The values of the keys will be displayed in a random order. In order to retrieve the keys in sorted order, we
can use the sorted() function, all the keys should of the same type. But for using the sorted() function, all
keys should of same type.
Example Program
#Demo of [Link]() in sorted order
dictl= { 'Name': Tom', 'Age' : 20, 'Height':160}
print(dict1)
print("Keys in sorted order:", sorted([Link]()))
Output
{Age : 20, 'Name': "Tom', 'Height’: 160}
[Link]. values0 - This method returns list of all values available in a dictionary
Example Program
#Demo of [Link]()
54
CS1543: PYTHON PROGRAMMING Module 1
dict1={‘Name': Tom', 'Age’: 20, ‘Height’:160}
print(dict1)
print("Values in Dictionary:",[Link]())
Output
The values will be displayed in a random order. In order to retrieve the values in sorted order, we can use
the sorted function. But for using the sorted() function, all the values should of the same type.
Example Program
#Demo of [Link]()in sorted order
dict1= { 'Height' :160, 'Age':20, 'weight':60}
print(dict1)
print("Values in sorted order:",sorted ([Link]()))
Output
{'Age': 20, 'Height': 160, 'Weight': 60}
Values in sorted order: [20, 60, 160]
Example Program
#Demo of [Link]()
dict1={'Name' :' Tom', 'Age':20, 'Height' :160}
print(dict1)
print("Items in Dictionary:", [Link]()) . .
Output
{age': 20, 'Name': 'Tom', 'Height': 160}
Items in Dictionary: [('Age', 20), ('Name', 'Tom'), ('Height', 160)]
[Link](dict2) - The dictionary dict's key-value pair will be updated in dictionary dictl.
Example Program
#Demo of [Link] (dict2)
dict1= { 'Name': 'Tom', 'Age' :20, 'Height' :160)
print(dict1)
dict2={'Weight': 60}
print (dict2)
[Link] (dict2)
print("Dict1 updated Dict2 :",dict1)
Output
{'Age': 20, 'Name': "Tom', 'Height': 160}
{'Weight': 60}
Dict1 updated Dict2: {'Age': 20, 'Name': 'Tom', 'Weight’:60,"Height':
160}
[Link](key, default=None) - Returns the value corresponding to the key specified and if the key
specified is not in the dictionary, it returns the default value.
Example Program
#Demo of [Link] (key, default='Name')
dict1= { 'Name': 'Tom', 'Age’:20, 'Height' :160}
print (dict1)
print("[Link]('Age') :", [Link]('Age'))
55
CS1543: PYTHON PROGRAMMING Module 1
print ("[Link]('Phone') :", [Link]('Phone', 0)) #' Phone not a
key, hence 0 #is given as default
Output
{'Age': 20, 'Name': 'Tom', 'Height': 160)
[Link](key) : 20
[Link](key) : 0
8. [Link](key, default=None) - Similar to [Link](key,default=None) but will set the key with the
value passed and if key is not in the dictionary, it will set with the default value
Example Program
#Demo of [Link] (key, default='Name')
dict1= { 'Name': 'Tom', 'Age':20, 'Height' :160}
print (dict1)
print("[Link] ('Age') :",[Link] ('Age'))
print("[Link] (‘Phone'):", [Link] ('Phone',0))
#'Phone not a #key, hence 0 is give as default value.
Output
{'Age' : 20, 'Name': "Tom', 'Height': 160}
[Link]('Age') : 20
[Link]('Phone') : 0
9. [Link](seq,[val)) - Creates a new dictionary from sequence seq and values from val.
Example Program
#Demo of [Link] (seg, (val])
list=['Name', 'Age', 'Height']
dict=[Link] (list)
print("New Dictionary:", dict)
Output
New Dictionary: { ‘Age': None, 'Name': None, "Height': None }
Objects whose value can change are said to be mutable and objects whose value is unchangeable once they
are created are called immutable. An object's mutability is determined by its type. For instance, numbers,
strings and tuples are immutable, while lists, sets and dictionaries are mutable. The following example
illustrates the mutability of objects.
Example Program
#Mutability illustration
#Numbers
a=10
print(a) #Value of a before subtraction
print(a-2) #value of a - 2
print(a) #Value of a after subtraction
#Strings
56
CS1543: PYTHON PROGRAMMING Module 1
str="abcde"
print(str) #Before applying upper() function
print([Link]()) #result of upper()
print(str) #After applying upper() function
#Lists
list=[1,2,3,4,5]
print(list) #Before applying remove () method
[Link](3)
print(list)#After applying remove() method
Output
10
8
10
abcde
ABCDE
abcde
[1, 2, 3, 4, 5]
[1, 2, 4, 5]
From the above example, it is clear that the values of numbers and strings are not even after applying a
function or operation. But in the case of list, the value is changed or the changes are reflected in the
original variable and hence called mutable.
We may need to perform conversions between the built-in types. To convert between different data types,
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 representing the converted value. Table 2.6 shows various
functions and their descriptions used for data type conversion.
Function Description
int(x [,base]) Converts x to an integer, base specifies the base if x is a string.
long(x [,base]) Converts x to a long integer. base specifies the base if x is a string
float(x) Converts x to a floating-point number.
complex(real [imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
57
CS1543: PYTHON PROGRAMMING Module 1
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Example Program 1
Integer x= 12
Long x= 12000
Floating Point x= 12.0
Complex number = (5+2j)
String conversion of 12 is 12
Expression String of 12 is 12
Example Program 2
Output 2
Conversion of abcde to tuple is ('a', 'b', 'c', d', 'e')
Conversion of abcde to list is ['a', 'b', 'c', 'd', 'e']
Conversion of abcde to set is set(['a', 'c', 'b', 'e', 'd'])
58
CS1543: PYTHON PROGRAMMING Module 1
Conversion of abcde to frozenset is frozenset(['a', 'c', 'b', 'e',
d'])
Conversion of {1: 'a', 2: 'b', 3: 'c'} to dictionary is {1: 'a', 2:
'b',3: 'c'}
Example Program 3
Output 3
SOLVED EXERCISES
1. Write a Python program which accept the radius of a circle from the user and compute the area.
Program
import math
r = float (input("Input the radius of the circle:")
print("The area of the circle with radius",r,"is" , [Link] * r**2))
Output
Input the radius of the circle:3.5 .
The area of the circle with radius 3.5 is: 38.48451000647496
Program
# Biggest of three numbers
a = int(input("Enter first number:")) #Reads First Number
b = int(input("Enter second number:")) #Reads Second Number
c = int(input("Enter third number:")) #Reads Third Number
big = max(a,b,c) #Finds the biggest
print("Biggest of", a,b,c, "is", big)#prints the biggest number
59
CS1543: PYTHON PROGRAMMING Module 1
Output
Enter first number:3
Enter second number: 4
Enter third number: 5
Biggest of 3 4 5 is 5
3. Write a Python program which accepts a sequence of comma-separated number from user and generate
a list and a tuple with those numbers.
Program
values = input ("Input some comma separated numbers:”)
list = [Link](",”)
tuple = tuple(list) print('List : ',
list) print("Tuple : ", tuple)
Output
[Link] a Python program to accept a filename from the user print the extension of that.
Program
filename = input ("Input the Filename: ")
f_extns = [Link](".")
print("The extension of the file is ",f_extns [-1])
Output
Input the Filename: [Link]
The extension of the file is : doc
[Link] a Python program to display the first and last colors from the following list.
Program
color=input("Enter colors (space between colors) :")
color_list = [Link](" ")
print(color_list)
print("The first color in the list is:", color_list[0],"and last
color is:",color_list[-1])
Output
Enter colors (space between colors) : red green blue white yellow
['red', 'green', 'blue', 'white', 'yellow']
The first color in the list is: red and last color is: yellow
6. Write a Python program that accept an integer (n) and computes the value of n+nn+nnn.
Program
a =int (input ("Input an integer:" ))
60
CS1543: PYTHON PROGRAMMING Module 1
n1 = int("%s" %a)
n2 = int("%s%s" %(a, a))
n3 = int("%s%s%s" %(a, a, a))
print(n1," ", n2, " ",n3)
print("sum=", (n1+n2+n3))
Output
Input an integer: 2
2 22 222
sum= 246
*************************************
61
Python's set is an unordered collection of unique items, meaning it cannot have duplicate elements. As it is unordered, elements do not have a specific order and cannot be accessed via indexing or slicing. Sets are created using curly brackets {} or the 'set()' function and support operations like union, intersection, and difference, ensuring only unique values. For instance, a set created with '{1,2,3,2,1}' results in '{1, 2, 3}' by automatically eliminating duplicates .
Identity operators ('is', 'is not') in Python compare the memory locations of two objects to see if they reference the same object (value equality is not considered). If the variables point to the same object, 'is' returns true, otherwise false. Membership operators ('in', 'not in'), however, check the presence of a value within a sequence (like lists, strings, or tuples). They return true if the sequence contains the value, regardless of memory reference. For example, 'a is b' is true only if both 'a' and 'b' point to the same object, while 'x in y' is true if the value 'x' exists within the sequence 'y' .
Bitwise operators in Python perform operations on binary representations of integers, manipulating bits directly, such as AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>). For instance, 'a & b' results in a binary AND operation, where each bit in the output is 1 if the corresponding bits of both operands are 1. Logical operators, on the other hand, evaluate the truthiness of expressions rather than perform bit-level computations. They include AND, OR, and NOT, which are used in boolean logic, returning true or false based on the operands' truth values .
Python's built-in list functions enhance list management by providing essential operations. 'len(list)' returns the total number of elements in the list, useful for iteration and control structures. 'max(list)' and 'min(list)' return the maximum and minimum values, respectively, allowing for efficient comparative operations, especially in sorting or filtering data. These functions simplify common mathematical and data processing tasks by enabling easy access and computation over list elements, allowing developers to focus on logic implementation rather than manual calculations .
Operator precedence in Python determines the order in which parts of an expression are evaluated. Operators with higher precedence are executed first. If operators have the same precedence, their associativity decides their evaluation order; left-associative operators are evaluated from left to right, whereas right-associative operators from right to left. For example, while both '*' (multiplication) and '/' (division) have the same precedence, and '*' being left-associative means '3 * 4 / 2' is calculated as '(3 * 4) / 2'. The exponent operator '**' is right associative, so '2 ** 3 ** 2' is evaluated as '2 ** (3 ** 2)' .
The operator precedence table defines the order in which operations are executed in expressions. This is crucial in complex expressions because it influences logical flow and calculations. Operators with higher precedence are executed first unless overridden by parentheses. Associativity resolves precedence clashes; most operators are left-associative, evaluated from left to right, while expressions like exponentiation (`**`) are right-associative. Misunderstandings in precedence and associativity can lead to logic errors or incorrect computations, making it essential for programmers to use parentheses judiciously to ensure clarity and correctness in expression evaluation and avoid potentially costly real-world errors .
Lists in Python are mutable, allowing changes such as updating, adding, or removing elements after a list has been created. They are suitable for scenarios that require dynamic modification of content. Tuples, however, are immutable, meaning once they are created, their content cannot be altered, making them ideal for fixed collections of items or when a stable data structure is preferred. While lists are defined using square brackets [], tuples are defined using parentheses (). Due to their immutability, tuples can be used as keys in dictionaries while lists cannot .
Python's 'map(function, sequence)' applies a specified function to every item in an iterable, returning a map object that contains the results. This approach enables efficient and clean functional iterations over data collections without the explicit need for loops. For example, converting a list of strings to integers can be simplified through 'map(int, list_of_strings)', enhancing code clarity and reducing redundancy. By abstracting the iteration and application process, 'map()' contributes to more concise and potentially faster running code when processing extensive datasets .
Python supports multiple numeric types including int, long, float, and complex. When combined in an arithmetic operation, these undergo implicit type conversion (promotion) to a common data type before computation to ensure data integrity and precision. For instance, an integer and a float in an expression will result in a float, as Python converts the integer to a float to match types and avoid data loss. This mechanism helps maintain precision and ensures correct type operation, with floating points, for example, accurate up to 15 decimal places .
The 'del' statement in Python is used to delete variables or objects, which can prompt garbage collection and free memory by removing references. This is particularly useful when dealing with large data structures or when an object is no longer needed, as it allows Python's memory allocator to reuse the memory space. By reducing the reference count of an object to zero, 'del' helps in efficient memory usage and is often used in managing resources or cleaning up in long-running applications to prevent memory bloat .