II B.
Tech year I semester(ME)
PYTHON PROGRAMMING Lab Manual
(SKILL ENHANCEMENT COURSE)
Prepared by
K. SURENDRA
Assistant Professor(Adhoc),
Dept. C.S.E, JNTUACEA.
II Year II B.Tech. ME– I Semester
L T P C
0 1 2 2
(23A05304) PYTHON PROGRAMMING(SKILLENHANCEMENTCOURSE)
Course Objectives: The main objectives of the course are to
Introduce core programming concepts of Python programming language.
Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries
Implement Functions ,Modules and Regular Expressions in Python Programming and to create practical
and contemporary applications using these
Course Outcomes: After completion of the course ,students will be able to
Classify data structures of Python(L4)
Apply Python programming concepts to solve a variety of computational problems(L3)
Understand the principles of object-oriented programming(OOP) in Python including classes, objects,
inheritance, polymorphism, and encapsulation, and apply them to design and implement Python
programs(L3)
Become proficient in using commonly used Python libraries and frameworks such asJSON ,XML, NumPy,
pandas(L2)
Exhibit competence in implementing and manipulating fundamental data structures such as lists, tuples
,sets, dictionaries (L3)
Propose new solutions to computational problems(L6)
UNTI-I: History of Python Programming Language, Thrust Areas of Python, Installing
Anaconda Python Distribution, Installing and Using Jupyter Notebook.
Parts of Python Programming Language: Identifiers, Keywords, Statements and
Expressions, Variables, Operators, Precedence and Associativity, Data Types, Indentation,
Comments, Reading Input, Print Output, Type Conversions, the type () Function and Is
Operator, Dynamic and Strongly Typed Language.
Control Flow Statements: if statement, if-else statement, if...elif…else, Nested if statement,
while Loop, for Loop, continue and break Statements, Catching Exceptions Using try and
except Statement.
Sample Experiments:
1. Write a program to find the largest element among three Numbers
2. Write a Program to display all prime numbers with in an interval
3. Write a program to swap two numbers without using a temporary variable.
4. Demonstrate the following Operators in Python with suitable examples.
i) ArithmeticOperatorsii)RelationalOperatorsiii)AssignmentOperatorsiv)LogicalOperato
rsv)BitwiseOperatorsvi)TernaryOperatorvii)MembershipOperators
viii) Identity Operators
5. Write a program to add and multiply complex numbers
6. Write a program to print multiplication table of a given number.
UNIT-II: Functions: Built-In Functions, Commonly Used Modules, Function Definition and
Calling the function ,return Statement and void Function, Scope and Lifetime of Variables,
Default Parameters, Keyword Arguments, *args and **kwargs, Command Line Arguments.
Strings: Creating and Storing Strings, BasicString Operations, Accessing Characters in String
by Index Number, String Slicing and Joining, String Methods ,Formatting Strings.
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In Functions
Used on Lists ,List Methods, del Statement.
SampleExperiments:
7. Write a program to define a function with multiple return values.
8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using any library functions.
10. Write a program to check if the sub string is present in a given string or not.
11. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii.slicing
12. Write a program to perform any 5 built-in functions by taking any list.
UNIT-III: Dictionaries: Creating Dictionary, Accessing and Modifying key: value Pairs in
Dictionaries, Built-In Functions Used on Dictionaries, Dictionary Methods, del Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple () Function, Indexing and
Slicing in Tuples, Built-In Functions Used on Tuples, Relation between Tuples and Lists,
Relation between Tuples and Dictionaries, Using zip( ) Function, Sets, Set Methods,
Frozenset.
Sample Experiments:
13. Write a program to create tuples (name, age, address, college) for at least two members
and concatenate the tuples and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (Nocontrolflow allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new key-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary.
UNIT-IV: Files: Types of Files, Creating and Reading Text Data, File Methods to Read and
Write Data, Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV
Files, Python os and os .path Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python, Creating
Objects in Python, Constructor Method, Classes with Multiple Objects, Class Attributes Vs
Data Attributes, Encapsulation, Inheritance, Polymorphism.
<Sample Experiments:
18. Write a program to sort words in a file and put them in another file. The output file
Should have only lower-case words, so any upper-case words from source must be
lowered.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words and lines in a file.
21. Write a program to create, display, append, insert and reverse the order of the items
in the array.
22. Write a program to add, transpose and multiply two matrices.
23. Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
UNIT-V: Introduction to Data Science: Functiona Programming, JSON and XML in
Python, NumPy with Python, Pandas.
Sample Experiments:
24. Python program to check whether a JSON string contain complex object or not.
25. Python Program to demonstrate NumPy arrays creation using array () function.
26. Python program to demonstrate use ofndim, shape, size,dtype.
27. Python program to demonstrate basic slicing, integer and Boole an indexing.
28. Python program to find min, max ,sum, cumulative sum of array
29. Create a dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame
and explore the data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
30. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in mat plotlib
Reference Books:
1. Gowri shankar S, Veena A.,Introduction to Python Programming,CRCPress.
2. Python Programming, SSridhar, JIndumathi, VMHariharan ,2nd Edition, Pearson,
2024
3. Introduction to Programming Using Python, Y.Daniel Liang ,Pearson.
Online Learning Resources/VirtualLabs:
1. https://www.coursera.org/learn/python-for-applied-data-science-ai
https://www.coursera.org/learn/python?specialization=python#syllabus
Installing Anaconda Python Distribution
Anaconda is a free and open source distribution of the Python programming language for data
science and machine-learning related applications such as large-scale data processing, predictive
analytics, and scientific computing, that aims to simplify package management and deployment.
Package versions are managed by the package management system conda, which makes it quite
simple to install, run, and update complex data science and machine learning software libraries like
Scikit-learn, PyTorch, TensorFlow, and SciPy. Anaconda Distribution is used by over 6 million
users, and it includes more than 250 popular data science packages suitable for Windows, Linux,
and MacOS.
The steps described here work on the Windows 10 OS.
Step 1: Go to the link https://www.continnum.io/downloads. You have the option to download the
32-bit or the 64-bit version of either Python 2.7 or Python 3.6 supported Anaconda distribution.
At the time of writing this book, Anaconda supported Python 3.6 version. As and when a new
version of Python is released, Anaconda distribution will be updated to newer releases. In this book
64-bit Anaconda distribution supporting Python 3.6 is used to execute programs, so download the
same version.
Step 2: Click on the executable file of Anaconda Python distribution which you have downloaded
and the setup screen will start loading.
Step 3: You will get a welcome screen as shown in FIGURE 1. Click on Next button.
FIGURE-1
Step 4: You will get a License Agreement Screen, read the licensing terms and click on I Agree
button.
Step 5: Assuming that you are the only user on your system, select Just Me radio button (FIGURE
2). Click on Next button.
FIGURE-2
Step 6: You need to choose a location to install Anaconda Python distribution. The default
installation will be under Users folder. Change the destination folder to C:\Anaconda3 to install
Anaconda and click on Next button (FIGURE 3).
FIGURE-3
Step 7: In the Advanced Installation Options screen, select all the check boxes. Ignore the
warnings and click on Install button (FIGURE 4).
FIGURE-4
Step 8: This starts the installation of Anaconda Python Distribution and once the installation is
complete, click on Next button.
Step 9: Finish the setup by clicking on Finish button.
Step 10: To check whether the installation is working properly or not, go to the command prompt
and type python. You should see a series of lines and a prompt as shown in FIGURE 5. This is
Python Interactive mode. Here, the three greater-than signs “>>>” is the primary prompt of the
interactive mode.
FIGURE-5
Installing PyCharm IDE to Set Up a Python Development Environment
PyCharm is an Integrated Development Environment (IDE) used for Python programming
language. It is developed by the Czech company JetBrains. It provides code analysis, a graphical
debugger, an integrated unit tester, integration with version control systems and supports web
development with Django web framework. PyCharm is cross-platform, with the availability of
Windows, MacOS and Linux versions. The Community Edition is released under the Apache
License and there is also Professional Edition released under a proprietary license with added
features like scientific tools, web development, Python Web Frameworks, Database and SQL
support. PyCharm is designed by programmers, for programmers, to provide all the tools you need
for productive Python development.
The steps described here works on the Windows 10 OS.
Step 1: Go to the link https://www.jetbrains.com/PyCharm/download/. You have the option to
download either the PyCharm Professional Edition or the PyCharm Community Edition. If you
have purchased a license for Professional Edition then go for it. Otherwise, you can download the
Community edition which will suffice most of our requirements. All the programs in this book
have been executed using PyCharm Community Edition IDE, so download the same edition.
Step 2: Click on the executable file which you have downloaded. You will be presented with the
PyCharm Community Edition Setup screen. Click on Next button.
Step 3: Now you will be presented with Choose Install Location screen. Go with the default
destination folder to install PyCharm Community Edition. Click on Next button.
Step 4: Select all the check boxes in the Installation Options screen except for the 32-bit launcher
check box (since Windows 10 is a 64-bit OS, you don’t need 32-bit launcher) and click on Next
(FIGURE 2.1).
FIGURE 2.1
Step 5: Go with the default Start Menu Folder as shown on the screen and click on Install button.
It will take some time for the installation to finish. Once the installation is done click on the Finish
button.
Step 6: You will be asked whether you want to import previous PyCharm settings. Since we are
starting on a clean slate, let’s select the second radio button as shown in FIGURE 2.2 and click on
OK button.
FIGURE 2.2
Step 7: You will be prompted with a Windows Security Alert. Do not worry about it. Click on
Allow Access Button. Next screen will be Python community edition initial configuration. Let the
default settings remain as it is and click on OK button. After you have completed initial PyCharm
configuration, a customization screen will be displayed as shown in FIGURE 2.3; click on Skip
Remaining and Set Defaults button.
FIGURE 2.3
Step 8: In the next screen, click on Configure pull down list and select Settings option as shown in
FIGURE 2.4.
FIGURE 2.4
Step 9: In the Default Settings screen, on the left pane, click on Project Interpreter as shown in
FIGURE 2.5.
FIGURE 2.5
On the right pane, in the Project Interpreter option, click on the button having toothed wheel icon
and select Add. In the Add Python Interpreter screen, on the left pane, click on System Interpreter
and select the Python interpreter path from the Interpreter pull down list as shown in FIGURE 2.6.
Click on OK button.
FIGURE 2.6
Step 10: It will take some time to list all the packages. Once done click on OK button.
Step 11: You will be again presented with the Welcome screen as shown in FIGURE 2.4. Now, to
work with PyCharm IDE, click on Create New Project option.
Creating and Running Your First Python Project
Before you start make sure that the following prerequisites are met:
• You are working with PyCharm Community Edition or Professional.
• You have installed Python 3.6 supported Anaconda distribution.
Below steps describe the process of creating and running a Python project.
Step 1: Click on the JetBrains Community Edition shortcut icon and you will be presented with a
welcome screen (FIGURE 2.4) and click on Create New Project. This screen is presented initially
when you are creating a project for the first time. For the subsequent project creation, Go to File
→ New Project and go to Step 2. Create a folder called PyWork in C:\ drive.
Step 2: For the Location option, browse to the PyWork folder which you had created in C:\ drive
in Step 1. Now give a name to your Python Project. For the purpose of the demo, the project name
is given as FirstProgram (FIGURE 2.7). Expand the project Interpreter and click on Existing
interpreter radio button. Select Python Interpreter path from Interpreter pull down list if it is not
already selected. Then, click on the Create button.
FIGURE 2.7
Step 3: On the left pane of the presented screen you can see the Project Name, which in our case is
FirstProgram. Right-click on FirstProgram → Select New → Select Python File as shown in
FIGURE 2.8.
FIGURE 2.8
Step 4: Give a name to the Python File. For the purpose of this demo, let’s name it as HelloWorld
as shown in FIGURE 2.9. No need to specify any extension. The PyCharm IDE itself will attach
the .py extension to the file name which you have specified. Click on OK button.
FIGURE 2.9
Step 5: On the left pane double click on the File name which you have created (in our case it is
HelloWorld.py). This should open an empty file on the right side of the editor in which you type
the following statement (FIGURE 2.10).
print("Hello World")
FIGURE 2.10
Step 6: To execute the above code, go to Run menu → and click on Run as shown in
FIGURE 2.11.
FIGURE 2.11
Another way of executing the above program is to right-click on the Python File Name (in our case
it is HelloWorld.py) and select Run “HelloWorld”.
Step 7: In the below screen (FIGURE 2.12), you can see the output in the output window of the
PyCharm IDE.
FIGURE 2.12(Output of HelloWorld.py program.)
Step 8: You can add multiple Python files to the project and execute them individually.
Create another Python File by following the steps 3, 4 and 5. Name the Python file as
SecondPythonFile and in the editor type,
print("This is second file")
Right-click on the SecondPythonFile.py file and select Run “SecondPythonFile” to execute.
Installing and Using Jupyter Notebook
Jupyter Notebook is one of the many possible ways to interact with Python and the scientific
libraries. Jupyter Notebook is an open source web application that uses a browser based interface
to Python with
• The choice to create and share documents.
• The ability to write and execute Python code.
• Formatted output in the browser, including tables, figures, equation, visualizations, etc.
• The option to mix in formatted text and mathematical expressions.
Because of these possibilities, Jupyter is fast turning into a major player in the scientific computing
ecosystem.
Starting Jupyter Notebook
Step 1: Once you have installed Anaconda, you can start the Jupyter Notebook.
Anaconda conveniently installs Python, the Jupyter Notebook, and other commonly used packages
for scientific computing and data science. For demo purpose let’s create a folder called
JupyterExample in C:\ drive. Invoke command prompt and navigate to the folder by issuing the
command cd C:\JupyterExample.
Your Jupyter Notebook will be saved in this folder. You can start Jupyter Notebook by issuing the
following command in the command prompt as shown in FIGURE 3.1.
jupyter notebook
FIGURE 3.1(Command to start Jupyter Notebook.)
You should see a series of lines in the command prompt as seen in FIGURE 3.2. The output tells us
the notebook is running at http://localhost:8888/ where localhost is the name of the local machine
and 8888 refers to port number 8888 on your computer. Thus, the Jupyter kernel is listening for
Python commands on port 8888 of our local machine.
FIGURE 3.3 (Output of jupyter notebook command.)
Your default browser has also opened up with a web page that looks something like FIGURE 3.3.
What you see here is called the Jupyter dashboard. If you look at the URL at the top, it should be
localhost:8888 or similar, matching the message above.
FIGURE 3.3 (Jupyter dashboard.)
Step 2: Assuming all this has worked OK, you can now click on New pull-down list at top right
and select Python 3 option (FIGURE 3.4).
FIGURE 3.4 (Creating new Jupyter Notebook.)
Step 3: Here’s what shows up on our machine. From the previous step, a new Jupyter Notebook
for Python is created but is still Untitled (FIGURE 3.5). The blue border around the cell indicates
that the particular cell is selected and you are in command mode. In command mode, you can cut,
copy, paste and insert a new cell.
FIGURE 3.5 (Untitled Jupyter Notebook.)
To rename the notebook click on Untitled at the top. A Rename Notebook window pops up. Enter a
name for the notebook. Let’s name the notebook as My_First_Notebook (FIGURE 3.6). Click on
Rename button. Notebook gets saved as My_First_Notebook.ipynb with .ipynb extension in
C:\JupyterExample folder.
FIGURE 3.6 (Rename Jupyter Notebook.)
Step 4: The notebook itself consists of cells. Notice that in the FIGURE 3.7 the cell is surrounded
by a green border. It means that the cell is in edit mode and you are permitted to type text into the
selected cell. The edit mode is invoked when you click in the code area of that cell. You can switch
to command mode from edit mode by pressing Esc key.
FIGURE 3.7 (Jupyter Notebook in edit mode.)
You can type in Python code and it will appear in the cell. Executing the code in this cell can be
done by either clicking on the Run button or hitting Alt + Enter (FIGURE 3.8).
FIGURE 3.8 (Executing Python code in Jupyter Notebook.)
UNIT-1
1. Write a program to find the largest element among three Numbers.
# Function to find the largest of three numbers
def find_largest(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
return largest
# Input three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Find the largest number
largest_number = find_largest(num1, num2, num3)
# Display the largest number
print(f"The largest number is: {largest_number}")
Output:-
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
The largest number is: 30.0
2. Write a Program to display all prime numbers within an interval
Code:-
# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Function to find and display all prime numbers within an interval
def display_primes(start, end):
print(f"Prime numbers between {start} and {end} are:")
for num in range(start, end + 1):
if is_prime(num):
print(num, end=" ")
# Input the interval
start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))
# Display all prime numbers in the given interval
display_primes(start, end)
Output:-
Enter the start of the interval: 10
Enter the end of the interval: 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29
3. Write a program to swap two numbers without using a temporary variable.
Code:-
# Function to swap two numbers
def swap_numbers(a, b):
print(f"Before swapping: a = {a}, b = {b}")
# Swapping without using a temporary variable
a=a+b
b=a-b
a=a-b
print(f"After swapping: a = {a}, b = {b}")
# Input two numbers
a = int(input("Enter the first number (a): "))
b = int(input("Enter the second number (b): "))
# Swap the numbers
swap_numbers(a, b)
Output:-
Enter the first number (a): 10
Enter the second number (b): 20
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators
iv) Logical Operators v) Bit wise Operators vi) Ternary Operator
vii) Membership Operators viii) Identity Operators
Solutions:-
i) Code:-
a = 10
b=3
print("Addition:", a + b) # Output: 13
print("Subtraction:", a - b) # Output: 7
print("Multiplication:", a * b) # Output: 30
print("Division:", a / b) # Output: 3.3333
print("Floor Division:", a // b) # Output: 3
print("Modulus:", a % b) # Output: 1
print("Exponentiation:", a ** b) # Output: 1000
Output:-
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000
ii) Code:-
x = 15
y = 10
print("Equal:", x == y) # Output: False
print("Not Equal:", x != y) # Output: True
print("Greater than:", x > y) # Output: True
print("Less than:", x < y) # Output: False
print("Greater than or equal:", x >= y) # Output: True
print("Less than or equal:", x <= y) # Output: False
Output:-
Equal: False
Not Equal: True
Greater than: True
Less than: False
Greater than or equal: True
Less than or equal: False
iii) Code:-
c=5
c += 3 #c=c+3
print("c += 3:", c) # Output: 8
c -= 2 #c=c-2
print("c -= 2:", c) # Output: 6
c *= 4 #c=c*4
print("c *= 4:", c) # Output: 24
c /= 3 #c=c/3
print("c /= 3:", c) # Output: 8.0
c %= 5 #c=c%5
print("c %= 5:", c) # Output: 3.0
c **= 2 # c = c ** 2
print("c **= 2:", c) # Output: 9.0
c //= 3 # c = c // 3
print("c //= 3:", c) # Output: 3.0
Output:-
c += 3: 8
c -= 2: 6
c *= 4: 24
c /= 3: 8.0
c %= 5: 3.0
c **= 2: 9.0
c //= 3: 3.0
iv) Code:-
p = True
q = False
print("p AND q:", p and q) # Output: False
print("p OR q:", p or q) # Output: True
print("NOT p:", not p) # Output: False
Output:-
p AND q: False
p OR q: True
NOT p: False
v) Code:-
m = 5 # (binary: 0101)
n = 3 # (binary: 0011)
print("m & n:", m & n) # AND operation (Output: 1 -> binary: 0001)
print("m | n:", m | n) # OR operation (Output: 7 -> binary: 0111)
print("m ^ n:", m ^ n) # XOR operation (Output: 6 -> binary: 0110)
print("~m:", ~m) # NOT operation (Output: -6 -> binary: ...1010)
print("m << 1:", m << 1) # Left Shift (Output: 10 -> binary: 1010)
print("m >> 1:", m >> 1) # Right Shift (Output: 2 -> binary: 0010)
Output:-
m & n: 1
m | n: 5
m ^ n: 6
~m: -6
m << 1: 10
m >> 1: 2
vi)Code:-
a = 20
b = 30
# Syntax: value_if_true if condition else value_if_false
max_value = a if a > b else b
print("Maximum value is:", max_value) # Output: 30
Output:-
Maximum value is: 30
vii) Code:-
my_list = [1, 2, 3, 4, 5]
print("3 in my_list:", 3 in my_list) # Output: True
print("6 not in my_list:", 6 not in my_list) # Output: True
Output:-
3 in my_list: True
6 not in my_list: True
viii) Code:-
x = [1, 2, 3]
y = [1, 2, 3]
z=x
print("x is y:", x is y) # Output: False (Different objects)
print("x is z:", x is z) # Output: True (Same object)
print("x is not y:", x is not y) # Output: True
Output:-
x is y: False
x is z: True
x is not y: True
5. Write a program to add and multiply complex numbers
Code:-
# Function to add two complex numbers
def add_complex(c1, c2):
return c1 + c2
# Function to multiply two complex numbers
def multiply_complex(c1, c2):
return c1 * c2
# Input two complex numbers
c1 = complex(input("Enter the first complex number (e.g., 2+3j): "))
c2 = complex(input("Enter the second complex number (e.g., 4+5j): "))
# Perform addition and multiplication
sum_result = add_complex(c1, c2)
product_result = multiply_complex(c1, c2)
# Display the results
print(f"The sum of {c1} and {c2} is: {sum_result}")
print(f"The product of {c1} and {c2} is: {product_result}")
Output:-
Enter the first complex number (e.g., 2+3j): 2+3j
Enter the second complex number (e.g., 4+5j): 5+6j
The sum of (2+3j) and (5+6j) is: (7+9j)
The product of (2+3j) and (5+6j) is: (-8+27j)
6. Write a program to print multiplication table of a given number.
Code:-
# Function to print the multiplication table
def print_multiplication_table(n):
print(f"Multiplication Table of {n}:")
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
# Input the number for which the table should be printed
number = int(input("Enter the number: "))
# Print the multiplication table
print_multiplication_table(number)
Output:-
Enter the number: 23
Multiplication Table of 23:
23 x 1 = 23
23 x 2 = 46
23 x 3 = 69
23 x 4 = 92
23 x 5 = 115
23 x 6 = 138
23 x 7 = 161
23 x 8 = 184
23 x 9 = 207
23 x 10 = 230
UNIT -2
UNIT-II: Functions: Built-In Functions, Commonly Used Modules, Function Definition
andCallingthefunction,returnStatementandvoidFunction,ScopeandLifetimeofVariables,D
efault Parameters, Keyword Arguments, *args and **kwargs, Command Line
Arguments.Strings:CreatingandStoringStrings,BasicStringOperations,AccessingCharact
ersinStringbyIndexNumber, String Slicing and Joining, String Methods, Formatting
Strings.
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In
Functions Used on Lists, List Methods, del Statement.
Sample Experiments:
7. Write a program to define a function with multiple return values.
8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using any library functions.
10. Write a program to check if the substring is present in a given string or not.
11. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii.slicing
12. Write a program to perform any 5built-in functions by taking any list.
7. Write a program to define a function with multiple return values.
CODE :
def Basic_Calculator(x, y):
# Returns the sum, difference, and product of two numbers.
sum_result = x + y
difference_result = x - y
product_result = x * y
division_result=x/y
return sum_result, difference_result, product_result,division_result
#Taking Numbers as Input
num1 = int(input("enter a num:"))
num2 = int(input("enter second num:"))
#Calling the function with multiple returnvalues
sum, difference, product,division = Basic_Calculator(num1, num2)
#printing the result
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Division:", division)
Output :
enter a num:3
enter second num:5
Sum: 8
Difference: -2
Product: 15
Division: 0.6
8. Write a program to define a function using default arguments.
CODE :
def greet(name, age=25, country='INDIA'):
print(f"Hello, {name}! You are {age} years old from {country}.")
# Calling the function with all arguments
greet("adithya", 30, "America")
# Calling the function with default age
greet("anurag", country="Canada")
# Calling the function with default age and country
greet("Bhargav")
Output :
Hello, adithya! You are 30 years old from America.
Hello, anurag! You are 25 years old from Canada.
Hello, Bhargav! You are 25 years old from INDIA.
9. Write a program to find the length of the string without using any library
functions.
CODE :
Output : def length_of_string(s):
count = 0
for char in s:
if char == " ":
continue
else:
count += 1
return count
s = input("enter the string :")
print("Length of the string:",length_of_string(s))
Output:
enter the string :Python Programming lab!!
Length of the string: 22
10. Write a program to check if the substring is present in a given string or not.
CODE :
#Function that checks for a given substring in a string
def find_substring(s, sub):
s_len = len(s)
sub_len = len(sub)
for i in range(s_len - sub_len + 1):
if s[i:i+sub_len] == sub:
return True
return False
#Taking the string and substring as inputs
s = input("enter a string ")
sub = input("enter a sub string ")
#Printing the Results
if find_substring(s, sub):
print(f"The substring '{sub}' is present in the string '{s}'.")
else:
print(f"The substring '{sub}' is not present in the string '{s}'.")
Output :
enter a string python programming
enter a sub string thon
The substring 'thon' is present in the string 'python programming'.
11.Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
CODE :
# Define a list
my_list = [1, 2, 3, 4, 5]
print("Original List:", my_list)
# i. Addition: append an element to the end of the list
i=int(input("Enter element to be added in the list "))
my_list.append(i)
print("After addition:", my_list)
# ii. Insertion: insert an element at a specific position
j=int(input("Enter element to be inserted in the list "))
k=int(input("Enter the position of the element to be inserted in the list "))
my_list.insert(k,j)
print("After insertion:", my_list)
# iii. Slicing: extract a subset of elements from the list
l=int(input("Enter starting index of slicing "))
m=int(input("Enter finishing index of slicing "))
sliced_list = my_list[l:m]
print("Sliced list:", sliced_list)
Output :
Original List: [1, 2, 3, 4, 5]
Enter element to be added in the list 3
After addition: [1, 2, 3, 4, 5, 3]
Enter element to be inserted in the list 4
Enter the position of the element to be inserted in the list 4
After insertion: [1, 2, 3, 4, 4, 5, 3]
Enter starting index of slicing 2
Enter finishing index of slicing 4
Sliced list: [3, 4]
12. Write a program to perform any 5 built-in functions by taking any list.
CODE :
# Define a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original List:", my_list)
# 1. len() function: returns the length of the list
print("Length of the list:", len(my_list))
# 2. max() function: returns the maximum value in the list
print("Maximum value in the list:", max(my_list))
# 3. min() function: returns the minimum value in the list
print("Minimum value in the list:", min(my_list))
# 4. sum() function: returns the sum of all values in the list
print("Sum of all values in the list:", sum(my_list))
# 5. sorted() function: returns a new sorted list
print("Sorted list:", sorted(my_list))
Output :
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Length of the list: 10
Maximum value in the list: 10
Minimum value in the list: 1
Sum of all values in the list: 55
Sorted list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
UNIT-3
UNIT-III: Dictionaries: Creating Dictionary, Accessing and Modifying key: value
Pairs in Dictionaries, Built-In Functions Used on Dictionaries, Dictionary Methods, del
Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple() Function, Indexing
and Slicing in Tuples, Built-In Functions Used on Tuples, Relation between Tuples
and Lists, Relation between Tuples and Dictionaries, Using zip() Function, Sets, Set
Methods, Frozen set.
Sample Experiments:
13. Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (No control flow
allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new k ey-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary.
13. Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
# Creating tuples
member1 = ('John', 25, '123 Street', 'ABC College')
member2 = ('Alice', 22, '456 Avenue', 'XYZ College')
# Concatenating tuples
concatenated_tuple = member1 + member2
print(concatenated_tuple)
Output:
('John', 25, '123 Street', 'ABC College', 'Alice', 22, '456 Avenue', 'XYZ College')
14. Write a program to count the number of vowels in a string (No control flow
allowed).
def count_vowels_no_control_flow(input_string):
"""
Counts the number of vowels in a string without explicit control flow.
Args:
input_string: The string to analyze.
Returns:
The number of vowels in the string.
"""
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
# The generator expression (1 for char in input_string if char in vowels)
# yields 1 for each character that is a vowel.
# sum() then adds up these 1s to get the total count.
return sum(1 for char in input_string if char in vowels)
# Example usage:
my_string = "Hello World"
vowel_count = count_vowels_no_control_flow(my_string)
print(f"The number of vowels in '{my_string}' is: {vowel_count}")
my_string_2 = "Python Programming"
vowel_count_2 = count_vowels_no_control_flow(my_string_2)
print(f"The number of vowels in '{my_string_2}' is: {vowel_count_2}")
Output:
The number of vowels in 'Hello World' is: 3
The number of vowels in 'Python Programming' is: 4
15. Write a program to check if a given key exists in a dictionary or not.
# Creating a sample dictionary
sample_dict = {'a': 1, 'b': 2, 'c': 3}
# Checking if a key exists
key_to_check = 'b'
key_exists = key_to_check in sample_dict
print(key_exists)
Output:
True
16. Write a program to add a new key-value pair to an existing dictionary.
# Existing dictionary
existing_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
existing_dict['c'] = 3
print(existing_dict)
Output:
{'a': 1, 'b': 2, 'c': 3}
17. Write a program to sum all the items in a given dictionary.
# Sum of values of a dictionary
# function
def Sum(dic):
#sum variable
sum=0
#iterate through values
for i in dic.values():
sum=sum+i
return sum
#initialisation
dic={ 'x':30, 'y':145, 'z':55 }
print("Dictionary: ", dic)
#print sum
print("sum: ",Sum(dic))
Output:
Dictionary: {'x': 30, 'y': 145, 'z': 55}
sum: 230
18. Program to iterate over items in tuples using for loop.
ocean_animals=("electrical_eel","jelly_fish","shrimp","turtles","blue_whales")
def main():
for each_animal in ocean_animals:
print(f"{each_animal} is an ocean animal")
if __name__=="__main__":
main()
Output:
electrical_eel is an ocean animal
jelly_fish is an ocean animal
shrimp is an ocean animal
turtles is an ocean animal
blue_whales is an ocean animal
19. Program to tabulate tuple with user-entered items.
tuple_items=()
total_items=int(input("enter the total number of items:"))
for i in range(total_items):
user_input=int(input("enter a number:"))
tuple_items += (user_input,)
print(f"items added to the tuple are{tuple_items}")
list_items=[]
total_items=int(input("enter a total number of items:"))
for i in range (total_items):
list_item=input("enter an item to add:")
list_items.append(item)
items_of_tuple=tuple(list_item)
print(f"tuple items are {items_of_tuple}")
Output:
enter the total number of items:4
enter a number:3
enter a number:4
enter a number:5
enter a number:6
items added to the tuple are(3, 4, 5, 6)
20.Write a python program to swap two numbers.
a=int(input("Enter a value for the first number"))
b=int(input("Enter a value for the second number"))
b,a=a,b
print("After swapping")
print(f"value for the first number{a}")
print(f"value for the second number{b}")
Output:
Enter a value for the first number6
Enter a value for the second number7
After swapping
value for the first number7
value for the second number6
21. Write a python program to count the number of elements.
my_list=[10,20,30,40,50]
count=len(my_list)
print("the given list is:",my_list)
print("Number of elements in list is:",count)
Output:
the given list is: [10, 20, 30, 40, 50]
Number of elements in list is: 5
22. Write a python program to calculate electricity bill.
def calculate_bill(units):
if units<=100:
return units*1
elif units<=200:
return 100*1+(units-100)*2
elif units<=300:
return 100*1+100*2+100*4+(units-200)*6
def generate_bill():
print("Electricity bill generator:")
customer_name=input("Enter customer name:")
customer_id=input("Enter customer id:")
try:
units_consumed=float(input("enter number of units consumed:"))
except value_Error:
print("Invalid inputs for command.")
amount=calculate_bill(units_consumed)
print("\n ----Electricity bill----")
print(f"customer Name:{customer_name}")
print(f"customer id:{customer_id}")
print(f"units consumed:{units_consumed}")
print(f"Total amount:{amount}Rs")
generate_bill()
Output:
Enter customer name:mahesh
Enter customer id:24001A0320
enter number of units consumed:56
----Electricity bill----
customer Name:mahesh
customer id:24001A0320
units consumed:56.0
Total amount:56.0Rs
23. Write a python program to find a factorial of a number.
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
number=5
print(f"the factorial of {number} is {factorial(number)}")
Output:
the factorial of 5 is 120
24. Write a python program to genetare Fibonacci series.
def fibonacci_series(n):
fib_series = []
a, b = 0, 1
for _ in range(n):
fib_series.append(a)
a, b = b, a + b
return fib_series
def main():
print("====Fibonacci series====")
try:
num_terms = int(input("Enter the number of terms:"))
if num_terms <= 0:
print("please enter a positive number:")
else:
series = fibonacci_series(num_terms)
print(f"Fibonacci series upto {num_terms} terms:")
print(series)
except ValueError:
print("Invalid input! Please enter a valid integer.")
if __name__ == "__main__":
main()
Output:
====Fibonacci series====
Enter the number of terms:3
Fibonacci series upto 3 terms:
[0, 1, 1]
25. Write a python program to count the frequency of elements in a List.
my_list=[10,20,30,10,20,10,10,30,30]
frequency={}
for item in my_list:
frequency[item]=frequency.get(item,0)+1
print("the given list is:",my_list)
print("frequency of element:")
for key,value in frequency.items():
print(f"{key}:{value}")
Output:
the given list is: [10, 20, 30, 10, 20, 10, 10, 30, 30]
frequency of element:
10:4
20:2
30:3
26. Write a python program for a frequency counter in a List.
def count_frequency(input_list):
frequency={}
for item in input_list:
if item in frequency:
frequency[item]+=1
else:
frequency[item]=1
return frequency
def main():
print("===frequency counter===")
user_input=input("enter list elements separated by space:")
input_list=user_input.split()
frequency=count_frequency(input_list)
print("\n element frequency count:")
for item,count in frequency.items():
print(f"{item}:{count}")
if __name__=="__main__":
main()
ouput:
===frequency counter===
enter list elements separated by space:66 89 67 45
element frequency count:
66:1
89:1
67:1
45:1
27. Write a python program a print a guess number.
import random
def guess_number():
"""
This function lets the user play a number guessing game.
The user tries to guess a number between 1 and 9.
"""
number_to_guess = random.randint(1, 9)
print("I've chosen a number between 1 and 9. Can you guess it?")
while True:
try:
guess = int(input("Enter your guess (1-9): "))
if guess < 1 or guess > 9:
print("Please enter a number between 1 and 9.")
continue # Jumps back to the start of the while loop
if guess == number_to_guess:
print("Congratulations! You guessed it right.")
break # Exits the while loop
else:
print("Wrong guess, try again!")
except ValueError:
print("Please enter a valid number.")
# The loop continues automatically after an invalid input
# Call the function to run the game
guess_number()
Output:
I've chosen a number between 1 and 9. Can you guess it?
Enter your guess (1-9): 4
Wrong guess, try again!
Enter your guess (1-9): 3
Wrong guess, try again!
Enter your guess (1-9): 6
Congratulations! You guessed it right.
28. Write a python program to write a reversed word of a given word.
def reverse_word():
word=input("Enter a word:")
reversed_word=word[::-1]
print("Reversed word:",reversed_word)
reverse_word()
Output:
Enter a word:mahesh
Reversed word: hseham
29. Write a python program for string calculation.
expression=input("enter a mathematical expression:")
try:
result=eval(expression)
print("Result:",result)
except:
print("Invalid expression!")
Output:
enter a mathematical expression:2+3*8
Result: 26
30. Write a program to count numbers of even and odd numbers present in atuple.
numbers=(1,2,3,4,5,6,7,8,9,10)
even_count=0
odd_count=0
for num in numbers:
if num%2==0:
even_count+=1
else:
odd_count+=1
print("Numbers in tuple:",numbers)
print("Total even numbers:",even_count)
print("Total odd numbers:",odd_count)
Output:
Numbers in tuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Total even numbers: 5
Total odd numbers: 5
25.write a python program to demonstrate using the same variable name is calling
functionand function definition.
god_name=input("who is the god of seas according to greek mythology?")
def greek_mythology(god_name):
print(f"the god of seas according to greek mythology is {god_name}")
def main():
greek_mythology(god_name)
if __name__=="__main__":
main()
Output:
who is the god of seas according to greek mythology?jesus
the god of seas according to greek mythology is jesus
31. Write a program to find the area of the trapezium using the formula
Area=1/2(a+b)*h,where a and b are the two bases of the trapezium and h is height.
def area_trapezium(a,b,h):
area=0.5*(a+b)*h
print(f"area of trapezium is {area}")
def main():
area_trapezium(10,20,30)
if __name__=="__main__":
main()
Output:
area of trapezium is 450.0
32. Write a program to check if a 3 digit number is Armstrong or not.
def armstrong_number(user_number):
result = 0
temp = user_number
while temp != 0:
last_digit =float( temp % 10)
result += pow(last_digit, 3)
temp =int( temp / 10 )
if user_number == result:
print(f"Entered number {user_number} is an Armstrong number")
else:
print(f"Entered number {user_number} is not an Armstrong number")
def main():
user_number = int(input("Enter a three-digit positive number to check for Armstrong: "))
armstrong_number(user_number)
if __name__ == "__main__":
main()
Output:
Enter a three-digit positive number to check for Armstrong: 345
Entered number 345 is not an Armstrong number
UNIT-IV
UNIT-IV: Files: Types of Files, Creating and Reading Text Data, File Methods to
Read and Write Data, Reading and Writing Binary Files, Pickle Module, Reading and
Writing CSV Files Python os and os.path Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python,
Creating Objects in Python, Constructor Method, Classes with Multiple Objects, Class
Attributes Vs Data Attributes, Encapsulation, Inheritance, Polymorphism.
Sample Experiments:
39. Write a program to sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper-case words from source must be
lowered.
40. Python program to print each line of a file in reverse order.
41. Python program to compute the number of characters , words and lines in a file.
42. Write a program to create, display, append, insert and reverse the order of the items
in the array.
43. Write a program to add, transpose and multiply two matrices.
44. Write a Python program to create a class that represents a shape. Include methods
to calculate its area and perimeter. Implement subclasses for different shapes like
circle, triangle, and square.
33. Python program to sort words in a file and write them to another file in lowercase
# Input and output file names
input_file = "input.txt"
output_file = "output.txt"
try:
# Open the input file and read its contents
with open(input_file, "r") as infile:
text = infile.read()
# Split text into words, convert to lowercase, and sort
words = text.lower().split()
words.sort()
# Write sorted words into the output file
with open(output_file, "w") as outfile:
for word in words:
outfile.write(word + "\n")
print(f"Words sorted successfully and written to '{output_file}'.")
except FileNotFoundError:
print(f"Error: The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output: input.txt
Apple banana ORANGE Mango grape
Output.txt
apple
banana
grape
mango
orange
34. Python program to print each line of a file in reverse order
# Input file name
input_file = "input.txt"
try:
# Open the file in read mode
with open(input_file, "r") as infile:
# Read all lines from the file
lines = infile.readlines()
print("Reversed lines:")
# Print each line in reverse order
for line in lines:
# Strip newline and reverse characters
reversed_line = line.rstrip('\n')[::-1]
print(reversed_line)
except FileNotFoundError:
print(f"Error: The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
Input.txt
Hello World
Python Programming
File Handling
Output.txt
dlroW olleH
gnimmargorP nohtyP
gnildnaH eliF
35. Python program to compute the number of characters, words, and lines in a file
# Input file name
input_file = "input.txt"
try:
# Open the file in read mode
with open(input_file, "r") as infile:
lines = infile.readlines()
# Initialize counters
num_lines = len(lines)
num_words = 0
num_chars = 0
# Count words and characters line by line
for line in lines:
words = line.split()
num_words += len(words)
num_chars += len(line)
# Display the results
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_chars}")
except FileNotFoundError:
print(f"Error: The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
input.txt
Python is fun
File handling is important
Count characters words and lines
Number of lines: 3
Number of words: 10
Number of characters: 78
36. Python program to create, display, append, insert, and reverse items in an array
import array as arr
# Create an integer array
numbers = arr.array('i', [10, 20, 30, 40, 50])
# Display the array
print("Original array:", numbers.tolist())
# Append an element to the array
numbers.append(60)
print("After appending 60:", numbers.tolist())
# Insert an element at a specific position
numbers.insert(2, 25) # Insert 25 at index 2
print("After inserting 25 at index 2:", numbers.tolist())
# Reverse the array
numbers.reverse()
print("Array in reverse order:", numbers.tolist())
Output:
Original array: [10, 20, 30, 40, 50]
After appending 60: [10, 20, 30, 40, 50, 60]
After inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]
Array in reverse order: [60, 50, 40, 30, 25, 20, 10]
37. Python program to add, transpose, and multiply two matrices
# Function to display a matrix
def display_matrix(matrix, name="Matrix"):
print(f"\n{name}:")
for row in matrix:
print(row)
# Function to add two matrices
def add_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
row.append(A[i][j] + B[i][j])
result.append(row)
return result
# Function to transpose a matrix
def transpose_matrix(A):
rows, cols = len(A), len(A[0])
transpose = [[A[j][i] for j in range(rows)] for i in range(cols)]
return transpose
# Function to multiply two matrices
def multiply_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
total = 0
for k in range(len(B)):
total += A[i][k] * B[k][j]
row.append(total)
result.append(row)
return result
# ---- Main Program ----
A= [
[1, 2, 3],
[4, 5, 6]
]
B=[
[7, 8, 9],
[10, 11, 12]
]
display_matrix(A, "Matrix A")
display_matrix(B, "Matrix B")
# Matrix Addition
add_result = add_matrices(A, B)
display_matrix(add_result, "A + B")
# Transpose of Matrix A
transpose_A = transpose_matrix(A)
display_matrix(transpose_A, "Transpose of A")
# For multiplication, B must have compatible dimensions
# Let's take B as a 3x2 matrix for valid multiplication
B2 = [
[1, 2],
[3, 4],
[5, 6]
]
display_matrix(B2, "Matrix B (for multiplication)")
# Matrix Multiplication
multiply_result = multiply_matrices(A, B2)
display_matrix(multiply_result, "A x B")
Output:
Matrix A: Matrix B:
[1, 2, 3] [7, 8, 9]
[4, 5, 6] [10, 11, 12]
A + B:
[8, 10, 12] Transpose of A:
[14, 16, 18] [1, 4]
[2, 5]
[3, 6]
Matrix B (for multiplication): A x B:
[1, 2] [22, 28]
[3, 4] [49, 64]
[5, 6]
38. Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
import math
# Base class
class Shape:
def area(self):
pass # To be implemented by subclass
def perimeter(self):
pass # To be implemented by subclass
# Subclass: Circle
class Circle(Shape):
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
# Subclass: Square
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
# Subclass: Triangle
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
# Using Heron's formula
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
# ---- Main Program ----
# Create objects for each shape
circle = Circle(5)
square = Square(4)
triangle = Triangle(3, 4, 5)
# Display results
print("Circle:")
print(" Area:", round(circle.area(), 2))
print(" Perimeter:", round(circle.perimeter(), 2))
print("\nSquare:")
print(" Area:", square.area())
print(" Perimeter:", square.perimeter())
print("\nTriangle:")
print(" Area:", round(triangle.area(), 2))
print(" Perimeter:", triangle.perimeter())
Output:
Circle:
Area: 78.54
Perimeter: 31.42
Square:
Area: 16
Perimeter: 16
Triangle:
Area: 6.0
Perimeter: 12
UNIT-V
UNIT-V: Introduction to Data Science: Functiona Programming, JSON and XML in Python,
NumPy with Python, Pandas.
39. Python program to check whether a JSON string contain complex object or not.
import json
def contains_complex_object(json_str):
try:
data = json.loads(json_str)
return check_complex(data)
except json.JSONDecodeError:
return True
def check_complex(obj):
if isinstance(obj, (str, int, float, bool)) or obj is None:
return False
elif isinstance(obj, list):
return any(check_complex(item) for item in obj)
elif isinstance(obj, dict):
return any(check_complex(value) for value in obj.values())
else:
return True
simple_json = '{"name": "Alice", "age": 25}'
complex_json = '{"num": {"real": 1, "imag": 2j}}'
print("Simple JSON:", "Complex" if contains_complex_object(simple_json) else "Simple")
print("Complex JSON:", "Complex" if contains_complex_object(complex_json) else "Simple")
Output:
Simple JSON: Simple
Complex JSON: Complex
40. Python Program to demonstrate NumPy arrays creation using array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print("Array:", arr)
print("Type:", type(arr))
Output:
Array: [1 2 3 4 5]
Type: <class 'numpy.ndarray'>
41. Python program to demonstrate use of ndim, shape, size, dtype.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Array:\n", arr)
print("Dimensions (ndim):", arr.ndim)
print("Shape:", arr.shape)
print("Size:", arr.size)
print("Data type:", arr.dtype)
Output:
Array:
[[1 2 3]
[4 5 6]]
Dimensions (ndim): 2
Shape: (2, 3)
Size: 6
Data type: int64
42. Python program to demonstrate basic slicing, integer and Boolean indexing.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print("Original Array:", arr)
# Slicing
print("Sliced (1:4):", arr[1:4])
# Integer Indexing
indices = [0, 2, 4]
print("Integer Indexing:", arr[indices])
# Boolean Indexing
bool_idx = arr > 25
print("Boolean Indexing (arr > 25):", arr[bool_idx])
Output:
Original Array: [10 20 30 40 50]
Sliced (1:4): [20 30 40]
Integer Indexing: [10 30 50]
Boolean Indexing (arr > 25): [30 40 50]
43. Python program to find min, max, sum, cumulative sum of array.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print("Array:", arr)
print("Min:", np.min(arr))
print("Max:", np.max(arr))
print("Sum:", np.sum(arr))
print("Cumulative Sum:", np.cumsum(arr))
Output:
Array: [10 20 30 40 50]
Min: 10
Max: 50
Sum: 150
Cumulative Sum: [ 10 30 60 100 150]
44. Create a dictionary and explore the data through pandas DataFrame.
import pandas as pd
data = {
'A': [10,20,30,40,50,60,70,80,90,100],
'B': [5,15,25,35,45,55,65,75,85,95],
'C': [2,4,6,8,10,12,14,16,18,20],
'D': [1,3,5,7,9,11,13,15,17,19],
'E': [9,18,27,36,45,54,63,72,81,90]
}
df = pd.DataFrame(data)
# a) Head Function
print("Head of DataFrame:\n", df.head())
# b) Data Selection Operations
print("Select Column A:\n", df['A'])
print("Select Multiple Columns:\n", df[['A', 'B']])
print("Select Rows 0-4:\n", df[0:5])
Output:
Head of DataFrame:
A B C D E
0 10 5 2 1 9
1 20 15 4 3 18
2 30 25 6 5 27
3 40 35 8 7 36
4 50 45 10 9 45
Select Column A:
0 10
1 20
2 30
3 40
4 50
5 60
6 70
7 80
8 90
9 100
Select Multiple Columns:
A B
0 10 5
1 20 15
2 30 25
3 40 35
4 50 45
Select Rows 0-4:
A B C D E
0 10 5 2 1 9
1 20 15 4 3 18
2 30 25 6 5 27
3 40 35 8 7 36
4 50 45 10 9 45
45. Scatter plot between two attributes using matplotlib.
import matplotlib.pyplot as plt
import pandas as pd
data = {
'A': [10,20,30,40,50,60,70,80,90,100],
'B': [5,15,25,35,45,55,65,75,85,95]
}
df = pd.DataFrame(data)
plt.scatter(df['A'], df['B'], color='blue')
plt.title('Scatter Plot between A and B')
plt.xlabel('A values')
plt.ylabel('B values')
plt.show()
Output: Displays a scatter plot showing linear relationship between columns A and B.