I BCA Python Final Class Notes With Practical Programs1
I BCA Python Final Class Notes With Practical Programs1
M. Nareshkumar M.C.A.,M.Phil.,B.Ed.,
Asst.Professor
Department of B.C.A
PYTHON PROGRAMMING
UNIT - I
Basics of Python Programming: History of Python-Features of Python-Literal-
Constants-Variables - Identifiers–Keywords-Built-in Data Types-Output Statements – Input
Statements-Comments – Indentation- Operators-Expressions-Type conversions. Python
Arrays: Defining and Processing Arrays – Array methods
UNIT – II
Control Statements: Selection/Conditional Branching statements: if, if-else, nested if
and if-elif-else statements. Iterative Statements: while loop, for loop, else suite in loop and
nested loops. Jump Statements: break, continue and pass statements
UNIT -III
Functions: Function Definition – Function Call – Variable Scope and its Lifetime-
Return Statement. Function Arguments: Required Arguments, Keyword Arguments, Default
Arguments and Variable Length Arguments- Recursion. Python Strings: String operations-
Immutable Strings - Built-in String Methods and Functions - String Comparison. Modules:
import statement- The Python module – dir( ) function – Modules and Namespace – Defining
our own modules.
UNIT -IV
Lists: Creating a list -Access values in List-Updating values in Lists- Nested lists -
Basic list operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting
Elements in a tuple – Nested tuples– Difference between lists and tuples. Dictionaries:
Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary Functions
and Methods - Difference between Lists and Dictionaries.
UNIT – V
Python File Handling: Types of files in Python - Opening and Closing files-Reading
and Writing files: write( ) and writelines( ) methods- append( ) method – read( ) and
readlines( ) methods – with keyword – Splitting words – File methods - File Positions-
Renaming and deleting files.
I BCA – PYTHON PROGRAMMING M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
UNIT – I
Basics of Python Programming:
INTRODUCTION: THE PYTHONPROGRAMMING LANGUAGE
➢ Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
➢ Python is not intended to work on special area such as web programming. That is why
it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.
➢ We don’t need to use data types to declare variable because it is dynamically
typed so we can write a=10 to declare an integer value in a variable.
➢ Python makes the development and debugging fast because there is no compilation
step included in python development.
HISTORY
➢ Python was first introduced by Guido Van Rossum in 1991 at the National Research
Institute for Mathematics and Computer Science, Netherlands.
➢ Though the language was introduced in 1991, the development began in the 1980s.
Previouslyvan Rossum worked on the ABC language at CentrumWiskunde
&Informatica (CWI) inthe Netherlands.
➢ The ABC language was capable of exception handling and interfacing with the
Amoeba operating system. Inspired by the language, Van Rossum first tried out
making his own version of it.
➢ Python is influenced by programming languages like: ABC language, Modula-3,
Python is used for software development at companies and organizations such as
Google, Yahoo, CERN, Industrial Light and Magic, and NASA.
Why the Name Python?
➢ Python developer, Rossum always wanted the name of his new language to be short,
unique, and mysterious.
➢ Inspired by Monty Python’s Flying Circus, a BBC comedy series,he named it
Python.
FEATURES
There are various reasons why Python is gaining good popularity in the programming
community. The following are some of the important features of Python:
Simple:
➢ Python is a simple programming language. When we read a Python program, we
feel like reading English sentences. It means more clarity and less stress on
understanding the syntax of the language. Hence, developing and understanding
programs will become easy.
Easy to learn:
➢ Python uses very few keywords. Its programs use very simple structure. So,
developing programs in Python become easy. Also, Python resembles C language.
Most of the language constructs in C are also available in Python. Hence,
migrating from C to Python is easy for programmers.
Open source:
➢ There is no need to pay for Python software. Python can be freely downloaded from
www.python.org website. Its source code can be read, modified and can be used in
programs as desired by the programmers.
Dynamically typed:
➢ In Python, we need not declare anything. An assignment statement binds a
name to an object, and the object can be of any type.
➢ If a name is assigned to an object of one type, it may later be assigned to an object
of a different type.
➢ This is the meaning of the saying that Python is a dynamically typed language.
➢ Languages like C and Java are statically typed. In these languages, the variable
names and data types should be mentioned properly.
➢ Attempting to assign an object of the wrong type to a variable name triggers error
or exception.
Platform independent:
➢ When a Python program is compiled using a Python compiler, it generates byte
code.
➢ Python‟s byte code represents a fixed set of instructions that run on all operating
systems and hardware.
➢ Using a Python Virtual Machine (PVM), anybody can run these byte code
instructions on any computer system. Hence, Python programs are not dependent on
any specific operating system.
➢ We can use Python on almost all operating systems like UNIX, Linux,
Windows,Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, etc. This makes Python
an ideal programming language for any network or Internet.
Portable:
➢ When a program yields the same result on any computer in the world, then it is
called a portable program.
➢ Python programs will give the same result since they are platform independent.
➢ Once a Python program is written, it can run on any computer system using PVM.
However, Python also contains some system dependent modules (or code), which
are specific to operating system.
➢ Programmers should be careful about such code while developing the software if
they want it to be completely portable.
➢ Suppose you are running Python on Windows and you need to shift the same to either a
Mac or a Linux system, then you can easily achieve the same in Python without
having to worry about changing the code.
➢ This is not possible in other programming languages, thus making Python one of the
most portable languages available in the industry.
INSTALLING PYTHON
➢ To install Python, firstly download the Python distribution from official website of
python (www.python.org/ download).
➢ Having downloaded the Python distribution now execute it.
Setting Path in Python:
Before starting working with Python, a specific path is to set to set path follow the steps:
Right click on My Computer--> Properties -->Advanced System setting -->Environment
Variable -->New
In Variable name write path and in Variable value copy path up to C:// Python (i.e., path
where Python is installed). Click Ok ->Ok.
➢ To execute the Python file, you have to use the keyword ‘Python’ followed by the
file name with extension.py See the example given in the screen above with the output
of the file.
Interactive Mode to Execute Python Program:
➢ To execute the code directly in the interactive mode. You have to open the interactive
mode. Press the window button and type the text “Python”. Click the “Python 3.7(32
bit) Desktop app” as given below to open the interactive mode of Python.
➢ You can type the Python code directly in the Python interactive mode. Here, in the
image below contains the print program of Python.
➢ Press the enter button to execute the print code of Python. The output gives the text
“Hello World!” after you press the enter button.
Type any code of Python you want to execute and run directly on interactive mode.
➢ Create a Python file with .py extension and open it with the Python shell. The file looks
like the image given below.
➢ It contains the simple Python code which prints the text “Hello World!”. In order to
execute the Python code, you have to open the ‘run’ menu and press the ‘Run Module’
option.
➢ A new shell window will open which contains the output of the Python code. Create
your own file and execute the Python code using this simple method using Python
IDLE.
DEBUGGING
➢ Debugging means the complete control over the program execution. Developers use
debugging to overcome program from any bad issues.
➢ debugging is a healthier process for the program and keeps thediseases bugs far away.
➢ Python also allows developers to debug the programs using pdb module that comes
with standard Python by default.
➢ We just need to import pdb module in the Python script. Using pdb module, we can set
breakpoints in the program to check the current status.
➢ We can Change the flow of execution by using jump, continue statements.
Syntax Error:
➢ Errors are the mistakes or faults performed by the user which results in abnormal
working of the program.
➢ However, we cannot detect programming errors before the compilation of programs.
The process of removing errors from a program is called Debugging.
➢ A syntax error occurs when we do not use properly defined syntax in any
programming language. For example: incorrect arguments, indentation, use of
undefined variables etc.
Example:
age=16
if age>18:
print ("you can vote”) # syntax error because of not using indentation
else
print ("you cannot vote”) #syntax error because of not using indentation
Runtime Errors:
➢ The second type of error is a runtime error, so called because the error does not
appear until after the program has started running.
➢ These errors are also called exceptions because they usually indicate that something
exceptional (and bad) has happened.
Some examples of Python runtime errors:
➢ division by zero
➢ performing an operation on incompatible types
➢ using an identifier which has not been defined
➢ accessing a list element, dictionary value or object attribute which doesn’t exist
➢ trying to access a file which doesn’t exist
Semantic Errors:
➢ The third type of error is the semantic error. If there is a semantic error in your
program, it will run successfully in the sense that the computer will not generate any
error messages, but it will not do the right thing. It will do something else.
➢ The problem is that the program you wrote is not the program you wanted to write. The
meaning of the program (its semantics) is wrong.
➢ Identifying semantic errors can be tricky because it requires you to work backward by
looking at the output of the program and trying to figure out what it is doing.
Experimental Debugging:
➢ One of the most important skills you will acquire is debugging. Although it can be
frustrating, debugging is one of the most intellectually rich, challenging, and
interesting parts of programming.
➢ Debugging is also like an experimental science. Once you have an idea about what is
going wrong, you modify your program and try again.
➢ For some people, programming and debugging are the same thing. That is,
programming is the process of gradually debugging a program until it does what you
want.
➢ The idea is that you should start with a program that does something and make small
modifications, debugging them as you go, so that you always have a working
program.
Example:
Lookup the first characters of string
str>>>’mumbai’
>>> str [0]
‘m’
Example: To slice a string
>>> str [1:4]
‘umb’
Braces {}
➢ Curly braces are used in python to define set or dictionary.
Example:
Create a set with three elements 10,20,30.
>>> s1 = {10,20,30}
>>> type(s1)
<class ‘set’>
Example:
Create a dictionary with two elements with keys, ‘rollno’ and ‘name’
>>> d1= {‘rollno’:101, ‘name’:’ Vivek’}
>>> type(d1)
<class ‘dict’>
➢ Brackets can be used to access the value of dictionary element by specifying the key.
>>> d1[‘rollno’]
101
Parentheses ( )
➢ Parentheses can be used to create immutable sequence data type tuple.
Example: Create a tuple named ‘t1’ with elements 10,20,30
>>> t1= (10,20,30)
>>> type(t1)
<class ‘tuple’>
➢ Parentheses can be used to define the parameters of function definition and function
call.
Example:
Multiply two numbers using a function def mul(a,b):
#returns a*b
x=2y=3
z=mul (2,3)
print(x,’*’,y,’=’z)
➢ In the function definition def mul(a,b) formal parameters arespecified using
parentheses
➢ In the function call z=mul (2,3) actual values are specified using parenthesis.
Python Literals:
➢ literals are a notation for representing a fixed value in source code.
➢ They can also be defined as raw values or data given in variables or constants.
➢ Python has different types of literal such as:
1. String literals
2. Character literal
3. Numeric literals
4. Boolean literals
5. Literal Collections
6. Special literals
Python String literals
➢ A string is literal and can be created by writing a text(a group of Characters )
surrounded by a single(”), double(“), or triple quotes.
➢ By using triple quotes we can write multi-line strings or display them in the desired
way.
# in single quote
s = 'Welcome To BCA'
# in double quotes
t = "Welcome To BCA"
# multi-line String
m = '''Welcome
To
BCA'''
print(s)
print(t)
print(m)
Output
Welcome To BCA
Welcome To BCA
Welcome
To
BCA
Integer
➢ Both positive and negative numbers including 0.
➢ There should not be any fractional part.
➢ In this example, We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different
variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal, and ‘d‘
is a hexadecimal literal.
➢ But on using the print function to display a value or to get the output they were converted
into decimal.
# integer literal
# Binary Literals
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal
c = 0o320
# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
Output :
20 50 208 299
Float
➢ These are real numbers having both integer and fractional parts. In this example, 24.8 and
45.0 are floating-point literals because both 24.8 and 45.0 are floating-point numbers.
# Float Literal
e = 24.8
f = 45.0
print(e, f)
Output :
24.8 45.0
Complex
➢ The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is the
complex part.
Example: Numeric literal [ Complex ]
Python3
z = 7 + 5j
print(odd_number)
Output :
(2, 4, 6, 8)
(1, 3, 5, 7)
Dictionary literal
➢ The dictionary stores the data in the key-value pair.
➢ It is enclosed by curly braces ‘{}‘ and each pair is separated by the commas(,).
➢ We can store different types of data in a dictionary. Dictionaries are mutable.
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}
print(alphabets)
print(information)
Output :
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}
Set literal
➢ Set is the collection of the unordered data set.
➢ It is enclosed by the {} and each element is separated by the comma(,).
vowels = {'a', 'e', 'i', 'o', 'u'}
fruits = {"apple", "banana", "cherry"}
print(vowels)
print(fruits)
Output :
{'o', 'e', 'a', 'u', 'i'}
{'apple', 'banana', 'cherry'}
Python Special literal
➢ Python contains one special literal (None).
➢ ‘None’ is used to define a null variable.
➢ If ‘None’ is compared with anything else other than a ‘None’, it will return false.
water_remain = None
print(water_remain)
Output :
None
Constants:
What are Constants?
➢ Generally, a constant term is used in Mathematics, a value or quantity that never changes.
➢ In programming, a constant refers to the name associated with a value that never changes
during the programming execution.
➢ Programming constant is different from other constants, and it consists of two things - a
name and an associated value.
➢ The name will describe what the constant is all about, and the value is the concrete
expression of the constant itself.
➢ Once we define the constant, we can only access its value but cannot change it over time.
However, we can modify the value of the variable.
➢ A real-life example is - The speed of light, the number of minutes in an hour, and the
name of a project's root folder.
➢ Using uppercase letters makes the constant stand out from our variables and is a useful or
preferred practice.
➢ Above we discussed the user-defined users; Python also provides several internal names
that can consider and should treat as constants.
Important Constants in Python
Built-in Constants
➢ In the official documentation, the True and False are listed as the first constant.
➢ These are Python Boolean values and are the instance of the int.
>>> int(True)
1
>>> int(False)
0
>>> True = 42
...
SyntaxError: cannot assign to True
The -c is used to execute a small piece of code of Python at the command line. In the
above example, we imported the new_file module, which displays some messages on
the screen.
Output -
The type of __name__ is: <class 'str'>
The value of __name__ is: timezone
➢ As we can see that the __name__ stores the __main__ string, indicates that we
can run the executable files directly as Python program.
➢ On the other hand, the __file__ attribute has the file that Python is currently
importing or executing.
➢ If we use the __file__ attribute inside the file, we will get the path to the
module itself.
Let's see the following example -
Example -
1. print(f"The type of __file__ is: {type(__file__)}")
2. print(f"The value of __file__ is: {__file__}")
Output:
The type of __file__ is: <class 'str'>
The value of __file__ is: D:\Python Project\new_file.py
We can also run directly and will get the same result.
Example -
1. print(f"The type of __file__ is: {type(__file__)}")
2. print(f"The value of __file__ is: {__file__}")
Output:
python new_file.py
The type of __file__ is: <class 'str'>
The value of __file__ is: timezone.py
Useful String and Math Constants
➢ There are many valuable constants in the standard library. Some are strictly connected to
specific modules, functions, and classes; many are generic, and we can use them in
several scenarios.
➢ In the below example, we will use the math and string-related modules math and string,
respectively.
➢ Let's understand the following example -
Example -
>>> import math
>>> math.pi
3.141592653589793
>>> math.tau
6.283185307179586
>>> math.nan
nan
>>> math.inf
inf
>>> math.sin(30)
-0.9880316240928618
>>> math.cos(60)
-0.9524129804151563
>>> math.pi
3.141592653589793
➢ These constants will play a vital role when we write math-related code or perform some
specific computations.
Let's understand the following example -
Example -
import math
class Sphere:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius**2
def perimeter(self):
return 2 * math.pi * self.radius
def projected_volume(self):
return 4/3 * math.pi * self.radius**3
def __repr__(self):
return f"{self.__class__.__name__}(radius={self.radius})"
➢ In the above code, we have used the math.pi instead of custom PI constants.
➢ The math-related constant provides the more contexts to the program.
➢ The advantage of using math.pi constant is that if we are using an older version of
Python, we will get a 32-bit version of Pi.
➢ If we use the above program in modern version of Python, we will get a 64-bit version of
pi. So our program will self-adapt of its concrete execution environment.
➢ The string module also provides some useful built-in string constants. Below is the table
of the name and value of each constant.
Name Value
ascii_lowercase Abcdefghijklmnopqrstuvwxyz
ascii_uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ
ascii_letters ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
digits 0123456789
hexdigits 0123456789abcdefABCDEF
octdigits 01234567
➢ We can use these string-related constants in regular expressions, processing natural
language, with the lot of string processing, and more.
Type-Annotating Constants
➢ The typing module includes a Final class that allows us to type-annotate constants.
➢ If we use the Final class to define the constants in the program, we will get the static type
error that the mypy checker checks and it will show that we cannot reassign to the Final
name. Let's understand the following example.
Example -
from typing import Final
MAX_Marks: Final[int] = 300
MAX_Students: Final[int] = 500
MAX_Marks = 450 # Cannot assign to final name "MAX_SPEED" mypy(error)
String Constants
➢ As discussed in the earlier section, Python doesn't support strict constants; it just has
variables that never change. Therefore, the Python community follows the naming
convention of using the uppercase letter to identify the constant variables.
➢ It can be an issue if we work on a large Python project with many programmers at
different levels. So it would be good practice to have a mechanism that allows us to use
strict constants. As we know, Python is a dynamic language, and there are several ways to
make constants unchangeable. In this section, we will learn about some of these ways.
o The .__slots__ Attributes
➢ Python classes provide the facility to use the __slots__ attributes. The slot has the special
mechanism to reduce the size of the objects. It is a concept of memory optimization on
objects. If we use the __slots__ attribute in the class, we won't be able to add the new
instance, because it doesn't use __dict__ attributes. Additionally, not having
a .__dict__ attribute implies an optimization in terms of memory consumption. Let's
understand the following example.
Example - Without using __slots__ attributes
class NewClass(object):
def __init__(self, *args, **kwargs):
self.a = 1
self.b = 2
if __name__ == "__main__":
instance = NewClass()
print(instance.__dict__)
Output -
{'a': 1, 'b': 2}
➢ Every object in Python contains a dynamic dictionary that allows adding attributes.
Dictionaries consume lots of memory, and using __slots__ reduces the wastage of space
and memory. Let's see another example.
Example -
class ConstantsName:
__slots__ = ()
PI = 3.141592653589793
EULER_NUMBER = 2.718281828459045
constant = ConstantsName()
print(constant.PI)
print(constant.EULER_NUMBER)
constant.PI = 3.14
print(constant.PI)
Output -
3.141592653589793
2.718281828459045
➢ It can have a sequence of letters and digits. However, it must begin with a letter
or _. The first letter of an identifier cannot be a digit.
➢ It's a convention to start an identifier with a letter rather _.
➢ Whitespaces are not allowed.
➢ We cannot use special symbols like !, @, #, $, and so on.
Python Variables:
➢ In programming, a variable is a container (storage area) to hold data. For example,
number =10
➢ Here, number is the variable storing the value 10.
Assigning values to Variables in Python
➢ As we can see from the above example, we use the assignment operator = to assign a value
to a variable.
# assign values to site name variable
site_name = ‘program’
print(site_name)
➢ In the above example, we assigned the value 'programiz.pro' to the site_name variable.
➢ Then, we printed out the value assigned to site_name.
Note: Python is a type-inferred language, so you don't have to explicitly define the variable type.
It automatically knows that programiz.pro is a string and declares the site_name variable as a
string.
Output:
program
apple
➢ Here, the value of site_name is changed from 'program' to 'apple'.
Example: Assigning multiple values to multiple variables
a,b,c = 5,3.2, Hello’
print(a) #prints 5
print(b) #prints 3.2
print(c) #prints Hello
➢ If we want to assign the same value to multiple variables at once, we can do this as:
s1 =s2 = ‘programiz.com’
print(s1) #prints programiz.com
print(s2) #prints programiz.com
➢ Here, we have assigned the same string value 'programiz.com' to both the
variables s1 and s2.
# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=10+3j
print("The type of variable having value", c, " is ", type(c))
➢ The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator in Python.
➢ For example −
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
This will produce the following result −
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
➢ 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 −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples
This produce the following result −
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
➢ The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Ranges
➢ Python range() is an in-built function in Python which returns a sequence of numbers
starting from 0 and increments to 1 until it reaches a specified number.
➢ We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:
range(start, stop, step)
Here is the description of the parameters used:
• start: Integer number to specify starting position, (Its optional, Default: 0)
• stop: Integer number to specify starting position (It's mandatory)
• step: Integer number to specify increment, (Its optional, Default: 1)
Examples
Following is a program which uses for loop to print number from 0 to 4 −
for i in range(5):
print(i)
This produce the following result −
0
1
2
3
4
Now let's modify above program to print the number starting from 1 instead of 0:
for i in range(1, 5):
print(i)
# Returns false as a is 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
This produce the following result −
False
False
False
False
False
True
INPUT STATEMENTS:
How to Take Input from User in Python
➢ Sometimes a developer might want to take user input at some point in the
program. To do this Python provides an input() function.
Syntax:
input('prompt')
➢ where prompt is an optional string that is displayed on the string at the time of taking
input.
# Output
print("Hello, " + name)
print(type(name))
Output:
Enter your name: GFG
Hello, GFG
<class 'str'>
Note: Python takes all the input as a string input by default. To convert it to any other data type
we have to convert the input explicitly. For example, to convert the input to int or float we
have to use the int() and float() method respectively.
# Output
print(add)
Output:
Enter a number: 25
26
How to take Multiple Inputs in Python :
➢ we can take multiple inputs of the same data type at a time in python, using map()
method in python.
a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)
Output :
Enter the Numbers : 2 3 4
The Numbers are : 2 3 4
How take inputs for the Sequence Data Types like List, Set, Tuple, etc.
In the case of List and Set the input can be taken from the user in two ways.
1. Taking List/Set elements one by one by using the append()/add() methods.
2. Using map() and list() / set() methods.
Set.add(int(input()))
print(List)
print(Set)
Output :
Enter the size of the List : 4
Enter the size of the Set : 3
Enter the List elements :
9
0
1
3
Enter the Set elements :
2
9
1
[9, 0, 1, 3]
{9, 2, 1}
Using map() and list() / set() Methods
List = list(map(int, input("Enter List elements : ").split()))
Set = set(map(int, input("Enter the Set elements :").split()))
print(List)
print(Set)
Output :
Enter List elements : 3 4 8 9 0 11
Enter the Set elements :34 88 230 234 123
[3, 4, 8, 9, 0, 11]
{34, 230, 234, 88, 123}
OUTPUT STATEMENTS
How to Display Output in Python
➢ Python provides the print() function to display output to the standard output
devices.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.
Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.
Output
GFG
GFG
➢ In the above example, we can see that in the case of the 2nd print statement there is a
space between every letter and the print statement always add a new line character at
the end of the string.
➢ This is because after every character the sep parameter is printed and at the end of the
string the end parameter is printed. Let’s try to change this sep and end parameter.
Example: Python Print output with custom sep and end parameter
# Python program to demonstrate
# print() method
print("GFG", end = "@")
Output
GFG@G#F#G
Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below
➢ In this string, we can write Python expressions between { and } that can refer to a
variable or any literal value.
Example: Python String formatting using F string
# Declaring a variable
name = "Gfg"
# Output
print(f'Hello {name}! How are you?')
Output:
Hello Gfg! How are you?
Using format()
➢ We can also use format() function to format our output to make it look presentable.
➢ The curly braces { } work as placeholders.
➢ We can specify the order in which variables occur in the output.
Example: Python string formatting using format() function
# Initializing variables
a = 20
b = 10
# addition
sum = a + b
# subtraction
sub = a- b
# Output
print('The value of a is {} and b is {}'.format(a,b))
print('{2} is the sum of {0} and {1}'.format(a,b,sum))
print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,
value_b = b, sub_value = sub))
Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10
Using % Operator
➢ We can use ‘%’ operator.
➢ % values are replaced with zero or more value of elements.
➢ The formatting using % is similar to that of ‘printf’ in the C programming
language.
• %d – integer
• %f – float
• %s – string
• %x – hexadecimal
• %o – octal
Example:
# Taking input from the user
num = int(input("Enter a value: "))
add = num + 5
# Output
print("The sum is %d" %add)
Output:
Enter a value: 50
The sum is 55
Python Comments
➢ Comments in Python are the lines in the code that are ignored by the interpreter during
the execution of the program.
➢ Comments enhance the readability of the code and help the programmers to understand
the code very carefully.
There are three types of comments in Python:
• Single line Comments
• Multiline Comments
• Docstring Comments
Comments in Python
➢ In the example, it can be seen that Python Comments are ignored by the interpreter
during the execution of the program.
# sample comment
name = "welcome to I BCA"
print(name)
Output:
welcome to I BCA
Output
welcome to I BCA
Output
Multiline comments
String Literals In Python
➢ Python ignores the string literals that are not assigned to a variable so we can use these
string literals as Python Comments.
Single-line comments using string literals
➢ On executing the above code we can see that there will not be any output so we use the
strings with triple quotes(“””) as multiline comments.
'This will be ignored by Python'
Indentation in Python
➢ Indentation is a very important concept of Python because without properly indenting
the Python code, you will end up seeing IndentationError and the code will not get
compiled.
Python Indentation
➢ Python indentation refers to adding white space before a statement to a particular block
of code.
➢ In another word, all the statements with the same space to the right, belong to the same
code block.
Example 1
➢ The lines print(‘Logging on to I BCA…’) and print(‘retype the URL.’) are two separate
code blocks.
➢ The two blocks of code in our example if-statement are both indented four spaces.
➢ The final print(‘All set!’) is not indented, so it does not belong to the else block.
# Python program showing
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to I BCA..')
else:
print('retype the URL.')
print('All set !')
Output:
Logging on to geeksforgeeks...
All set !
Example 2
➢ To indicate a block of code in Python, you must indent each line of the block by the
same whitespace.
➢ The two lines of code in the while loop are both indented four spaces.
➢ It is required for indicating what block of code a statement belongs to.
➢ For example, j=1 and while(j<=5): is not indented, and so it is not within the Python
while block.
➢ So, Python code structures by indentation.
j=1
while(j<= 5):
print(j)
j=j+1
Output:
1
2
3
4
5
Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to
you, but a minimum of 1 space has to be used .
OPERATORS
• Operators are particular symbols which operate on some values andproduce an output.
• The values are known as Operands.
Example:
4+5=9
Here 4 and 5 are Operands and (+), (=) signs are the operators.They produce the output 9
• Python supports the following operators:
1. Arithmetic Operators
2. Relational Operators.
3. Logical Operators.
4. Membership Operators.
5. Identity Operators
6. Assignment operator
7. Unary operator
8. Bitwise operator
1. Arithmetic Operators:
Operat Description
ors
// Perform Floor division (gives integer value after
division)
+ To perform addition
- To perform subtraction
* To perform multiplication
/ To perform division
% To return remainder after division (Modulus)
** Perform exponent (raise to power)
• Arithmetic Operator Examples:
Ex 1:
>>> 10+20
30
>>> 20-10
10
>>> 10*220
>>> 10/25
>>> 10%3
1
>>> 10**2
100
>>> 10//3
3
Ex2:
print(20 + 2)
print(20.5 -2)
print(20 * 2)
print(20.5/2)
print(30//2)
print(30.0//2)
OUTPUT
22
18.5
40
10.2
15
15.0
2. Relational Operators:
Operators Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Ex 2:
a = 10
b = 20
print('a < b is', a<b)
print('a <= b is', a<=b)
print('a > b is', a>b)
print('a >= b is', a>=b)
OUTPUT:
a < b is True
a <= b is True
a > b is False
a >= b is False
3. Logical Operators:
Operat Description
ors
and Logical AND (When both conditions are true output will be true)
or Logical OR (If any one condition is true output will be true
not Logical NOT (Compliment the condition i.e., reverse)
Operat Description
ors
in Returns true if a variable is in sequence of another
variable, else false.
not in Returns true if a variable is not in sequence of
another variable, else false.
Membership Operators Examples:
a=10b=20
list= [10,20,30,40,50]
if (a in list):
print (“a is in given list”) else:
print (“a is not in given list”)if (b not in list):
print (“b is not given in list”)
else:
print (“b is given in list”)
Output:
>>>
a is in given listb is given in list
5. Identity operators:
Operat Description
ors
is Returns true if identity of two operands are same, else false
is not Returns true if identity of two operands are not same, else false.
6. Bitwise Operators
➢ We can apply these operators bit by bit.
➢ These operators are applicable only for int and boolean types. By mistake if
we are trying to apply for anyother type then we will get Error
Following are the various bitwise operators used in Python:
1. Bitwise and (&)
2. Bitwise or (|)
3. Bitwise ex-or (^)
4. Bitwise complement (~)
5. Bitwise leftshift Operator (<<)
6. Bitwise rightshift Operator(>>)
Behavior of Bitwise Operators
& ==> If both bits are 1 then only result is 1 otherwise result is 0
OUTPUT
4
5
1
-5
40
2
7. Assignment operator
Output:
30
EXPRESSIONS:
➢ An expression is a combination of values, variables, and operators.
➢ A value all by itself is considered an expression, and so is a variable,so the following
are all legal expressions (assuming that the variable x has been assigned a value):
17
x
x + 17
➢ A statement is a unit of code that the Python interpreter can execute. Wehave seen
two kinds of statement: print and assignment.
➢ Technically an expression is also a statement, but it is probably simpler to think of
them as different things. The important differenceis that an expression has a value; a
statement does not.
Order of Operations:
➢ In Python expression, the order of operations follows the standard order of operations,
also known as PEMDAS (Parentheses, Exponentiation, Multiplication and Division, and
Addition and Subtraction).
➢ This means that operations inside parentheses are performed first, followed by
exponentiation, then multiplication and division, and finally addition and subtraction.
➢ Example 1
Let’s have a look at the below example of an arithmetic expression which is using
multiple operators in one expression.
x = 2 + 3 * 4 - 5 / 2 ** 3
result = x
print(result)
# Output: 13.6875
Explanation:
We solved it using the BODMASS rule or with the help of the order of operations.
➢ 2.Evaluation of Comparison Expressions:
When a comparison expression is evaluated, the values of the operands are compared, and
the result of the comparison is returned as either True or False.
➢ For example, if the expression "5 < 10" is evaluated, the result would be True, as 5 is less
than 10.
Examples:
Here are some examples of comparison Expression-
a = [1,2,3,4]
b = [1,2,3,4]
result = a is b
print(result)
# Output: False
Example –
Here is an example of an expression that uses multiple operators with different precedence:
x = (2 + 3) * 4 - 5 / 2
➢ In this expression, the multiplication of 3 and 4 is done first and returns 12. Then the
addition of 2 and 12 is done and returns 14. Next, the division of 5 by 2 is done and
returns 2.5. Finally, 14 – 2.5 = 11.5
TYPE CONVERSIONS:
➢ The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion.
➢ Python has two typesof type conversion.
➢ When we run the above program, the output will be:datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
➢ In the above program, we add two variables num_int and num_flo,storing the value in
num_new.
➢ We will look at the data type of all three objects respectively.
➢ In the output, we can see the data type of num_int is an integer while the data type of
num_flo is a float.
➢ Also, we can see the num_new has a float data type because Python always converts
smaller data types to larger data types to avoid theloss of data.
Syntax:
<required_datatype>(expression)
➢ Typecasting can be done by assigning the required data type function tothe
expression
ARRAYS:
➢ Array is a container which can hold a fix number of items and these items should be of
the same type.
➢ Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array are as follows −
• Element − Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
➢ As per the above illustration, following are the important points to be considered −
• Index starts with 0.
• Array length is 10, which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an element
at index 6 as 9.
Basic Operations
➢ The basic operations supported by an array are as stated below −
➢ Traverse − print all the array elements one by one.
➢ Insertion − Adds an element at the given index.
➢ Deletion − Deletes an element at the given index.
➢ Search − Searches an element using the given index or by the value.
➢ Update − Updates an element at the given index.
➢ Array is created in Python by importing array module to the python program. Then, the
array is declared as shown below −
from array import *
arrayName = array(typecode, [Initializers])
➢ Typecode are the codes that are used to define the type of value the array will hold.
➢ Some common typecodes used are as follows −
Typecode Value
30
Insertion Operation
➢ Insert operation is to insert one or more data elements into an array.
➢ Based on the requirement, a new element can be added at the beginning, end, or any
given index of array.
Example
➢ Here, we add a data element at the middle of the array using the python in-built insert()
method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)
➢ When we compile and execute the above program, it produces the following result which
shows the element is inserted at index position 1.
Output
10
60
20
30
40
50
Deletion Operation
➢ Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Example
➢ Here, we remove a data element at the middle of the array using the python in-built
remove() method.
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
Output
➢ When we compile and execute the above program, it produces the following result which
shows the element is removed form the array.
10
20
30
50
Search Operation
➢ You can perform a search for an array element based on its value or its index.
Example
Here, we search a data element using the python in-built index() method.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))
Output
➢ When we compile and execute the above program, it produces the following result which
shows the index of the element.
➢ If the value is not present in the array then th eprogram returns an error.
3
Update Operation
➢ Update operation refers to updating an existing element from the array at a given index.
Example
➢ Here, we simply reassign a new value to the desired index we want to update.
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)
Output
➢ When we compile and execute the above program, it produces the following result which
shows the new value at the index position 2.
10
20
80
40
50
Array Methods:
Example
Get the value of the first array item:
x = cars[0] #Ford
Example
Modify the value of the first array item:
cars[0] = "Toyota" #cars = ["Toyota ", "Volvo", "BMW"]
Output:
0
1
2
3
Output:
apple
banana
cherry
Output:
[[2,3,4]
[0,1,5]]
UNIT - II
Control Statements:
1. Conditional Statements:
➢ Conditional Statement in Python perform different computations or actions
depending on whether a specific Boolean constraint evaluates to true or false.
➢ Conditional statements are handled by IF statements in Python.
➢ You can chain together only simple statements, like assignments, prints, and function
calls.
if statement:
Syntax
if (test expression):
statement1
-------
statement n
statement x
➢ Here, the program evaluates the test expression and will execute statement(s)
only if the test expression is True.
➢ If the test expression is False, the statement(s) is not executed.
➢ In Python, the body of the if statement is indicated by the indentation. The
body starts with an indentation and the first unindented line marks the end.
➢ Python interprets non-zero values as True. None and 0 are interpreted as False.
Flow chart:
if-else statement:
Syntax
if (test expression):
statement block 1
else:
statement block 2
statement x
➢ The if...else statement evaluates test expression and will executethe body of if only
when the test condition is True.
➢ If the condition is False, the body of else is executed. Indentation is used to separate
the blocks.
Flow chart :
Example:
# Program checks if the number is positive or negative# And displays an appropriate
message
num = 3
# Try these two variations as well. # num = -5
# num = 0
if (num >= 0):
print ("Positive or Zero")
else:
print ("Negative number")
Output:
Positive or Zero
➢ In the above example, when num is equal to 3, the test expression is true and
the body of if is executed and the body of else is skipped.
➢ If num is equal to -5, the test expression is false and the body of else is
executed and the body of if is skipped.
➢ If num is equal to 0, the test expression is true and body of if is executed and
body of else is skipped.
if...elif...else Statement:
Syntax:
if (test expression 1):
statement block 1
elif (test expression 2):
statement block 2
…………………
elif (test expression N):
statement block n
else:
statement block X
statement Y
➢ The elif is short for else if. It allows us to check for multiple expressions.
➢ If the condition for if is False, it checks the condition of the next elif block
and so on.
Example of if...elif...else:
➢ '''In this program, we check if the number is positive ornegative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
Nested if –else:
➢ We can have a if...elif...else statement insideanother
if...elif...else statement. This is called nesting in computer programming.
➢ Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. They can get confusing, so they must be
avoided unless necessary.
Output1:
Enter a number: 5 Positive number
Output2:
Enter a number: -1 Negative number
Output3:
Enter a number: 0 Zero
Looping Statements:
➢ In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.
➢ There may be a situation when you need to execute a block of code several number of
times.
➢ Programming languages provide various control structures that allow for more
complicated
execution paths.
➢ A loop statement allows us to execute a statement or group of statements multiple
times.
for loop:
➢ The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal.
Syntax :
for loop_control_variable in sequence:
statement block
➢ Here, val is the variable that takes the value of the item inside the sequence on each
iteration.
➢ Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
Flow chart:
Example:
print(range(10))
print(list(range(10)))
print (list (range (2, 8)))
print (list (range (2, 20, 3)))
Output:
range (0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
➢ We can use the range () function in for loops to iterate through a sequence of
numbers.
➢ It can be combined with the len () function to iterate through a sequence using
indexing. Here is an example.
# Program to iterate through a list using indexing
city = ['pune', 'mumbai', 'delhi']
# iterate over the list using index
for i in range(len(city)):
print ("I like", city[i])
Output:
I like pune
I like mumbai I like delhi
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
➢ Here, the for loop prints items of the list until the loop exhausts.
➢ When the for-loop exhausts, it executes the block of code in the else and
prints No items left.
➢ This for...else statement can be used with the break keyword to run the else block
only when the break keyword was not executed.
Example:
# program to display student's marks from record s
tudent_name = 'Soyuj'
marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77}
Output:
No entry with that name found.
While loop:
➢ The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
➢ We generally use while loop when we don't know the number oftimes to iterate
beforehand.
Syntax
statement - X
while (test_expression/condition):
statement block
statement - Y
➢ In the while loop, test expression is checked first. The body of theloop is
entered only if the test_expression evaluates to True.
➢ After one iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.
➢ In Python, the body of the while loop is determined through indentation.
➢ The body starts with indentation and the first unindented line marks the end.
➢ Python interprets any non-zero value as True. None and 0 areinterpreted as
False.
Output:
Inside loop Inside loop Inside loop Inside else
➢ Here, we use a counter variable to print the string Inside loop three times.
➢ On the fourth iteration, the condition in while becomes False.
➢ Hence, the else part is executed.
Nested Loops:
➢ Loops can be nested in Python similar to nested loops in other programming
languages.
➢ Nested loop allows us to create one loop inside another loop.
➢ It is similar to nested conditional statements like nested ifstatement.
➢ Nesting of loop can be implemented on both for loop and while loop.
➢ We can use any loop inside loop for example, for loop can havewhile loop in it.
➢ In this first for loop will initiate the iteration and later second for loop will start
its first iteration and till second for loop complete its all iterations the control will
not be given to first for loop and statements of inside for loop will be executed.
➢ Once all iterations of inside for loop are completed then statements of outside for loop
will be executed and next iteration from first for loop will begin.
Output:
1 2 3 4 5 6 7 8 9 10 Table of 1
2 4 6 8 10 12 14 16 18 20 Table of 2
3 6 9 12 15 18 21 24 27 30 Table of 3
4 8 12 16 20 24 28 32 36 40 Table of 4
5 10 15 20 25 30 35 40 45 50 Table of 5
6 12 18 24 30 36 42 48 54 60 Table of 6
7 14 21 28 35 42 49 56 63 70 Table of 7
8 16 24 32 40 48 56 64 72 80 Table of 8
9 18 27 36 45 54 63 72 81 90 Table of 9
10 20 30 40 50 60 70 80 90 100 Table of 10
Output:
*
**
***
****
*****
******
*******
********
*********
Syntax
while expression:
while expression2:
statement(s) of inside while loop
statement(s) of outside while loop
➢ In this first while loop will initiate the iteration and later second while loop will
start its first iteration and till second while loop complete its all iterations the
control will not be given to first while loop and statements of inside while loop will be
executed.
➢ Once all iterations of inside while loop are completed than statements of outside while
loop will be executed and next iteration from first while loop will begin.
➢ It is also possible that if first condition in while loop expression is False then second
while loop will never be executed.
Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999
Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222
Jumping Statements:
➢ Control statements in python are used to control the order ofexecution of the
program based on the values and logic.
➢ Python provides us with three types of Control Statements:
1. Continue
2. Break
3. Pass
Terminating loops:
➢ The break statement is used inside the loop to exit out of the loop. It is useful
when we want to terminate the loop as soon as the condition is fulfilled
instead of doing the remaining iterations.
➢ It reduces execution time. Whenever the controller encountered a break statement,
it comes out of that loop immediately.
Syntax of break statement for element in sequence:
if condition:
break
Example:
for num in range (10):
if num > 5:
print ("stop processing.")
break
print(num)
Output:
0
1
2
3
4
5
stop processing.
Skipping specific conditions:
➢ The continue statement is used to skip the current iteration and continue with the
next iteration.
Output:
3
4
6
7
Example:
for letter in “Hello”;
pass #The statement is doing nothing
print(“Pass : “,letter)
print(“Done”)
Output
Pass : H
Pass : e
Pass : l
Pass : l
Pass : o
Done
UNIT - III
FUNCTIONS:
➢ Function is a sub program which consists of set of instructions used to perform a specific
task.
➢ A large program is divided into basic building blocks called function.
➢ When the program is too complex and large they are divided into parts. Each part is
separately coded and combined into single program. Each subprogram is called as
function.
➢ Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
➢ Functions are used to avoid rewriting same code again and again in a program.
➢ Function provides code re-usability
➢ The length of the program is reduced.
Types of function:
i) Built in functions
➢ Built in functions are the functions that are already created and stored in python.
➢ These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.
➢ User defined functions are the functions that programmers create for their requirement
and use.
➢ These functions can then be combined to form module which can be used in other
programs by importing them.
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
Flow of Execution:
➢ The order in which statements are executed is called the flow of execution
➢ Execution always begins at the first statement of the program.
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.
Function Prototypes:
i. Function without arguments and without return type
ii. Function with arguments and without return type
iii. Function without arguments and with return type
iv. Function with arguments and with return type
i) Function without arguments and without return type
➢ In this type no argument is passed through the function call and no output is return to
main function
➢ The sub function will read the input values perform the operation and print the result in
the same block
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()
OUTPUT:
enter a 5
enter b 10
15
OUTPUT:
enter a 5
enter b 10
15
iv) Function with arguments and with return type
➢ In this type arguments are passed through the function call and output is return to the
main function
def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)
OUTPUT:
enter a 5
enter b 10
15
Example :
Let’s write a program in Python in which we will define a global variable and access it from
both inside the function and main program body.
# Declaring a global variable in the global scope.
x = 50
# Declare a simple function that prints the value of x.
def showMe():
print('Value of x from local scope = ',x) # calling variable x inside the
function.
# Main program.
showMe() # calling function.
print('Value of x from global scope = ',x)
Output:
Value of x from local scope = 50
Value of x from global scope = 50
➢ In this example, variable x is a global variable. We have accessed it from both inside the
function and outside the function because it has a global scope.
Output:
Good morning!
print(msg) # accessing local variable from outside the function.
NameError: name 'msg' is not defined
➢ As you can see in the output, as we called local variable from outside the function or
main program, we got error because Python destroyed the local variable after the
execution of function.
➢ That is, the local variable does not exist outside the function.
➢ When we define a variable inside the function, it is not related to any way to another
variable with the same name used outside the function.
➢ However, a variable defined outside a function will be read inside a function only when
the function does not change the value. Let’s an example of it.
Example :
# Creating a variable city and set to New York.
city = 'New York' # global scope.
def showMe():
city = 'Dhanbad' # local scope within a function.
print('City:',city)
# Function call
showMe()
print('City:',city) # accessing global variable from the global scope.
Output:
City: Dhanbad
City: New York
➢ In the above program code, first we have assigned a value ‘New York’ to the city, and
then printed the value of city on the console after calling the function.
➢ Next, we have created a function named showMe(). Inside the function showMe(), we
have defined a variable with the same name as that of global variable but with a change
value.
➢ When we accessed this variable, then Python prints the change value on the console, not
the value of global variable because it is not related to any way to another variable with
the same name used outside the function.
➢ As the execution of function body is completed, the value of city is destroyed because it
is a local variable to that function only.
For this reason, the following code throws an exception:
def foo():
print(min([1, 2, 3]))
min = lambda n: "local"foo()
throws the exception:
Traceback (most recent call last):
File "example.py", line 5, in <module>
foo()
File "example.py", line 2, in foo
print(min([1, 2, 3]))
UnboundLocalError: local variable 'min' referenced before assignment
➢ I need this very rarely. To make sure that I don’t confuse anything, I like to use
the globals() dictionary. In this case, I would rather use:
x = "global"def foo():
globals()["x"] = "local"foo()
print(x) # gives "local"
The “nonlocal” statement
➢ You can assign a value to an enclosed variable with the nonlocal statement:
x = "global"def foo():
x = "enclosed" def bar():
nonlocal x
x = "local" bar()
print(x) # gives "local"foo()
print(x) # gives "local"
RETURN STATEMENT:
➢ The return statement is used to exit a function and go back to the place from where it was
called.
➢ If the return statement has no arguments, then it will not return any values.
➢ But exits from function.
Syntax:
return[expression]
Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
Output:
9
Arguments :
➢ Arguments are the value(s) provided in function call/invoke statement.
➢ List of arguments should be supplied in same way as parameters are listed.
➢ Bounding of parameters to arguments is done 1:1, and so there should be same number
and type of arguments as mentioned in parameter list.
Example: my_add(x,y)
Arguments types:
1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments
1. Required Arguments:
➢ The number of arguments in the function call should match exactly with the function
definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56
2. Keyword Arguments:
➢ Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george
Age 56
3. Default Arguments:
➢ Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40
Recursion Function
➢ Recursion is the process of defining something in terms of itself.
➢ A physical world example would be to place two parallel mirrors facing each other. Any
object in between them would be reflected recursively.
Output:
The factorial of 3 is 6
➢ In the above example, factorial() is a recursive function as it calls itself.
➢ When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
➢ Each function multiplies the number with the factorial of the number below it until it is
equal to one.
➢ This recursive call can be explained in the following steps.
➢ Let's look at an image that shows a step-by-step process of what is going on:
➢ Our recursion ends when the number reduces to 1. This is called the base condition.
➢ Every recursive function must have a base condition that stops the recursion or else the
function calls itself infinitely.
➢ The Python interpreter limits the depths of recursion to help avoid infinite recursions,
resulting in stack overflows.
➢ By default, the maximum depth of recursion is 1000.
➢ If the limit is crossed, it results in RecursionError. Let's look at one such condition.
def recursor( ):
recursor( )
recursor( )
Output
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
PYTHON STRINGS:
➢ There are numerous types of sequences in Python.
➢ Strings are a special type of sequence that can only store characters, and they have a
special notation.
➢ Strings are sequences of characters and are immutable.
➢ A string is a sequence of characters. We can access the characters one at a
time with the bracket operator:
>>>food = 'roti'
>>>letter = food[1]
➢ The second statement retrieves the character at index position onefrom the food variable
and assigns it to the letter variable.
➢ The expression in brackets is called an index. The index indicates which
character in thesequence you required.
Example.
‘I want to read book’. This is a string, It has been surrounded in single
quotes.
Declaring Python String
String literals in Python
String literals are surrounded by single quotes or double-quotes.
You can also surround them with triple quotes (groups of 3 single quotes
or double quotes).
“””I want to read book’”””
”’ I want to read book’”’
Or using backslashes.
>> ‘Thank\
Good Morning Sir !’
‘ThanksGood Morning Sir!’
➢ You cannot start a string with a single quote and end it with a doublequote..
➢ But if you surround a string with single quotes and also want to use singlequotes as
part of the string, you have to escape it with a backslash (\).
‘Send message to Madam\’s son ’
This statement causes a SyntaxError:
‘Send message to Madam’s son’
➢ You can also do this with double-quotes. If you want to ignore escape sequences, you
can create a raw string by using an ‘r’ or ‘R’ prefix with the string.
Common escape sequences:
➢ \\ Backslash
➢ \n Linefeed
➢ \t Horizontal tab
➢ \’ Single quotes
➢ \” Double quotes
We can assign a string to a variable.
Hello Python
Hello Python
➢ Triple quotes are generally used for represent the multiline or docstring
Operator Description
str1 = "Hello"
str2 = " World"
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Hello world
print(str1[4]) # prints o
print(str1[2:4]) # prints ll
print('w' in str1) # prints false as w is not present in str1
print('Wo' not in str2) # prints false as Wo is present in str2.
Output:
HelloHelloHello
Hello World
o
ll
False
False
Hello\n world
The string str1 : Hello
String Operations:
➢ String is an array of bytes that represent the Unicode characters in Python.
➢ Python does not support character datatype.
➢ A single character also works as a string.Python supports writing the string within a
single quote('') and a double quote("").
Example
"Python" or 'Python'Code
SingleQuotes ='Python in Single Quotes'
DoubleQuotes ="Python in Double Quotes"
print(SingleQuotes)
print(DoubleQuotes)
Output:
Python in Single Quotes Python in Double
Quotes
➢ A single character is simply a string with a length of 1. The squarebrackets can be
used to access the elements from the string.
print()
➢ This function is used for displaying the output or result on the user screen.
Syntax
print('Text or Result') or print("Text or Result')Indexing in String
➢ This helps the programmer to concatenate a string with any data which is
otherwise not allowed.
Example:
str1 = “Hello”
var = 7
str2 = str1 + str(var)
print(str2)
Output:
Hello7
Python slice string:
syntax:
str_object[start_pos:end_pos:step]
➢ The slicing starts with the start_pos index (included) and ends at
end_pos index (excluded).
➢ The step parameter is used to specify the steps to take from start to
end index.
➢ Python String slicing always follows this rule: s[:i] + s[i:] == s for any index ‘i’.
➢ All these parameters are optional – start_pos default value is 0, theend_pos
default value is the length of string and step default value is 1.
➢ Let’s look at some simple examples of string slice function to create substring.
s = 'HelloWorld'
print(s[:])
print(s[::])
Output:
HelloWorld
HelloWorld
➢ Note that since none of the slicing parameters were provided, the substringis
equal to the original string.
➢ Let’s look at some more examples of slicing a string.
s = 'HelloWorld'
first_five_chars = s[:5]
print(first_five_chars)
third_to_fifth_chars = s[2:5]
print(third_to_fifth_chars)
Output:
Hello
Llo
➢ Note that index value starts from 0, so start_pos 2 refers to the third
character in the string.
➢ Let’s look at some other examples of using steps and negative index
values.
s1 = s[2:8:2]
print(s1)
Output:
Loo
➢ Which implies that each time you make a change to a string variable, you are actually
producing a brand new string.
➢ Because of this, tutorials out there warn you to avoid string concatenation inside a loop
andadvise using join instead for performance reasons.
➢ Even the official documentation says so!
➢ You will get a mistake message when you need to change the substance ofthe string.
Traceback (latest call last):
Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in
<module>
name_1[0] = 'T'
TypeError: 'str' object doesn't uphold thing task
Arrangement
➢ One potential arrangement is to make another string object with vital alterations:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("name_1 = ", name_1, "and name_2 = ", name_2)
name_1 = Aarun and name_2 = Tarun
➢ To watch that they are various strings, check with the id() work:
name_1 = "Aarun"
name_2 = "T" + name_1[1:]
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_2 = 2342565669888
➢ To see more about the idea of string permanence, think about theaccompanying code:
name_1 = "Aarun"
name_2 = "Aarun"
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))
Output:
id of name_1 = 2342565667256
id of name_1 with new value = 2342565668656
endswith(suffix, [start], [end]) Returns True if the string ends >>> mystr = "Python"
with the specified suffix, >>>print(mystr.endswith("y"))
otherwise it returns False. False
>>>print(mystr.endswith("hon"))
True
Expandtabs(tabsize=8) Returns a copy of the string >>> mystr = "1\t2\t3"
where all tab characters are >>> print(mystr)
replaced by one or more spaces, 123
depending on the current column >>>print(mystr.expandtabs())
and the given tab size. 123
>>>print(mystr.expandtabs(tabsize=15))
12
3
>>>print(mystr.expandtabs(tabsize=2))
123
Find(sub, [start], [end]) Returns the lowest index in the >>> mystring = "Python"
string where substring sub is >>>print(mystring.find("P"))
found within the slice 0
s[start:end]. >>>print(mystring.find("on")) 4
>>> print(a.isdecimal())
False
>>> c = u"\u00B2"
>>> print(c.isdecimal())
False
>>> c="133"
>>> print(c.isdecimal())
True
Isdigit() Returns True if all characters in >>> c="133"
the string are digits >>> print(c.isdigit())
True
>>> c = u"\u00B2"
>>> print(c.isdigit())
True
>>> a="1.23"
>>> print(a.isdigit())
False
isidentifier() Returns True if the string is an >>> c="133"
identifier >>> print(c.isidentifier())
False
>>> c="_user_123"
>>> print(c.isidentifier())
True
>>> c="Python"
>>> print(c.isidentifier())
True
Islower() Returns True if all characters in >>> c="Python"
the string are lower case >>> print(c.islower())
False
>>> c="_user_123"
>>> print(c.islower())
True
>>> print(c.islower())
False
Isnumeric() Returns True if all characters in >>> c="133"
the string are numeric >>> print(c.isnumeric())
True
>>> c="_user_123"
>>> print(c.isnumeric())
False
>>> c="Python"
>>> print(c.isnumeric())
False
isprintable() Returns True if all characters in >>> c="133"
the string are printable >>> print(c.isprintable())
True
>>> c="_user_123"
>>> print(c.isprintable())
True
>>> c="\t"
>>> print(c.isprintable()) False
------------Hello Python----------- -
>>> print(mystr.rstrip(),"_")
------------Hello Python----------- _
split(sep=None, maxsplit=-1) Splits the string at the specified >>> mystr = "Hello Python"
separator, and returns a list >>> print(mystr.split())
['Hello', 'Python']
>>> mystr1="Hello,,Python"
>>> print(mystr1.split(","))
['Hello', '', 'Python']
splitlines([keepends]) Splits the string at line breaks >>> mystr = "Hello:\n\n
and returns a list Python\r\nJava\nC++\n"
>>>print(mystr.splitlines())
['Hello:', '', ' Python',
'Java', 'C++']
>>>print(mystr.splitlines(keepe
nds=True))
['Hello:\n', '\n', '
Python\r\n', 'Java\n',
'C++\n']
startswith(prefix[,start[, end]]) Returns true if the string starts >>> mystr = "Hello Python"
with the specified value >>>print(mystr.startswith("P"))
False
>>>print(mystr.startswith("H"))
True
>>>print(mystr.startswith("Hell"))
True
strip([chars]) Returns a trimmed version of the >>> mystr = "Hello Python"
string >>> print(mystr.strip(),"!")
Hello Python !
>>> print(mystr.strip(), "")
Hello Python
swapcase() Swaps cases, lower case >>> mystr = "Hello PYthon"
becomes upper case and vice >>> print(mystr.swapcase())
versa hELLO python
title() Converts the first character of >>> mystr = "Hello PYthon"
each word to upper case >>> print(mystr.title())
Hello Python
>>> mystr = "HELLO JAVA"
>>> print(mystr.title())
Hello Java
translate(table) Returns a translated string >>> frm = "helloPython"
>>> to = "40250666333"
>>> trans_table =str.maketrans(frm, to)
>>> secret_code = "Secret
Code".translate(trans_table)
>>> print(secret_code)
S0cr06 C3d0
upper() Converts a string into upper case >>> mystr = "hello Python"
>>> print(mystr.upper())
HELLO PYTHON
zfill(width) Fills the string with a specified >>> mystr = "999"
STRING COMPARITIONS:
The following are the ways to compare two string in Python:
1. By using == (equal to) operator
2. By using != (not equal to) operator
3. By using sorted() method
4. By using is operator
5. By using Comparison operators
Output:
Enter the first String: Engineering Discipline
Enter the second String: Discipline
EngineeringFirst and second strings are
equal.
4. Comparing two strings using ‘is’ operator
o Python is Operator returns True if two variables refer to the same
objectinstance.
str1 = "DEED"
str2 = "DEED"
str3 = ''.join(['D', 'E', 'E', 'D'])
print(str1 is str2)
print("Comparision result = ", str1 is str3)
Output:
True
Comparision result = False
➢ In the above example, str1 is str3 returns False because object str3 wascreated
differently.
Output:
False
False
True
True
Python Modules
➢ Here we will explain how to construct and import custom Python modules.
➢ Additionally, we may import or integrate Python's built-in modules via various methods.
Simplification:
➢ A module often concentrates on one comparatively small area of the overall problem
instead of the full task.
➢ We will have a more manageable design problem to think about if we are only
concentrating on one module.
➢ Program development is now simpler and much less vulnerable to mistakes.
Flexibility:
➢ Modules are frequently used to establish conceptual separations between various problem
areas.
➢ It is less likely that changes to one module would influence other portions of the program
if modules are constructed in a fashion that reduces interconnectedness.
➢ (We might even be capable of editing a module despite being familiar with the program
beyond it.) It increases the likelihood that a group of numerous developers will be able to
collaborate on a big project.
Reusability:
➢ Functions created in a particular module may be readily accessed by different sections of
the assignment (through a suitably established api).
➢ As a result, duplicate code is no longer necessary.
Scope:
➢ Modules often declare a distinct namespace to prevent identifier clashes in various parts
of a program.
➢ In Python, modularization of the code is encouraged through the use of functions,
modules, and packages.
➢ Rather than duplicating their definitions into several applications, we may define our
most frequently used functions in a separate module and then import the complete
module.
➢ Let's construct a module. Save the file as example_module.py after entering the
following.
Example:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function
➢ Here, a module called example_module contains the definition of the function square().
The function returns the square of a given number.
Output:
The value of euler's number is 2.718281828459045
➢ The math module is now named mt in this program. In some situations, it might help us
type faster in case of modules having long names.
➢ Please take note that now the scope of our program does not include the term math. Thus,
mt.pi is the proper implementation of the module, whereas math.pi is invalid.
Code
# Here, we are creating a simple Python program to show how to import specific
# objects from a module
# Here, we are import euler's number from the math module using the from keyword
from math import e
# here, the e value represents the euler's number
print( "The value of euler's number is", e )
Output:
The value of euler's number is 2.718281828459045
➢ Only the e constant from the math module was imported in this case.
➢ We avoid using the dot (.) operator in these scenarios. As follows, we may import many
attributes at the same time:
Code
# Here, we are creating a simple Python program to show how to import multiple
# objects from a module
from math import e, tau
➢ Since we provide a Number a value inside the function, Python considers a Number to be
a local variable. UnboundLocalError will be the outcome if we try to access the value of
the local variable without or before declaring it global.
Code
Number = 204
def AddNumber(): # here, we are defining a function with the name Add Number
# Here, we are accessing the global namespace
global Number
Number = Number + 200
print("The number is:", Number)
# here, we are printing the number after performing the addition
AddNumber() # here, we are calling the function
print("The number is:", Number)
Output:
The number is: 204
The number is: 404
Note : Modules should be placed in the same directory as that of the program in which it is
imported. It can also be stored in one of the directories listed in sys.path.
➢ Now that we have been using the dot operator to acess members(variables or functions)
of the module.
# code in MyModule
def large(a,b):
if a>b:
return a
else:
return b
# code in Find.py
import MyModule
print(“Large(50, 100) = “ , MyModule.large(50,100))
print(“Large(‘B’, ‘c) = , MyModule.large(‘B’ , ‘c’))
print(“Large(‘HI’, ‘BI’) =”MyModule.large(“HI’ , ‘BI’))
Output:
Large(50 , 100) = 100
Large(‘B’ , ‘c’) = c
Large(‘HI’, ‘BI’) = HI
UNIT - IV
Python List:
➢ Python Lists are similar to dynamically scaled arrays.
➢ They are used to hold a series of different formats of data.
➢ Python lists are changeable (mutable), which means they can have their elements changed
after they are created.
➢ A Python list can also be defined as a collection of distinct types of values or items.
➢ The elements in the list are separated by using commas (,) and are surrounded by square
brackets [].
➢ A single list can contain Datatypes such as Integers, Strings, and Objects.
➢ Lists are changeable, which means they can be changed even after they are created.
➢ Each element in the list has a different location in the list, allowing for the duplication of
components in the list, each with its own individual place and credibility.
Output
[]
List of languages are: ['Python', 'Java', 'C++', 'SQL']
['John', 23, 'Car', 45.2837]
['Values', [1, 2, 3], ['Marks']]
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
1.List Index
➢ Lists are ordered sequences of elements that, like all other ordered containers in Python, are
indexed with a starting index of 0.
➢ We supply the index (an integer) inside square brackets ([]) to access an element in a list.
Nested indexing is used to retrieve nested listings.
➢ Attempting to access indexes beyond the limit will result in an IndexError.
➢ The index must be a positive integer.
➢ We can’t use floats or other kinds because it will cause a TypeError.
Example
# Python program to illustrate List Indexing
my_list = ['A', 'B', 'Car', 'Dog', 'Egg']
# nesting list
nested = ['Values', [1, 2, 3], ['Marks']]
print(nested[0][0])
print(nested[1][0])
print(nested[1][2])
print(nested[2][0])
# IndexError exception
print(my_list[10])
Output:
List value at index 1: B
List value at index 2: Car
List value at index 4: Egg
V
1
3
Marks
Traceback (most recent call last):
File "", line 16, in
IndexError: list index out of range
General Format:
Seq = List[start:stop:step]
Example:
num_list = [1,2,3,4,5,6,7,8,9,10]
2. Negative Indexing
➢ Negative sequence indexes in Python represent positions from the array’s end.
➢ Python sequences support negative indexing.
➢ The value of -1 denotes the last item, the index of -2 the second last item, and so on.
Example
# Python program to illustrate Negative Indexing
my_list = ['A', 2, 'Car', 'Dog', 'Egg', 100]
print(my_list[-1])
print(my_list[-3])
print(my_list[-6])
Output
100
Dog
A
Updating Values in Lists:
➢ Once created , one or more elements of a list can be easily updated by giving the slice on the
left -hand side of the assignment operator.
➢ We can also append new values in the list and remove existing values from the list using the
append( ) method and del statement respectively.
Example:
num_list = [1,2,3,4,5,6,7,8,9,10]
print(“num_list is: “,num_list)
num_list[5] = 100
print(“List after updation is :”,num_list)
num_list.append(200)
print(“List after appending a value is :”,num_list)
del num_list[3]
print(“List after deleting a value is :”,num_list)
Output:
num_list is: [1,2,3,4,5,6,7,8,9,10]
List after updation is : [1,2,3,4,5,100,7,8,9,10]
List after appending a value is : [1,2,3,4,5,100,7,8,9,10 , 200]
List after deleting a value is : [1,2,3,5,100,7,8,9,10 , 200]
➢ If you know exactly which element to delete , use the del statement, otherwise use the
remove( ) method to delete the unknown elements.
Example:
num_list = [1,2,3,4,5,6,7,8,9,10]
del num_list[2:4] # delete numbers at index 2 and 3
print(num_list)
Output:
[1,2,5,6,7,8,9,10]
➢ Can you now imagine what will happen if you write delnum num_list? Yes, the entire
variables will be deleted.
➢ If you make any attempt to use this variable after the del statement, then an error will be
generated. This is very much evident from the code given the following example.
num_list = [1,2,3,4,5,6,7,8,9,10]
del num_list # delete numbers at index 2 and 3
print(num_list)
Output:
Error name ‘num_list’ is not defined
➢ To insert items from another list or sequence at a particular location, you can use the
slice operation.
➢ This will result in the creation of a list with in anotherlist.
Example:
num_list = [1,9,11,13,15]
print(“Original List : “, num_list)
num_list[2] =[3,4,5]
print(“After inserting another list, the updated list is :”,num_list)
Output:
Original List :[1,9,11,13,15]
After inserting another list, the updated list is :[1,9,[3,5,7],13,15]
Nested Lists:
➢ Nested list means a list within another list.
➢ We have already said that a list has elements of different data types which can include
even a list,
Example:
list1= [1 , ‘a’ , “abc” , [2,3,4,5] , 8.9]
i=0
while i<(len(list1));
print[“list1[“,I,”] = “,list1[i])
i+=1
Output:
List1[0] = 1
List1[1] = a
List1[2] = abc
List1[3] = [2,3,4,5]
List1[4] = 8.9
Cloning Lists:
➢ If you want to modify a list and also keep a copy of the original list, then you should
create a separate copy of the list.
➢ This process is called cloning, The slice operation is used to clone a list.
Example:
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = list1
print(“List1 = “, list1)
print(“List2 = “, list2)
list3 = list1[2:6]
print(“List3 = “, list3)
Output:
List1 = [1,2,3,4,5,6,7,8,9,10]
List2 = [1,2,3,4,5,6,7,8,9,10]
List3 = [3,4,5,6]
➢ Let behave in the similar way as strings when operators like + (concatenation) and
*(repetition) are used.
List Methods :
1. append( )
➢ This function is used to add value to the existing list. Just use the append keyword and
add the name.
➢ The new value will be added at the end of the list.
➢ If we pass another list in the append function, it will add a list as the value.
names = ["Sanjay", "Ramesh", "Suresh", "Ravi"]
names.append("John")
print (names)
Output:
[“Sanjay”, “Ramesh”, “Akshay”,” Ravi”, “John”]
nums = [1,2,3]
names.append(nums)
print (names)
output:
[“Sanjay”, “Ramesh”, “Akshay”, “Ravi”, “John”,[1,2,3]]
2. sort( )
➢ This function is used to arrange the data alphabetically in ascending or descending order.
➢ By default, it does the sort in ascending order.
➢ If we need to do the sorting in descending order, we need to reverse the keyword.
Output:
["Akshay","John","Ramesh","Ravi","Sanjay"]
names.sort(reverse=True)
Output:
["Sanjay","Ravi","Ramesh","John","Akshay"]
3. copy( )
➢ If we want to make a copy of the list, we can assign it to a new variable, but in the case of
Python, a copy might be created, but the problem is that if we change any value in the
original list, then the value of the new list also changes.
➢ They are just sharing the reference of the original variable.
➢ So to avoid this, we can use the copy() function.
new_names = names.copy()
print(new_names)
Output:
["Sanjay","Ravi","Ramesh","John","Akshay"]
names.append(1)
print(names)
Output:
["Sanjay","Ravi","Ramesh","John","Akshay",1]
new_names = ["Sanjay","Ravi","Ramesh","John","Akshay",1]
print(new_names)
Output:
["Sanjay","Ravi","Ramesh","John","Akshay"]
4. clear( )
➢ This function is used to remove all the values from the list and return an empty list with a
square bracket.
names.clear()
print(names)
Output:
[]
5. reverse( )
➢ This function is used to reverse the items of the list.
➢ It will read the element from right to left and modify the current list.
names=["Sanjay","Ravi","Ramesh","John","Akshay"]
names.reverse()
Output:
["Akshay","John","Ramesh","Ravi","Sanjay"]
6. remove( )
➢ If we want to remove any value from the list and don’t know the value’s index position,
then we can use the remove() function.
➢ We have to pass the value which we want to remove from the list, and it will search that
element from left to right, from index position 0, and whichever the matching element
comes first will be removed.
names = ["Sanjay","Ravi","Ramesh","John","Akshay"]
names.remove("Ravi")
print(names)
Output:
["Sanjay","Ramesh","John","Akshay"]
7. pop( )
➢ This function is also similar to the remove() function, but in this function, we can remove
the value from the list based on an index, not a value.
➢ We must know the index position of the value in the list to remove it.
names = ["Sanjay","Ravi","Ramesh","John","Akshay"]
names.pop[2]
print(names)
Output:
["Sanjay","Ravi","John","Akshay"]
8. insert( )
➢ This function is also used to insert the value into the list, but we can insert value at a
specific index position using this function.
➢ The element that exists, in particular, will shift to the next index, which means all the
elements after that index will increment by 1.
names = ["Sanjay","Ravi","John","Akshay"]
names.insert(1,"David")
print(names)
Output:
["Sanjay","David","Ravi","John","Akshay"]
9. count( )
➢ This function is used to find which element exist and how many times in the list.
➢ It will count the total number based on which value is passed inside the function.
names = ["Sanjay","Ravi","John","Akshay","John"]
names.count("David")
Output:
1
names.count("John")
Output:
2
10. extend( )
➢ This function is similar to the append() function only difference is that if we add a list in
another list append() function will make it as a nested list, but in this function, if we add
another list, it will add items on that list instead of making it nested.
names = ["Sanjay",”Ramesh” ,"Akshay" ,"Ravi","John “]
names.append(nums)
print(names)
Output:
["Sanjay", "Ramesh", "Akshay", "Ravi", "John",1,2,3]
11. index( )
➢ This function is used to find the index of any element from the list.
➢ We need to pass the name of the value. Values are case-sensitive.
names = ["Sanjay","Ravi","John","Akshay","John"]
names.index("Ravi")
Output:
1
Example :
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple',
'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
TUPELS IN PYTHON:
➢ A tuple in the Python is similar to the list. The difference between the two is that we
cannot change the element of the tuple once it is assigned to whereas we can change the
elements of a list
➢ The reasons for having immutable types apply to tuples: copy efficiency: rather than
copying an immutable object, you can alias it (bind a variable to a reference) ... interning:
you need to store at most of one copy of any immutable value.
➢ There’s no any need to synchronize access to immutable objects in concurrent code.
Creating a Tuple:
➢ A tuple is created by the placing all the elements inside parentheses '()', separated by
commas. The parentheses are the optional and however, it is a good practice to use
them.
➢ A tuple can have any number of the items and they may be a different types (integer,
float, list, string, etc.).
Example:
# Different types of tuples # Empty tuple
tuple = ( )
print(tuple)
# Tuple having integers
tuple = (1, 2, 3)
print(tuple)
# tuple with mixed datatypes
tuple = (1, "code", 3.4)
print(tuple)
# nested tuple
tuple = ("color ", [6, 4, 2], (1, 2, 3)) print(tuple)
Output:
()
(1, 2, 3)
(1, 'code', 3.4)
('color', [6, 4, 2], (1, 2, 3))
➢ A tuple can also be created without using parentheses. This is known astuple packing.
Example:
tuple = 3, 2.6, "c print(tuple)
# tuple unpacki a, b, c = tuple
print(a) #3
print(b) # 4.6
print(c) # dog
Output:
( 3, 2.6, 'color')
3
2.6
color
1.Indexing:
➢ We can use the index operator [] to access an item in a tuple,where the index starts from 0.
➢ So, a tuple having 6 elements will have indices from 0 to 5.
➢ Trying to access an index outside of the tuple index range(6,7,... in this example) will raise
an IndexError.
➢ The index must be an integer, so we cannot use float or othertypes.
➢ This will result in TypeError.
➢ Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
print(tuple[5]) # ’f’
Output:
afo4
2.Negative Indexing:
➢ Python allows negative indexing for its sequences.
➢ The index of -1 refers to the last item, -2 to the second last item and so on.
Example:
# Negative indexing for accessing tuple elements
tuple = (’a’,’b’,’c’,’d’,’e’,’f’)
# Output: ’f’ print(tuple[-1])
# Output: ’a’ print(tuple[-6])
Output:
fa
3.Slicing:
➢ We can access the range of items from the tuple by using theslicing operator colon:
Example:
# Accessing tuple elements using slicing
tuple = (’a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’)
# elements 2nd to 4th
# Output: (’b’, ’c’, ’d’)
print(tuple[1:4])
# elements beginning to 2nd
# Output: (’a’, ’b’)
print(tuple[:-7])
# elements 8th to end
# Output: (’h’, ’i’)
print(tuple[7:])
# elements beginning to end
# Output: (’a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’, ’i’)
print(tuple[:])
Output:
(’b’, ’c’, ’d’)
(’a’, ’b’)
(’h’, ’i’)
(’a’, ’b’, ’c’, ’d’, ’e’, ’f’, ’g’, ’h’, ’i’)
Updating Tuple:
➢ We have already learn that tuple is immutable and so, the values in the tuple cannot be
changed.
➢ You can only extract values from a tuple to form a tuple.
Example:
Tup1 = (1,2,3,4,5)
Tup2 = (6,7,8,9,10)
Tup3 = Tup1 + Tup2
print(Tup3)
Output:
(1,2,3,4,5,6,7,8,9,10)
Deleting Elements in Tuple:
➢ Since tuple is an immutable data structure, you cannot delete values from it.
➢ Of course , you can create a new tuple that has all elements in your tuple except the ones
you don’t want.
➢ Observe the code given in the following example and note the error generated.
Tup1 =(1,2,3,4,5)
del Tup1[3]
print(Tup1)
Output :
Eror ‘tuple’ object doesn’t support item deletion.
➢ Here you can always delete the entire tuple by using the del statement. This is done in the
code given below.
Example:
Tup1 = (1,2,3,4,5)
del Tup1
print(Tup1)
Output:
NameError : name ‘Tup1’ is not defined
➢ Note that this exception is raised because you are now trying to print a tuple that has
already been deleted.
Tuple Operation:
Nested Tuples:
➢ Python allows you to define tuple inside another tuple. This is called a nested tuple.
Consider the program code given below.
➢ We have a list of students who have topped in their respective courses. We store the
name, course, and aggregate of three students as tuples into the tuple Toppers.
Example:
Toppers = ((“Arrav”,”BCA”,92.0),(“”Chaitanya”,”BCA”,99.0),(“Vijay”,”BCA”,97))
for i in Toppers:
print(i)
Output:
(‘Arav’,’BCA’,92.0)
(‘Chaitanya’,’BCA’,99.0)
(‘Vijay’,’BCA’,97)
Example:
Tup = (1,2,3,4,5,6,7,8)
print(Tup.index(4))
Output:
3
Difference between List and Tuple :
List
➢ List is a container to contain different types of objects and is used to iterate objects.
Example
list = ['a', 'b', 'c', 'd', 'e']
Tuples
➢ Tuple is also similar to list but contains immutable objects. Tuple processing is faster
than List.
Example
tuples = ('a', 'b', 'c', 'd', 'e')
Appropriate for List is useful for insertion Tuple is useful for readonly
3
and deletion operations. operations like accessing elements.
Methods List provides many in-built Tuples have less in-built methods.
5
methods.
Error prone List operations are more Tuples operations are safe.
6
error prone.
Dictionaries:
Creating a Dictionary:
➢ To create the Python dictionary, we need to pass the sequence of the items inside curly
braces {}, and to separate them using a comma (,).
➢ Each item has a key and a value expressed as an "key:value" pair.
➢ The values can belong to the any of data type and they can repeat, but the keys are must
remain the unique.
➢ The following examples are demonstrate how to create the Python dictionaries:
Creating an empty dictionary:
dict_sample = {}
➢ To print the dictionary contents, we can use the Python's print() function and pass the
dictionary name as the argument to the function. For example:
dict_sample = { "Company": "Toyota","model": "Premio","year": 2012 }
print(dict_sample)
Output:
{'Company': 'Toyota', 'model': 'Premio', 'year': 2012}
print(x)
Output:
Premio
➢ In this example you can see that we have updated the value for the key"year" from
the old value of 2012 to a new value of 2014.
For example:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012 }
dict_sample.pop("year")
print(dict_sample)
Output:
{’Company’: ’Toyota’, ’model’: ’Premio’}
➢ We invoked that pop() method by appending it with the dictionary name. And, in this
example the entry for "year" in the dictionary will be deleted.
➢ The popitem() method removes the last item of inserted into the dictionary, without
needing to specify the key. Take a look at the following example:
dict_sample = { "Company": "Toyota","model": "Premio","year": 2012}
dict_sample.popitem()
print(dict_sample)
Output:
{’Company’: ’Toyota’, ’model’: ’Premio’}
➢ The last entry into the dictionary was "year". It has been removed after calling the
popitem() function.
➢ But what if you want to delete the entire dictionary? It would be difficult and
cumbersome to use one of these methods on every single key. Instead, you can use the del
keyword to delete the entire dictionary.
For example:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012}
del dict_sample
print(dict_sample)
Output:
NameError: name ’dict_sample’ is not defined
➢ The code returns an error. The reason is we are trying to access the an dictionary which is
doesn't exist since it is has been deleted.
➢ However, your use-case may require you to just remove all dictionary elements and be
left with an empty dictionary.
➢ This can be achieved by calling the clear() function on the dictionary:
dict_sample = { "Company": "Toyota","model": "Premio", "year": 2012 }
dict_sample.clear()
print(dict_sample)
Output:
{}
➢ The code is returns an empty dictionary since all the dictionary elementshave been
removed.
UNIT - V
➢ There are two types of files in Python and each of them are explained below in detail with
examples for your easy understanding.
They are:
• Binary file
• Text file
Note: The above-mentioned modes are for opening, reading or writing text files only.
While using binary files, we have to use the same modes with the letter ‘b’ at the end. So that
Python can understand that we are interacting with binary files.
• ‘wb’ – Open a file for write only mode in the binary format.
• ‘rb’ – Open a file for the read-only mode in the binary format.
• ‘ab’ – Open a file for appending only mode in the binary format.
• ‘rb+’ – Open a file for read and write only mode in the binary format.
• ‘ab+’ – Open a file for appending and read-only mode in the binary format.
Example 1:
fo = open(“C:/Documents/Python/test.txt”, “r+”)
➢ In the above example, we are opening the file named ‘test.txt’ present at the location
‘C:/Documents/Python/’ and we are opening the same file in a read-write mode which
gives us more flexibility.
Example 2:
fo = open(“C:/Documents/Python/img.bmp”, “rb+”)
➢ In the above example, we are opening the file named ‘img.bmp’ present at the location
“C:/Documents/Python/”, But, here we are trying to open the binary file.
There are three ways in which we can read the files in python.
• read([n])
• readline([n])
• readlines()
• Here, n is the number of bytes to be read.
• First, let’s create a sample text file as shown below.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
➢ Here we are opening the file test.txt in a read-only mode and are reading only the first 5
characters of the file using the my_file.read(5) method.
Output:
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Output:
Hello World
Hello Python
Good Morning
➢ Here we have not provided any argument inside the read() function. Hence it will read all
the content present inside the file.
Output:
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
This function returns the first 2 characters of the next line.
Output:
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
➢ Using this function we can read the content of the file on a line by line basis.
Output:
Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
[‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’]
Here we are reading all the lines present inside the text file including the newline characters.
Output:
Output:
Output:
➢ In order to write data into a file, we must open the file in write mode.
➢ We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
• write(string)
• writelines(list)
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’ file.
Before writing data to a test.txt file:
Output:
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
➢ The first line will be ‘Hello World’ and as we have mentioned \n character, the cursor
will move to the next line of the file and then write ‘Hello Python’.
➢ Remember if we don’t mention \n character, then the data will be written continuously in
the text file like ‘Hello WorldHelloPython’
Output:
Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
➢ The above code writes a list of data into the ‘test.txt’ file simultaneously.
Output:
Output:
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
➢ The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new line.
Output:
Example 3:
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.writelines(fruits)
➢ The above code appends a list of data into a ‘test.txt’ file.
Output:
Example 4:
text=["\nHello","\nHi","\nPython"]
my_file=open("C:/Documents/Python/test.txt",mode="a+")
my_file.writelines(text)
print("where the file cursor is:",my_file.tell())
my_file.seek(0)
for line in my_file:
print(line)
➢ In the above code, we are appending the list of data into the ‘test.txt’ file. Here, you can
observe that we have used the tell() method which prints where the cursor is currently at.
seek(offset): The offset takes three types of arguments namely 0,1 and 2.
When the offset is 0: Reference will be pointed at the beginning of the file.
When the offset is 1: Reference will be pointed at the current cursor position.
When the offset is 2: Reference will be pointed at the end of the file.
Output:
remove() method:
➢ We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)
Example 1:
import os
os.remove(“test.txt”)
Here ‘test.txt’ is the file that you want to remove.
Similarly, we can pass the file location as well to the arguments as shown in the below
example
Example 2:
import os
os.remove(“C:/Documents/Python/test.txt”)
Encoding in Files
➢ File encoding represents converting characters into a specific format which only a
machine can understand.
Different machines have different encoding format as shown below.
• Microsoft Windows OS uses ‘cp1252’ encoding format by default.
• Linux or Unix OS uses ‘utf-8’ encoding format by default.
• Apple’s MAC OS uses ‘utf-8’ or ‘utf-16’ encoding format by default.
Let’s see the encoding operation with some examples.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, mode=”r”)
print(“Microsoft Windows encoding format by default is:”, my_file.encoding)
my_file.close()
Output:
Microsoft Windows encoding format by default is cp1252.
➢ Here, I executed my program on the windows machine, so it has printed the default
encoding as ‘cp1252’.
Output:
➢ We can also change the encoding format of a file by passing it as arguments to the open
function.
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, mode=”w”, encoding=”cp437”)
print(“File encoding format is:”, my_file.encoding)
my_file.close()
Output:
File encoding format is: cp437
Output:
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, mode=”w”, encoding=”utf-16”)
print(“File encoding format is:”, my_file.encoding)
my_file.close()
Output:
File encoding format is: utf-16
Output:
Example:
#Let’s create some binary file.
my_file = open(“C:/Documents/Python/bfile.bin”, “wb+”)
message = “Hello Python”
file_encode = message.encode(“ASCII”)
my_file.write(file_encode)
my_file.seek(0)
bdata = my_file.read()
print(“Binary Data:”, bdata)
ntext = bdata.decode(“ASCII”)
print(“Normal data:”, ntext)
➢ In the above example, first we are creating a binary file ‘bfile.bin’ with the read and write
access and whatever data you want to enter into the file must be encoded before you call
the write method.
➢ Also, we are printing the data without decoding it, so that we can observe how the data
exactly looks inside the file when it’s encoded and we are also printing the same data by
decoding it so that it can be readable by humans.
Output:
Binary Data: b’Hello Python’
Normal data: Hello Python
Output:
Output:
Output:
Using split()
➢ We can use a for loop to iterate through the contents of the data file after opening it
with Python’s ‘with’ statement.
➢ After reading the data, the split() method is used to split the text into words.
➢ The split() method by default separates text using whitespace.
with open("examplefile.txt", 'r') as file_data:
for line in file_data:
data = line.split()
print(data)
Output:
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
data = generator_data("examplefile.txt")
for line in data:
print(line.split())
Output:
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
File Positions
➢ There are two more methods of file objects used to determine or get files positions.
tell()
seek()
tell():
➢ This method is used to tell us the current position within the file which means the
next read or write operation will be performed that many bytes away from the start
of the file.
Syntax :
obj.tell()
Example :
"""
Author : ITVoyagers (https://itvoyagers.in/)
seek():
➢ This method is used to change the current position of file.
➢ This method has two main parameters offset and from.
Syntax :
obj.seek(offset,from)
➢ Here, offset argument means the number of bytes to be moved.
➢ from argument is used to specify the reference position from where the bytes needs to be
moved.
c=f.read(s)
print(c)
f.seek(0,2) #goes to end position in file
c=f.read(s)
print(c)
bin_file.write(message_content)
bin_file.seek(0)
bdata = bin_file.read()
print("Binary Data is:", bdata)
ndata = bdata.decode("utf-32")
print("Normal Data is:", ndata)
file.close()
bin_file.close()
Output:
What is the file name? C:/Documents/Python/test.txt
What is the mode of the file? w+
What is the encoding format? cp1252
Size of the file is: 192
Cursor position is at byte: 36
Content of the file is: Hello Python
Good Morning
Good Bye
Data present at the current line is: Good Bye
Binary Data is: b’\xff\xfe\x00\x00G\x00\x00\x00o\x00\x00\x00o\x00\x00\x00d\x00\x00\x00
\x00\x00\x00B\x00\x00\x00y\x00\x00\x00e\x00\x00\x00′
Normal Data is: Good Bye
Output:
ALGORITHM:
Step 1: Start the program.
Step 2: Define the constant PI=3.14.
Step 3: Read the input values length , breath , radius using (len, bre, r) input variables.
Step 4: Calculate the area, perimeter, circumference values by using variables.
area1= len * bre , area2 = PI*r*r , perimeter=2*(len+bre) , circum=2*PI*r.
Step 5: Print the results as area, circumference, perimeter values (area1,area2,perimeter,circum)
using output statements.
Step 6: Stop the program.
FLOWCHART
PROGRAM :
print(‘To find the area , perimeter , circumference calculation using variable , constants , I/O
statements’)
PI=3.14
len=int(input("Enter the Length of rectangle:"))
bre=int(input("Enter the Breadth of rectangle:"))
r=int(input("Enter the Radius of Circle:"))
area1=len*bre
perimeter=2*(len+bre)
area2=PI*r*r
circum=2*PI*r
print("Area of Rectangle =",area1)
print("Perimeter of Rectangle =",perimeter)
print("Area of Circle =",area2)
print("Circumference of Circle =",circum)
OUTPUT:
To find the area , perimeter , circumference calculation using variable , constants , I/O statements:
RESULT:
Thus the above program has executed successfully and outputs are verified.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input values a,b,x.
Step 3: Apply the input variable values to different expressions using different operators.
Step 4: Print the each expression and condition results to the output screen.
Step 5: Stop the program.
FLOWCHART:
PROGRAM:
c=((a+b)*(a-b)/(a))
d=((a**b)+(a//b))
print('\nResult for using Arithmetic operators : ' , c , d)
a += b
print('Result for using Assignment Operator: ', (a))
print('Result for using Relational & Logical operators : ' , ((a > b) and (c <= d) or (b>=c)))
print('Result for using Bitwise operators (& , | , ~ , ^) : ' , (a&b) , (a|b) , (~a) , (a^b))
print('Result for using Bitwise Shift operators (<< , >>) : ' , (a<<2) , (b>>2))
print('Result for using Identity operators : ' , (a is b) , (c is not d))
print('Result for using Membershif Operators : ' , ('H' in x) , ('hello' not in x))
OUTPUT:
Expressions Evaluations using operators
Enter the First Number:4
Enter the Second Number:2
Enter the String:hello
RESULT:
Thus the above program has executed successfully and outputs are verified.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input values a,b,c.
Step 3: Find the biggest number from the given three numbers using nested if statements
Step 3.1: Check the input condition(if(a>b)) if it’s true means check (if(a>c)) then assign ‘a’ value
otherwise assign ‘c’ value then check(if(b>c)) then assign ‘b’ value otherwise assign ’c’ value.
Step 3.2: Print the biggest number value.
Step 4: Find the smallest number from the given three numbers using if elif else statement.
Step 4.1: Check the if condition(if(a<b and a<c)) then its true means assign ‘a’ value otherwise false
means check (if(b<c)) then assign ‘b’ value otherwise assign ‘c’ value.
Step 4.2: Print the smallest number value.
Step 5: Stop the program.
FLOWCHART:
PROGRAM:
print('Finding Biggest and Smallest number using conditional statements')
print('\nTo Find the Biggest among the given three numbers for using Nested IF sttement')
print('and To Find the Smallest among the given three numbers for using IF_ElIF_ELSE sttement')
a=int(input('Enter the Number1: '))
b=int(input('Enter the Number2: '))
c=int(input('Enter the Number3:' ))
if (a>b):
if (a>c):
g=a
else:
g=c
else:
if (b>c):
g=b
else:
g=c
print('The Largest Number is = ',g)
s=0
if (a < b and a < c ):
s=a
elif (b < c):
s=b
else :
s=c
print('The Smallest Number is =',s)
OUTPUT:
Finding Biggest and Smallest number using conditional statements
To Find the Biggest among the given three numbers for using Nested IF sttement
and To Find the Smallest among the given three numbers for using IF_ElIF_ELSE sttement
Enter the Number1: 25
Enter the Number2: 45
Enter the Number3: 15
The Largest Number is = 45
The Smallest Number is = 15
RESULT: Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program for finding the reverse of digits in the given number and also
find the sum of n natural numbers using looping statements.
ALGORITHM:
Step 1:Start the program.
Step 2: Read the input integer number.
Step 3: Assign revs_number=0.
Step 3.1: Check the while loop condition while(number>0) , Inside the body of the loop perform the
following calculations ( remainder = number%10 , revs_number=(revs_number*10)+remainder
, number = number//10)
Step 3.2: Print reverse digits of the given number.
Step 4: Read the input number num.
Step 5: Perform the for loop (for value in range(1,num+1)) then inside the loop body do the
calculation(sum = sum+value).
Step 5.1: Print the sum value.
Step 6: Stop the program.
FLOWCHART:
PROGRAM
print('Program For Demonstrating the various looping statements')
print('\n Print the reverse digits of given number using while loop')
number = int(input('Enter the integer number: '))
revs_number = 0
while (number > 0):
remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10
print('The reverse number is : {}'.format(revs_number))
print('\n Sum of N natural numbers using for loop')
num = int(input("Please enter the number: "))
sum = 0
for value in range(1, num + 1):
sum = sum + value
print('the sum of first',num,'natural number is =',sum)
OUTPUT:
Program For Demonstrating the various looping statements
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program for finding the square root of the given numbers using Jump
statements.
ALGORITHM:
Step 1: Start the program.
Step 2: import the math package.
Step 3: Perform the while loop condition while(1).
Step 4: Inside the while loop body read the input number and check the if condition (if(num == 999)
it’s true means break the reading inputs otherwise read the input num again.
Step 5: if(num<0) its true means the square root may not be calculated for negative numbers
otherwise print the squart value using (math.sqrt(num)) function.
Step 6: Stop the program.
FLOWCHART:
PROGRAM:
import math
print(‘To find the Square root of given numbers using Jump Statements\n’)
while(1):
num = int(input('Enter the Number:'))
if(num == 999):
break
elif (num<0):
print('Square root of negative numbers cannot be calculated')
continue
else:
print('Square root of',num,'=',math.sqrt(num))
OUTPUT:
To find the Square root of given numbers using Jump Statements
Enter the Number:81
Square root of 81 = 9.0
Enter the Number:78
Square root of 78 = 8.831760866327848
Enter the Number:-49
Square root of negative numbers cannot be calculated
Enter the Number:999
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program for swapping of two numbers using user defined function.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the function swap(x,y), Inside the function print the before swapping the numbers and
swap the numbers (x,y = y,x) then return the x,y value to function declaration part.
Step 3: Read the user inputs a,b values assign the values to swap(a,b).
Step 4: Print the After swapping values a,b.
Step 5: Stop the program.
Step 6: Stop the program.
FLOWCHART:
PROGRAM:
def swap(x,y):
print('Before swapping a :',x)
print('Before swapping b :',y)
x,y=y,x
return x,y
print('Swapping of two numbers using function\n')
a=int(input('Enter the a value : '))
b=int(input('Enter the b value : '))
a,b=swap(a,b)
print('After swapping a becomes :',a)
print('After swapping b becomes :',b)
OUTPUT:
Swapping of two numbers using function
Enter the a value : 80
Enter the b value : 40
Before swapping a : 80
Before swapping b : 40
After swapping a becomes : 40
After swapping b becomes : 80
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program to find the factorial value of given input using Recursion
function.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the recr_factorial(n) function.
Step 3: Inside the function check (if(n==1) then return n value otherwise
return(n*recur_factorial(n-1) value.
Step 4: Read the user input value num.
Step 5: Check the if conditions (if(n<0)) then print factorial not calculated for negative number
otherwise (if(n==0)) then print factorial value is 1 otherwise the value passed to
(recur_factorial(num)) function.
Step 6: Stop the program.
FLOWCHART
PROGRAM:
def recur_factorial(n):
if (n == 1):
return n
else:
return n*recur_factorial(n-1)
print('Factorial Calculation Using Recursive Function')
num =int(input('Enter the Number : '))
if (num < 0):
print("Sorry, factorial does not exist for negative numbers")
elif (num == 0):
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
OUTPUT:
Factorial Calculation Using Recursive Function
Enter the Number : 5
The factorial of 5 is 120
RESULT:
Thus the above program has executed successfully and outputs are verified.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the NumArr = [ ] and Read the total number of array element value Number
Step 3: For using for loop as like (for i in range(1,Number +1) ) inside the loop body read the user
input values for an array and append it into NumArr.
Step 4: Do the For loop (for I in range(Number) and (for j in range(i+1,Number).
Step 5: Inside the nested for loop check the condition (if(NumArr[i]>NumArr[j]) then do the
following assignments: ( Temp = NumArr[i] ,NumArr[i] = NumArr[j] , NumArr[j] = temp)
Step 6: Print the sorted numbers in ascending order.
Step 7: Assigh (sort_numbers = sorted(NumArr,reverse = True)) and print the result of sorted
numbers in decending order.
Step 8: Stop the Program.
FLOWCHART:
PROGRAM:
print('Sorting the Numbers using Arrays')
NumArr = [ ]
Number = int(input('Please enter the Total Number of Array Elements: '))
for i in range(1, Number + 1):
value = int(input('Please enter the Value of %d Element : ' %i))
NumArr.append(value)
for i in range (Number):
for j in range(i + 1, Number):
if(NumArr[i] > NumArr[j]):
temp = NumArr[i]
NumArr[i] = NumArr[j]
NumArr[j] = temp
print('Element After Sorting Array Elements in Ascending Order is : ', NumArr)
sort_numbers = sorted(NumArr, reverse=True)
print('\nElements After Sorting Array Elements in Descending Order is :',sort_numbers)
OUTPUT:
Sorting the Numbers using Arrays
Please enter the Total Number of Array Elements: 5
Please enter the Value of 1 Element : 30
Please enter the Value of 2 Element : 50
Please enter the Value of 3 Element : 10
Please enter the Value of 4 Element : 20
Please enter the Value of 5 Element : 40
Element After Sorting Array Elements in Ascending Order is : [10, 20, 30, 40, 50]
Elements After Sorting Array Elements in Descending Order is : [50, 40, 30, 20, 10]
RESULT:
Thus the above program has executed successfully and outputs are verified.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the function (isPalindrome(string)).
Step 3: Check the condition (if(string == string[::-1)) if it’s true means print the given string is
palindrome otherwise print the given string is not palindrome.
Step 4: Read the user input string and pass the input to function(ispalindrome(string)) and print the
function returned output.
Step 5: Stop the program.
FLOWCHART:
PROGRAM:
print('Palindrome Checking using Strings\n')
def isPalindrome(string):
if(string == string[::-1]) :
return'The given string is a palindrome.'
else:
return'The given string is not a palindrome.'
string = input('Enter the input string:')
print(isPalindrome(string))
OUTPUT:
Palindrome Checking using Strings
Enter the input string: AMMA
The given string is a palindrome.
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program to generate the Fibonacci series using modules.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a module Fibonacci , Inside the module define the function (fib(nturms)).
Step 3: Inside the function declare the required variables and check the condition if(nterms<=0) if
it’s true means please enter positive integer will be printed otherwise go for next step
Step 4: Check (if(nterms == 1)) then print the (n1) value otherwise check the while loop
(while(count<nterms)) inside the loop body print (n1) value and do the following
assignments(nth = n1 + n2 , n1 = n2 , n2 = nth) then increase the count value by 1 up to the
while condition getting false onwards.
Step 5: Import the above module to another program.
Step 6: Read the user input value and pass it to the module (Fibonacci.fib(num)) then print the output
of the module.
Step 7: Stop the program.
FLOWCHART:
PROGRAM:
# Module (fibonacci.py)
def fib(nterms):
n1, n2 = 0, 1
count = 0
if (nterms <= 0):
print('Please enter a positive integer ')
elif (nterms == 1):
print('Fibonacci sequence upto',nterms,':')
print(n1)
else:
print('Fibonacci sequence:')
while (count < nterms):
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
fibprog.py
import fibonacci
print('Fibonacci Series using Modules\n')
num=int(input('Enter any number to print Fibonacci series : '))
fibonacci.fib(num)
OUTPUT:
Fibonacci Series using Modules
Enter any number to print Fibonacci series : 6
Fibonacci sequence:
0
1
1
2
3
5
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program for searching the element in given list using Lists.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the elements from the user input and evaluate then store the inputs in lst variable.
Step 3: Calculate the length of the created list and Read the searching element from the user input
and assign to element variable.
Step 4: Do the for loop condition (for i in range (0,length)).
Step 5: Inside the for loop body check the condition (if(element= = lst[i])) if it’s true means print the
searching element present in the list otherwise break the above process, then print searching
element is presented in the list.
Step 6: Stop the program.
FLOWCHART:
PROGRAM:
print('Searching Element in List\n')
lst=eval(input('Enter list:'))
length=len(lst)
element=int(input('Enter element to be searched for:'))
for i in range(0,length):
if element==lst[i]:
print(element,'found at index',i)
break
else:
print(element,'not found in given list')
OUTPUT:
Searching Element in List
Enter list:5,15,25,35,45,55
Enter element to be searched for:35
35 found at index 3
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program to find the sum of given positive numbers only using Tuples.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input values from the user It may contain the positive and negative numbers where
separated by commas.
Step 3: define the function (sum_pos(*args)) , Inside the function assign initial total value tot = 0.
Step 4: Do the for loop process (for i in args) , Inside the loop body check the condition (if(i>0) then
calculate total value tot += I and return the result.
Step 5: Print the sum of positive numbers output(sum_pos(*tp)).
Step 6: Stop the program.
FLOWCHART:
PROGRAM
print('Find the sum of given positive Numbers only using Tuple\n')
user_input = input('Enter space-separated integers: ')
tp = tuple(int(item) for item in user_input.split())
def sum_pos(*args):
tot = 0
for i in args:
if (i>0):
tot += i
return tot
print('The sum of Positive Numbers =',sum_pos(*tp))
OUTPUT:
Find the sum of given positive Numbers only using Tuple
Enter space-separated integers: 10 -20 35 -40 55 60 -32 25
The sum of Positive Numbers = 185
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program to print the employee salary details using Dictionary.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a dictionary employees={ } and get maximum length of the dictionary.
Step 3: Do the while condition (while(len(employees)<max_length)) , Inside the loop body read the
employees name and salary details.
Step 4: Check the condition(if name not in employees) then assign employees[name]=salary and
print employees dictionary details.
Step 5: Check the condition (if employees[key]= = max(employees.values( ))) and print which
employees getting high salary.
Step 6: Stop the program.
FLOWCHART:
PROGRAM:
print('Employee salary details checking using Dictionary\n')
employees = { }
max_length = int(input('Please enter the Employees count: '))
while (len(employees) < max_length):
name = input('Enter employees name: ')
salary = input('Enter employees salary: ')
if name not in employees:
employees[name] = salary
print(employees)
print('The highest salary getting employee is')
print([key for key in employees.keys() if employees[key]==max(employees.values())])
OUTPUT:
Employee salary details checking using Dictionary
Please enter the Employees count: 3
Enter employees name: S.Prasanth
Enter employees salary: 30000
Enter employees name: K.Sathishwaran
Enter employees salary: 45000
Enter employees name: N.Anmol
Enter employees salary: 50000
{S.'Prasanth': '30000', 'K.Sathishwaran': '45000', 'N.Anmol': '50000'}
The highest salary getting employee is
['N.Anmol']
RESULT:
Thus the above program has executed successfully and outputs are verified.
AIM:
To create a python program to copied the content from another file using Files.
ALGORITHM:
Step 1: Start the program.
Step 2: Import sys module, Read the input filename with its extension.
Step 3: Open the source file and write the content into the source file using writelines statement.
Step 4: Open the file1.txt in ‘r’ and file2.txt in ‘w’ mode.
Step 5: Assign num = 1 , Do the for loop (for line in file1) inside the loop body write the contents
into file2.txt and increase num = num +1.
Step 6: Close file1 , file2.
Step 7: Open file2.txt and read the contents from the file and print the contents in to user output
screen then close file2.txt.
Step 8: Stop the program.
FLOWCHART:
PROGRAM:
import sys
print('Copied the contents from one file into another file using File Methods\n')
file_name = input('Filename with extension, e.g. example.txt: ')
print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit')
with open(file_name, 'w', encoding='utf-8') as my_file:
my_file.writelines(sys.stdin.readlines( ))
file1 = open('file1.txt','r')
file2 = open('file2.txt','w')
num = 1
for line in file1:
file2.write(str(num) + ': ' +line)
num = num + 1
file1.close( )
file2.close( )
file2 = open('file2.txt','r')
OUTPUT:
Copied the contents from one file into another file using File Methods
Filename with extension, e.g. example.txt: file1.txt
Press CTRL + D (Unix) or CTRL + Z (Windows) to exit
ARIGNAR ANNA COLLEGE
WELCOME TO BCA
^Z
File2 contents are copied from file1 suessfully!
File2 copied contents are
1: ARIGNAR ANNA COLLEGE
2: WELCOME TO BCA
RESULT:
Thus the above program has executed successfully and outputs are verified.