0% found this document useful (0 votes)
86 views120 pages

Python Programming Manual

The document outlines the vision, mission, quality policy, and core values of the Maharashtra State Board of Technical Education (MSBTE) aimed at enhancing technical education and aligning it with industry needs. It includes a laboratory manual for Basic Python Programming (Course 313011) detailing practical outcomes, learning objectives, and a series of programming exercises for students. The manual emphasizes skill development, industry readiness, and the importance of ethical practices in technical education.

Uploaded by

rohitpatle103
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views120 pages

Python Programming Manual

The document outlines the vision, mission, quality policy, and core values of the Maharashtra State Board of Technical Education (MSBTE) aimed at enhancing technical education and aligning it with industry needs. It includes a laboratory manual for Basic Python Programming (Course 313011) detailing practical outcomes, learning objectives, and a series of programming exercises for students. The manual emphasizes skill development, industry readiness, and the importance of ethical practices in technical education.

Uploaded by

rohitpatle103
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

VISION

To ensure that the Diploma level Technical Education constantly matches the latest
requirements of Technology and industry and includes the all-round personal
development of students including social concerns and to become globally
competitive, technology led organization.

MISSION

To provide high quality technical and managerial manpower, information and


consultancy services to the industry and community to enable the industry and
community to face the challenging technological & environmental challenges.

QUALITY POLICY
We, at MSBTE are committed to offer the best-in-class academic services to the
students and institutes to enhance the delight of industry and society. This will be
achieved through continual improvement in management practices adopted in the
process of curriculum design, development, implementation, evaluation, and
monitoring system along with adequate faculty development programmes.

CORE VALUES
MSBTE believes in the following:
 Skill development in line with industry requirements.
 Industry readiness and improved employability of Diploma holders.
 Synergistic relationship with industry.
 Collective and Cooperative development of all stake holders.
 Technological interventions in societal development.
 Access to uniform quality technical education.
A Laboratory Manual
for

Basic Python Programming


(313011)

“K-SCHEME”

Semester-III
( AO/ DE/ EJ/ ET/ EX/ IC/ IE/ IS/ ML/ MU)

Maharashtra State Board of Technical Education, Mumbai


(Autonomous) (ISO 9001:2015) (ISO/IEC 27001:2013)
MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Certificate

This is to certify that Mr. / Ms…………………………. Roll No……………………

, of Third Semester of Diploma in ..…………………………………………………. of


Institute…………………………………………………………………………… (Institute Code ) has
completed the term work satisfactorily in Course
Basic Python Programming (313011) for the academic year 20…..-20…. as prescribed in the curriculum.

Place: …………… Enrollment No: .…………….


Date: …………… Exam. Seat No: ……………

Subject Teacher Head of the Department Principal

Seal Of
Institution
Basic Python Programming(313011)

Programmed Outcomes (POs) and Program Specific Outcomes (PSOs) to be achieved through
Practical’s of this course.

[Link] and Discipline Specific Knowledge: Apply knowledge of basic mathematics, science and
engineering fundamentals and engineering specialization to solve the engineering problems.

PO2. Problem Analysis: Identify and analyses well-defined engineering problems using codified standard
methods.

PO3. Design/ Development of Solutions: Design solutions for well-defined technical problems and assist
with the design of systems components or processes to meet specified needs.

PO4. Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements.

PO5. Engineering Practices for Society, Sustainability and Environment: Apply appropriate
technology in context of society, sustainability, environment and ethical practices.

PO6. Project Management: Use engineering management principles individually, as a team member or a
leader to manage projects and effectively communicate about well-defined engineering activities.

PO7. Life-Long Learning: Ability to analyze individual needs and engage in updating in the context of
technological changes.

Dated [Link]
Sr. Title of the practical teacher
No.
a) Install and configure Python IDE.
1. b) Write Python program to display message on screen.
2. *a) Write simple Python program to calculate equivalent registers connected in series and
parallel.
Accept values of R1, R2 and R3 from the user.
*b) Write simple Python program to calculate value of voltage by applying Ohm‟s law.
Accept value of Current(I) and Resistance(R) from the user.
3. Write program to check whether
entered frequency is radio frequency or audio frequency.
4. *a) Write program to display various radio frequency bands using if..elseif ladder.
*b) Write program to display resistor
color code using switch statement.
5. *a) Write a simple Python program to demonstrate use of control loops: i) while ii) do
while
*b) Create a simple program, to demonstrate use of: for loop in Python (e.g.: various
pattern building, printing multiplication table, checking
palindrome number etc.)
6 *Write Python program to perform following operations on List:
. Create Access Update Delete elements from list.
Develop Python program to perform following operations on Tuples:
7. Create Access Update Delete Tuple elements

Maharashtra State Board of Technical Education (K Scheme) v


Basic Python Programming(313011)
Dated sign. of
Sr. Title of the practical teacher
No.
8. Write Python program to perform following operations on Set:
Create Access Update Delete Access Set elements
9.*Create a program to perform following operations on Dictionaries in Python:
Create Access Update Delete Looping through Dictionary
10.*a) Create Python program to demonstrate use of math built- in function.
*b) Create Python program
to demonstrate use of string built-in function.
[Link] Python programs to define function with arguments.
a) Calculate factorial of a number
b) Swapping of two variables
[Link] programs to define function with default arguments.
13.*Create a program to demonstrate use of: Built-in module (e.g.: numeric,
mathematical functional and programming module) in Python.
[Link] program to create a user-
defined module (e.g.: building calculator) in python.
15.*Develop Python program to demonstrate use of NumPy package for creating, accessing
and performing different array operations.
[Link] program to demonstrate the use of user defined packages in Python.

Maharashtra State Board of Technical Education (K Scheme) vi


Basic of Python Programming (313011)

Practical No. 1: a) Install and configure Python IDE.


b) Write Python program to display message on screen.
I. Practical Significance
Python is a high-level, general-purpose, interpreted, interactive, object-oriented dynamic
programming language. Student will able to select and install appropriate installer for Python in
windows and package manager for Linux in order to setup Python environment for running programs.

II. Industry /Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.
III. Course Level Learning Outcome
CO1 - Develop script to demonstrate use of basic building blocks of python.
IV. Laboratory Learning Outcome

LLO 1.1 Install Python Integrated Development Environment.

V. Relevant Affective Domain related Outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.
VI. Relevant Theoretical Background
Python was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also
available under the GNU General Public License (GPL). Python is named after a TV Show called
„Monty Python‟s Flying Circus‟ and not after Python- the snake.
Installing Python in Windows:
 Open any internet browser. Type [Link] in address bar and
press Enter.
 Home page of Python will have displayed as shown in Fig. 1

Maharashtra State Board of Technical Education (K Scheme) 7


Basic of Python Programming (313011)
Fig. 1: Home Page
 Click on download the latest version for windows, which shows latest version as shown in
Fig. 2

Fig.2: Python release versions


 Open the Python 3.7.1 version pack and double click on it to start installation and
installation windows will be open as shown in Fig. 3.

Fig. 3: Installation Type

Maharashtra State Board of Technical Education (K Scheme) 8


Basic of Python Programming (313011)

 Click on next install now for installation and then Setup progress windows will be opened
as shown in Fig. 4.

Fig. 4: Setup Progress

 After complete the installation, Click on close button in the windows as shown in
Fig. 5.

Fig. 5: Setup Completion Starting Python in different modes:

1) Starting Python (Command Line)

Maharashtra State Board of Technical Education (K Scheme) 9


Basic Python Programming (313011)

 Press start button

 Click on all programs and then click on Python 3.7 (32 bit). You will see the Python interactive
prompt in Python command line.

 Python command prompt contains an opening message >>> called command prompt. The
cursor at command prompt waits for to enter Python command. A complete command is called a statement.
For example check first command to print message.

 You will see the Python interactive prompt i.e. interactive shell.

VII. esources required

Sr. Name of Specification Quantity Remarks


No. Resource (If any)
1. Computer System Computer (i3-i5 preferable As per Batch For ALL
RAM>2GB) Size Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software

VIII. Resources used (Additional)

Sr. Name of Resource Specification Quantity Remarks (If


No. any)
1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions


Note: Below given are few sample questions for reference. Teachers must design more such
questions to ensure the achievement of identified CO.
1. Write steps for installing Python on window.
Step 1: Download the Python Installer
1. Open your web browser and go to the official Python website downloads page.
2. The website should automatically detect your operating system and highlight the latest version of
Python available for Windows.
3. Click the Download Python [version number] button. The file will be saved to your computer.
Step 2: Run the Installer
1. Locate the downloaded .exe installer file (usually in your Downloads folder) and double-click it to
run. This will open the Python setup window.
Step 3: Crucial Installation Options
1. Check the "Add [Link] to PATH" box. This is a critical step. Adding Python to your system's
PATH environment variable makes it possible to run Python commands from the Command Prompt (CMD)
or PowerShell without having to specify the full path to the executable file.
2. Select "Install Now". This option uses recommended default settings for installation.

Step 4: Complete the Installation


1. The installer will show a progress bar as it installs the necessary components.
2. Once the installation is complete, a new window will appear with a "Setup was successful" message.
Maharashtra State Board of Technical Education (K Scheme)
10
Basic Python Programming (313011)
3. Click "Close".

Step 5: Verify the Installation


To confirm that Python was installed correctly and is accessible from your command line:
1. Open the Command Prompt by pressing the Windows key and typing cmd, then selecting
"Command Prompt" from the search results.
2. In the Command Prompt window, type the following command and press Enter:bash
python --version
or
bash
 py --version
 If the installation was successful, the output will display the installed Python version number (e.g.,
Python 3.12.1).
You are now ready to start using Python on your Windows machine!
2. State IDLE in Python.
In Python,
IDLE is an acronym for Integrated Development and Learning Environment. It is the standard, basic
IDE that comes bundled with the default installation of the Python programming language.
Key Features and Purpose
IDLE is designed to be simple and beginner-friendly, providing a straightforward platform for writing,
executing, and debugging Python code.
 Integrated: It combines several tools needed for programming into a single application, including a
text editor and an interpreter.
 Learning Environment: It is particularly suitable for educational purposes due to its simple
interface and basic functionalities that help new programmers understand Python fundamentals.
Main Components
IDLE primarily operates in two main window types:
 Python Shell (Interactive Interpreter): This window allows you to type Python commands one
line at a time and see the results immediately. It is useful for testing snippets of code and performing quick
calculations.
 Editor Window: This is a full-featured text editor where you can write longer, multi-line Python
programs (scripts), save them as .py files, and run the entire program at once.
IDLE is cross-platform, ensuring a consistent user experience on Windows, macOS, and Linux. While it
may lack some advanced features found in other IDEs, it provides essentials like syntax highlighting, smart
indentation, and a built-in debugger, making it a valuable tool for learning Python

3. List key features of Python.


Python is a versatile, high-level programming language known for its clear, readable syntax and extensive
ecosystem of libraries
.
Key features of Python include:
 Easy to Use and Learn: Python's syntax is designed to be simple and intuitive, often resembling
plain English. This makes it an ideal language for beginners and allows developers to focus on problem-
solving rather than complex syntax rules.
 Interpreted Language: Python code is executed line by line at runtime, rather than being fully
compiled ahead of time. This facilitates rapid development and easier debugging, as errors are detected
immediately.
 Dynamically Typed: Variables in Python do not require explicit type declarations. The interpreter
automatically determines the variable type at runtime, which adds flexibility and reduces the amount of
boilerplate code.
 Free and Open-Source: Python is freely available to use, modify, and distribute, even for
commercial purposes. Its open-source nature has fostered a large, active community that contributes to its
ongoing development and a vast collection of libraries and tools.
 Extensive Standard Library and Third-Party Packages: Python comes with a comprehensive
standard library that covers a wide range of tasks, from file I/O to internet protocols. Beyond this, a rich
Maharashtra State Board of Technical Education (K Scheme)
11
Basic Python Programming (313011)
ecosystem of third-party libraries (accessible via PyPI) supports specialized areas like data science (NumPy,
Pandas, TensorFlow), web development (Django, Flask), and machine learning.
 Object-Oriented Programming (OOP) Support: Python fully supports core OOP concepts such as
classes, objects, inheritance, polymorphism, and encapsulation. This promotes code reusability and
modularity, making it suitable for managing large codebases.
 Cross-Platform Compatibility: Python code can run on virtually any major platform, including
Windows, macOS, and Linux, with little or no modification. This portability makes it simple to develop and
deploy cross-platform applications.
 Support for Multiple Programming Paradigms: Python is a multi-paradigm language, allowing
developers to use procedural, object-oriented, and functional programming styles, offering flexibility to
choose the best approach for a given project.
 Automatic Memory Management: Python handles memory management automatically through a
private heap and an integrated garbage collector, so developers do not need to manually allocate or
deallocate memory.
 Large Community Support: A huge and active community of developers means extensive
documentation, tutorials, forums, and continuous improvements are readily available, making it easier to
find help and collaborate.
4. List different modes of Programming in Python.
Python programming is executed in two primary modes:
Interactive Mode and Script Mode.
 Interactive Mode: In this mode, Python commands are executed line-by-line using a command-line
interface or an integrated development environment (IDE) shell (often referred to as a REPL, or Read-
Evaluate-Print-Loop). This mode provides immediate feedback for each statement and is useful for:
o Testing small snippets of code or new syntax variations.
o Learning the basics of the language.
o Debugging functionality in isolation before integrating into a larger project.
You can access interactive mode by typing python (or py on Windows) in your terminal.
 Script Mode: This is the standard mode for developing complete programs. Code is written and
saved in files with a .py extension (known as modules). The entire program is then run from the beginning
by the Python interpreter, making it suitable for larger, more complex, and reusable applications. This
allows for:
o Saving and re-running code multiple times without re-typing.
o Easier editing and maintenance of the program.
o Building extensive software projects.
Most IDEs, such as IDLE, PyCharm, or VS Code, allow developers to work in both modes, often using the
interactive shell for testing alongside the script editor for development

5. Describe procedure to execute program using Interactive Mode.


To execute a program using
interactive mode (also known as a REPL: Read-Eval-Print Loop), you enter commands one line at a time
directly into the interpreter, and the results are displayed immediately.
Procedure to Execute in Interactive Mode
1. Open the Command Line Interface: Open your operating system's terminal, command prompt, or
PowerShell application.
2. Start the Interpreter: Type python (or python3, py depending on your system's configuration) and
press Enter.
3. Verify the Prompt: The prompt will change to three angle brackets (>>>), indicating that the
interpreter is ready to accept commands in interactive mode.
4. Type Code and Execute: Type your program statements or expressions directly at the >>> prompt
and press Enter after each line. The interpreter will evaluate the command and display the output (if any)
on the next line
5. Exit Interactive Mode: When finished, you can exit the session by typing exit() or quit() and pressing
Enter, or by pressing Ctrl + Z (on Windows) or Ctrl + D (on Linux/macOS) and then Enter
6. State the steps involved in executing the program using Script Mode.
Executing a Python program in
Maharashtra State Board of Technical Education (K Scheme)
12
Basic Python Programming (313011)
Script Mode involves writing your code in a dedicated editor and running the entire file using the Python
interpreter. The typical steps using Python's default Integrated Development and Learning Environment
(IDLE) are as follows:
1. Open the IDLE editor:
o Launch the Python IDLE application.
o In the initial IDLE Shell window, go to the menu bar and select File > New File (or press
Ctrl+N / Cmd+N). This opens a new, blank editor window, which is where you write scripts.
2. Write your code:
o Type the entire Python program in the new editor window. Unlike the interactive shell, the
code does not execute line by line as you type.
3. Save the file:
o Go to File > Save (or press Ctrl+S / Cmd+S).
o Choose a location on your computer to save the file.
o Ensure you save the file with a .py extension (e.g., my_program.py), which tells the
operating system it is a Python script. IDLE might prompt you to save if you forget this step before running.
4. Run the program:
o With the script file open and saved, go to the menu bar and select Run > Run Module.
o Alternatively, you can press the shortcut key F5 (or Fn+F5 on some systems) on your
keyboard.
5. View the output:
o The Python interpreter will execute the entire script. The output, as well as any errors or
prompts for input, will be displayed in the original IDLE Shell window
7. State the procedure to make file executable.
The procedure to make a file executable primarily depends on the operating system you are using. In Linux and
macOS, you use the
chmod command to set the execute permission, while on Windows, executables are typically created through a
compilation process or by using specific file extensions.
In Linux and macOS
You can make a file executable using either the command line or the graphical user interface (GUI).
Command Line Method (Terminal)
1. Open the terminal (e.g., [Link] on Mac, or any terminal emulator on Linux).
2. Navigate to the file's directory using the cd command. For example, if the file is in your Documents folder:
bash
 cd Documents
 Add execute permission to the file using the chmod command. The most common commands are:
 chmod +x filename - gives execute permission to the file owner, group, and others.
 chmod u+x filename - gives execute permission only to the file owner.
 chmod 755 filename - a common octal mode that gives the owner full read, write, and execute
permissions, and the group and others read and execute permissions.
 Verify the permissions by listing the file details:
bash
 ls -l filename
You should see an 'x' in the permissions list (e.g., -rwxr-xr-x).
 Execute the file by prefixing its name with ./ (to specify it's in the current directory):
bash
./filename
Note: For a script file (like a Bash or Python script) to run correctly, its first line should contain a "shebang" (e.g.,
#!/bin/bash or #!/usr/bin/env python3) which tells the system which interpreter to use.
Graphical Method (GUI)
1. Locate the file in your file manager (e.g., Nautilus in GNOME, Finder on Mac).
2. Right-click on the file and select Properties (or Get Info on macOS).
3. Go to the Permissions tab.
4. Check the box that says "Allow executing file as program" or similar wording.
In Windows
Windows primarily uses file extensions like .exe, .com, or .bat to identify executable files. Text-based scripts need
to be run by an appropriate interpreter (e.g., python your_script.py in Command Prompt).
To create a standalone executable (.exe) from source code or scripts, you typically need to use a compiler or a
Maharashtra State Board of Technical Education (K Scheme)
13
Basic Python Programming (313011)
packaging tool:
 For Source Code (C++, C#, etc.): Use a compiler (e.g., in a program like Visual Studio) to build and link
your source code into an .exe file.
 For Scripts (Python, etc.): Use tools like PyInstaller or Auto PY to EXE to package your script and its
dependencies into a standalone .exe file.
o Example using PyInstaller: pip install pyinstaller followed by pyinstaller --onefile
your_script.py.
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
8. Print the version of Python.
Python version3.12.8 (tags/v3.12.8:7e8fa1b, Dec 3 2024, 04:12:14) [MSC v.1929 64 bit
(AMD64)]
Version [Link].version_info(major=3, minor=12, micro=8, releaselevel='final',
serial=0)

9. Write steps to be followed to load Python interpreter in windows.


To run Python on a Windows machine, the Python interpreter must first be installed. Once installed, it can
be loaded in several ways.

Step 1: Install Python


If Python is not yet installed, you need to download the official Windows installer:
1. Navigate to the official Python Downloads page.
2. Download the latest recommended version for Windows.
3. Run the installer executable file.
4. Crucially, check the box that says "Add [Link] to PATH" during installation. This allows
you to open the interpreter from any command prompt location.
5. Click "Install Now" and follow the prompts to complete the installation.
Step 2: Load the Python Interpreter
After installation, you can load the Python interpreter using any of the following methods:
Method 1: Using the Command Prompt (Recommended)
This is the standard and most flexible method:
1. Open the Command Prompt by pressing the Windows key, typing cmd, and pressing Enter.
2. At the command prompt, type python or py.
3. Press Enter.
4. The prompt will change to >>>, indicating the Python interpreter is active and ready to accept
commands.
Method 2: Using the Windows Start Menu (IDLE)
Python installations usually include an integrated development environment called IDLE:
1. Press the Windows key.
2. Type IDLE in the search bar.
3. Click on IDLE (Python 3.x) in the search results.
4. This opens the IDLE Shell, which is a graphical interface for the Python interpreter.
Method 3: Using the Windows Run Dialog
1. Press the Windows Key + R to open the Run dialog box.
2. Type cmd and press Enter to open the Command Prompt.
3. Follow the steps in Method 1 (type python or py and press Enter).

10. Write a Python program to display your name using Interactive Mode.
Following are the code in python which gives the output in interactive mode: Explanation: print("Your name is:
"+input("Enter the name")) # it will take input from the user and print that input.1
11. Write a Python program to display “MSBTE” using Script Mode.

To display "MSBTE" using Python's script mode, you need to follow a two-step process: writing the code in
a text editor and then running it from your command line or terminal.
Step 1: Create the Python Script File
Maharashtra State Board of Technical Education (K Scheme)
14
Basic Python Programming (313011)
1. Open a text editor (like Notepad, VS Code, or Sublime Text).
2. Type the following code into the editor:
python
2. print("MSBTE")
3.
4. Save the file with a .py extension. For example, save it as display_msbte.py.
5. Note the location where you saved the file (e.g., in a "Documents" folder).
Step 2: Run the Script from the Command Line
1. Open your computer's command line interface (CLI):
o Windows: Search for "Command Prompt" or "PowerShell" in the Start menu.
o macOS/Linux: Open the "Terminal" application.
2. Navigate to the directory where you saved your file using the cd (change directory) command. For
example, if you saved it in a "Documents" folder:
bash
 cd Documents
 Run the script by typing python (or python3 on some systems) followed by the name of your file:
bash
3. python display_msbte.py
Output
After running the command in Step 2, the command line will display:
MSBTE
X. References / Suggestions for further Reading
1. [Link]
2. [Link]
2. [Link]
3. [Link]
4. [Link]

XI. Assessment Scheme

Performance Indicators Weightage


Process related: 15 Marks 60%
1. Debugging ability 20%

2. Correctness of Program codes 30%

3. Quality of output achieved (LLO mapped) 10%

Product related: 10 Marks 40%


1. Completion and submission of practical in time 20%
2. Answer to sample questions 20%
Total 25 Marks 100%

Marks obtained Dated Signature of Teacher

Process Related (15) Product Related Total (25)


(10)

Maharashtra State Board of Technical Education (K Scheme)


15
Basic Python Programming (313011)

Practical No 2: *a) Write simple Python program to calculate equivalent registers connected in series
and parallel. Accept values of R1, R2 and R3 from the user.
*b) Write simple Python program to calculate value of voltage by applying Ohm’s law. Accept value of
Current(I) and Resistance(R) from the user.

I. Practical Significance
The practical significance of using operators in Python includes performing essential mathematical and
logical computations, enabling complex decision-making in control flow, and facilitating data manipulation
and low-level programming tasks. Additionally, membershipand identity operators enhance efficiency in data
structure operations. Overall, operators contribute to code readability and conciseness, making Python
powerful for various applications.

II Industry / Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III Course Level Learning Outcome

CO1-Develop script to demonstrate use of basic building blocks of python.

IV Laboratory Learning Outcome

LLO 2.1 Use operators in Python.

V Relevant Affective domain related Outcome(s)


1. Follow safety practices.
2. Maintain tools and equipment.
3. Follow ethical practices.

VI Relevant Theoretical Background

1. Arithmetic Operators:
Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

2.
Assignment Operators:
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
Maharashtra State Board of Technical Education (K Scheme)
16
Basic Python Programming (313011)
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
:= print(x := 3) x = 3 print(x)

3.
Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

4. Logical Operators:
Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

5. Identity Operators:
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object,
with the same memory location:

Operator Description Example


is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y

6. Membership Operators:
Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with the specified value is x in y
present in the object
not in Returns True if a sequence with the specified value is not x not in y
present in the object

Maharashtra State Board of Technical Education (K Scheme)


17
Basic Python Programming (313011)
7. Bitwise Operators:
Bitwise operators are used to compare (binary) numbers:

Operator Name Description Example


& AND Sets each bit to 1 if both bits are 1 x&y
| OR Sets each bit to 1 if one of two bits is 1 x|y
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y
~ NOT Inverts all the bits ~x
<< Zero fill left Shift left by pushing zeros in from the right and let x << 2
shift the leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in x >> 2
rightshift from the left, and let the rightmost bits fall off

VII Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software

VIII Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.

1. Mention the use of //, **, % operator in Python.


In Python, the
//, **, and % operators are used for specific mathematical operations:
 // (Floor Division): This operator performs division and rounds the result down to the nearest whole
number (integer). For example, 10 // 3 results in 3, not 3.33....
 ** (Exponentiation): This operator raises the number on the left to the power of the number on the

right. For example, 2 ** 3 (which is 2 raised to the power of 3, or


2×2×22 cross 2 cross 2
2×2×2
) results in 8.

Maharashtra State Board of Technical Education (K Scheme)


18
Basic Python Programming (313011)
 % (Modulo): This operator returns the remainder of a division operation. For example, 10 % 3 divides
10 by 3 (which is 3 with a remainder of 1), so the result is 1. This is commonly used to determine if a number
is even or odd, or to keep a number within a specific range.

2. Write a Python program to calculate the final price after applying a discount. The user inputs the
original price and the discount percentage.
def calculate_discounted_price():
"""
Calculates the final price after applying a discount based on user input.
"""
try:
# Get input from the user
original_price_str = input("Enter the original price (e.g., 50.00): ")
discount_percentage_str = input("Enter the discount percentage (e.g., 15 for 15%): ")

# Convert input strings to float numbers


original_price = float(original_price_str)
discount_percentage = float(discount_percentage_str)

# Validate input for non-negative values


if original_price < 0 or discount_percentage < 0:
print("Price and discount percentage cannot be negative.")
return

# Calculate the discount amount


discount_amount = (original_price * discount_percentage) / 100

# Calculate the final price


final_price = original_price - discount_amount

# Print the result, formatted to two decimal places


print(f"\nOriginal Price: ${original_price:.2f}")
print(f"Discount Percentage: {discount_percentage:.2f}%")
print(f"Discount Amount: ${discount_amount:.2f}")
print(f"Final Price: ${final_price:.2f}")

except ValueError:
# Handle cases where user input is not a valid number
print("Invalid input. Please enter numerical values for price and percentage.")
except Exception as e:
# Handle any other unexpected errors
print(f"An error occurred: {e}")

# Call the function to run the program


if __name__ == "__main__":
calculate_discounted_price()

3. Write a Python program to compare the ages of two people. The user inputs the ages, and the
program prints who is older or if they are the same age.
# Function to compare the ages of two people
def compare_ages():
try:
# Get age input for the first person
age1_str = input("Enter the age of the first person: ")
# Get age input for the second person
Maharashtra State Board of Technical Education (K Scheme)
19
Basic Python Programming (313011)
age2_str = input("Enter the age of the second person: ")

# Convert the input strings to integers


age1 = int(age1_str)
age2 = int(age2_str)

# Compare the ages


if age1 > age2:
print("The first person is older.")
elif age2 > age1:
print("The second person is older.")
else:
print("Both people are the same age.")

except ValueError:
# Handle cases where the user enters something that is not a number
print("Error: Please enter valid integer numbers for ages.")

# Call the function to run the program


compare_ages()

4. Given `x = 5` and `y = 8`, how would you express whether `x` is less than or equal to `y`?

The expression used to determine if

xbold x
𝐱
is less than or equal to

ybold y
𝐲
is

x≤ybold x is less than or equal to bold y


𝐱≤𝐲
.

Expressing the Condition


The inequality symbol for "less than or equal to" is

≤is less than or equal to



. Given the values

x=5x equals 5
𝑥=5
and

y=8y equals 8
𝑦=8
, the expression is written as
Maharashtra State Board of Technical Education (K Scheme)
20
Basic Python Programming (313011)

5≤85 is less than or equal to 8


5≤8
.
This mathematical statement is True because 5 is a value less than 8. In many programming languages, this
condition would be expressed using the operator <= (e.g., x <= y), which would return a boolean value of
True

5. Write a Python program to check if a number `num` is greater than `10` and less than `20`.

# Define the number you want to check


num = 15

# Check if the number is greater than 10 AND less than 20


if num > 10 and num < 20:
# This code block executes if both conditions are true
print(f"The number {num} is greater than 10 and less than 20.")
else:
# This code block executes if one or both conditions are false
print(f"The number {num} is not in the specified range.")

# You can also write the condition using a more concise chained comparison in Python:
if 10 < num < 20:
print(f"The number {num} is in the range using a chained comparison.")

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1) Write simple Python program to calculate equivalent registers connected in series and parallel.
Accept values of R1, R2 and R3 from the user.
# Function to calculate series equivalent resistance
def series_equivalent(r1, r2, r3):
return r1 + r2 + r3

# Function to calculate parallel equivalent resistance


def parallel_equivalent(r1, r2, r3):
# The formula for three resistors in parallel is 1/R_total = 1/R1 + 1/R2 + 1/R3
# Rearranging for R_total gives R_total = 1 / (1/R1 + 1/R2 + 1/R3)
# This also needs to handle potential zero division if a resistor value is 0 or less, which isn't physically ideal
but can happen with user input.
if r1 <= 0 or r2 <= 0 or r3 <= 0:
return 0 # Or handle error more explicitly
else:
return 1 / (1/r1 + 1/r2 + 1/r3)

# --- User Input and Output ---

print("Enter the values for the three resistors (R1, R2, R3) in Ohms.")
# Get inputs from the user
try:
R1 = float(input("Enter value for R1: "))
R2 = float(input("Enter value for R2: "))
Maharashtra State Board of Technical Education (K Scheme)
21
Basic Python Programming (313011)
R3 = float(input("Enter value for R3: "))
# Calculate and display results
R_series = series_equivalent(R1, R2, R3)
R_parallel = parallel_equivalent(R1, R2, R3)
print(f"\nResults:")
print(f"Equivalent resistance in series: {R_series:.2f} Ohms")
# Only show parallel result if the inputs were valid for that calculation
if R_parallel > 0:
print(f"Equivalent resistance in parallel: {R_parallel:.2f} Ohms")
else:
print("Could not calculate parallel resistance (ensure all resistor values are positive).")
except ValueError:
print("Invalid input. Please enter numerical values for the resistors.")
2) Write simple Python program to calculate value of voltage by applying Ohm‟s law. Accept value
of Current(I) and Resistance(R) from the user.
# Function to calculate voltage using Ohm's Law
def calculate_voltage(current, resistance):
"""
Calculates voltage (V) using Ohm's Law (V = I * R).
Args:
current (float): Current in Amperes (A).
resistance (float): Resistance in Ohms (Ω).

Returns:
float: Voltage in Volts (V).
"""
voltage = current * resistance
return voltage

# Main part of the program to interact with the user


if __name__ == "__main__":
print("Ohm's Law Voltage Calculator (V = I * R)")

try:
# Accept input from the user and convert to a floating-point number
current_input = input("Enter the value of Current (I) in Amperes (A): ")
current = float(current_input)

resistance_input = input("Enter the value of Resistance (R) in Ohms (Ω): ")


resistance = float(resistance_input)

# Calculate the voltage


voltage = calculate_voltage(current, resistance)

# Display the result to the user


print(f"\nThe calculated Voltage (V) is: {voltage} Volts (V)")

except ValueError:
# Handle cases where the user enters non-numeric input
print("\nInvalid input. Please enter numeric values for Current and Resistance.")
3) Write a program to find the square root of a number.
#include <stdio.h>
#include <math.h> // Include the math library for sqrt()

int main() {
double num; // Variable to store the number
printf("Enter a number: ");
scanf("%lf", &num); // Get input from user
Maharashtra State Board of Technical Education (K Scheme)
22
Basic Python Programming (313011)

// Check if the number is non-negative before calculating


if (num >= 0) {
double root = sqrt(num); // Calculate the square root
printf("The square root of %.2lf is %.2lf\n", num, root);
} else {
printf("Cannot calculate the real square root of a negative number.\n");
}

return 0;
}
4) Write a program to find the area of Rectangle.
#include <stdio.h>

int main() {
float length, breadth, area;

// Prompt user for length


printf("Enter the length of the rectangle: ");
scanf("%f", &length); // Read length

// Prompt user for breadth


printf("Enter the breadth of the rectangle: ");
scanf("%f", &breadth); // Read breadth

// Calculate area
area = length * breadth;

// Display the result


printf("The area of the rectangle is: %.2f\n", area);

return 0;
}
5) Write a program to calculate area and perimeter of the square.
import math

# Example Test Case


area = 16

# Calculate side length


side = [Link](area)

# Calculate perimeter
perimeter = 4 * side

# Display result
print(f"Perimeter: {perimeter}")
6) Write a program to calculate surface volume and area of a cylinder.
import math

# Example
r=5
h = 10
surface_area = 2 * [Link] * r**2 + 2 * [Link] * r * h
volume = [Link] * r**2 * h

# Output results
print(surface_area)

Maharashtra State Board of Technical Education (K Scheme)


23
Basic Python Programming (313011)
print(volume)
7) Write a program to swap the value of two variables.

# Initializing variables
a = 10
b = 20

print(f"Before swap: a = {a}, b = {b}")

# Swapping the values using a temporary variable


temp = a
a=b
b = temp

print(f"After swap: a = {a}, b = {b}")


XI. References / Suggestions for further Reading
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme)


24
Basic Python Programming (313011)

Practical No. 3: Write program to check whether entered frequency is radiofrequency or audio frequency.

I. Practical significance
Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions. Decision structures evaluate multiple expressions which produce
TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE.

II. Industry / Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.
III. Course Level Learning Outcome
CO 2- Implement conditional and looping statements for given problem statement.
IV. Laboratory Learning Outcome
LLO 3.1 Implement two-way branching statement.

V. Relevant Affective Domain related outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.

VI. Relevant Theoretical Background Simple If Statement


A simple `if` statement is used to execute a block of code only if a specified condition is true. If the condition
is false, the block of code inside the `if` statement is skipped.
Syntax:
if condition:
code to execute if condition is true
**Example**:
age = 18
if age >= 18:
print("You are eligible to vote.")
In this example, the message "You are eligible to vote." is printed only if the `age` is 18 or older.

If-Else Statement
An `if-else` statement is used to execute one block of code if the condition is true, and another block of code if
the condition is false.
Syntax:
if condition:
# code to execute if condition is true else:
# code to execute if condition is false
**Example**:
age = 16
if age >= 18:
print("You are eligible to vote.") else:
print("You are not eligible to vote.")
In this example, the message "You are not eligible to vote." is printed because the `age` is less than 18.

Nested If Statement
A nested `if` statement is an `if` statement inside another `if` statement. This allows for more complex
decision-making and multi-level condition checking.
Syntax:
if condition1:
# code to execute if condition1 is true if condition2:
Maharashtra State Board of Technical Education (K Scheme)
25
Basic Python Programming (313011)
# code to execute if both condition1 and condition2 are true

**Example**:
age = 20 has_id = True if age >= 18:
if has_id:
print("You are eligible to enter the club.") else:
print("You need an ID to enter the club.")
else:
print("You are not old enough to enter the club.")
In this example, the message "You are eligible to enter the club." is printed because both conditions (`age >=
18` and `has_id`) are true. If `has_id` were `False`, the message "You need an ID to enter the club." would be
printed instead.

Summary:
Simple If: Executes a block of code if the condition is true.
If-Else: Executes one block of code if the condition is true, and another block if it is false.
Nested If: An `if` statement inside another `if` statement, allowing for multiple levels of condition
checking.
VII. Resources Required

Sr. No. Name of Specification Quantity Remarks


Resource (If any)
1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX Practical related Questions


Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.

1. Write a Python program that checks if the voltage of a battery is greater than 3.7V and prints
"Battery is charged" if true.
# Define the current battery voltage (you can change this value)
battery_voltage = 3.85 # Example: 3.85 Volts

# Check if the battery voltage is greater than 3.7V


if battery_voltage > 3.7:
# If true, print the message
print("Battery is charged")
else:
# Optional: Add an else block to handle cases where it's not charged
print("Battery level is low or not charged enough")

Maharashtra State Board of Technical Education (K Scheme)


26
Basic Python Programming (313011)
# Example with a lower voltage
battery_voltage_low = 3.2
if battery_voltage_low > 3.7:
print("Battery is charged")
else:
print("Battery level is low or not charged enough")
2. Write a Python program that checks if a resistor value is within a tolerance range (e.g., 5%
tolerance for a 100Ω resistor) and prints whether it is within tolerance or not.
def check_resistor_tolerance(nominal_value, measured_value, tolerance_percent):
"""
Checks if a measured resistor value is within the specified tolerance range.

Args:
nominal_value (float): The stated or target value of the resistor (e.g., 100).
measured_value (float): The actual measured value of the resistor (e.g., 98).
tolerance_percent (float): The tolerance percentage (e.g., 5 for 5%).

Returns:
bool: True if within tolerance, False otherwise. Prints the result.
"""
# Calculate the tolerance amount
tolerance_amount = nominal_value * (tolerance_percent / 100.0)

# Calculate the minimum and maximum acceptable values


min_value = nominal_value - tolerance_amount
max_value = nominal_value + tolerance_amount

# Check if the measured value falls within the range


if min_value <= measured_value <= max_value:
print(f"The measured value of {measured_value}Ω is within the {tolerance_percent}% tolerance range
of {nominal_value}Ω (Range: {min_value}Ω to {max_value}Ω).")
return True
else:
print(f"The measured value of {measured_value}Ω is NOT within the {tolerance_percent}% tolerance
range of {nominal_value}Ω (Range: {min_value}Ω to {max_value}Ω).")
return False

# --- Example Usage ---

# Example 1: Value within tolerance


nominal = 100.0
measured_1 = 98.0
tolerance = 5.0
check_resistor_tolerance(nominal, measured_1, tolerance)
print("-" * 40)

# Example 2: Value outside tolerance (too high)


nominal = 100.0
measured_2 = 106.0
tolerance = 5.0
check_resistor_tolerance(nominal, measured_2, tolerance)
print("-" * 40)

# Example 3: Value outside tolerance (too low)


nominal = 470.0 # Common resistor value
Maharashtra State Board of Technical Education (K Scheme)
27
Basic Python Programming (313011)
measured_3 = 440.0
tolerance = 1.0 # Example with a tighter tolerance (e.g., 1% metal film resistor)
check_resistor_tolerance(nominal, measured_3, tolerance)
3. Write a Python program that checks if a resistor value is within a tolerance range (e.g., 5%
tolerance for a 100Ω resistor) and prints whether it is within tolerance or not.
4. Write a Python program that checks if a resistor value is within a tolerance range (e.g., 5%
tolerance for a 100Ω resistor) and prints whether it is within tolerance or not.
5. Write a Python program that checks three sensor readings (voltage, current, and
temperature) and prints an alert if any of them are out of their specified ranges (e.g., voltage: 3.3V ± 0.3V,
current: 10mA ± 1mA, temperature: 25°C ± 5°C). The program should indicate which parameter(s) are out of
range.
def check_sensors(voltage, current, temperature):
"""
Checks sensor readings against specified ranges and prints alerts.

Args:
voltage (float): The measured voltage in Volts (V).
current (float): The measured current in milliamps (mA).
temperature (float): The measured temperature in degrees Celsius (°C).
"""

# Define the acceptable ranges (min, max)


VOLTAGE_RANGE = (3.0, 3.6)
CURRENT_RANGE = (9.0, 11.0)
TEMPERATURE_RANGE = (20.0, 30.0)

alerts = []

# Check voltage
if not (VOLTAGE_RANGE[0] <= voltage <= VOLTAGE_RANGE[1]):
[Link](f"Voltage ({voltage}V) is out of range. Acceptable range: {VOLTAGE_RANGE[0]}V to
{VOLTAGE_RANGE[1]}V.")

# Check current
if not (CURRENT_RANGE[0] <= current <= CURRENT_RANGE[1]):
[Link](f"Current ({current}mA) is out of range. Acceptable range: {CURRENT_RANGE[0]}mA
to {CURRENT_RANGE[1]}mA.")

# Check temperature
if not (TEMPERATURE_RANGE[0] <= temperature <= TEMPERATURE_RANGE[1]):
[Link](f"Temperature ({temperature}°C) is out of range. Acceptable range:
{TEMPERATURE_RANGE[0]}°C to {TEMPERATURE_RANGE[1]}°C.")

# Print results
if alerts:
print("--- ALERT: Sensor Readings Out of Range ---")
for alert in alerts:
print(f"- {alert}")
else:
print("All sensor readings are within acceptable limits.")

# Example Usage:

# Example 1: All readings within range


print("--- Test Case 1: All good ---")
Maharashtra State Board of Technical Education (K Scheme)
28
Basic Python Programming (313011)
check_sensors(3.35, 10.1, 24.5)
print("\n")

# Example 2: One reading out of range (voltage)


print("--- Test Case 2: Voltage failure ---")
check_sensors(2.9, 10.2, 25.0)
print("\n")

# Example 3: Multiple readings out of range (current and temperature)


print("--- Test Case 3: Multiple failures ---")
check_sensors(3.4, 12.5, 31.0)
print("\n")

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)
1) Write program to check whether entered frequency is radio frequency or audio frequency.
def classify_frequency(freq_hz):
# Standard human hearing range
AUDIO_MIN = 20
AUDIO_MAX = 20000

# Common definition for Radio Frequency spectrum start (often 3 kHz or 9 kHz)
RADIO_MIN = 3000

if freq_hz >= AUDIO_MIN and freq_hz <= AUDIO_MAX:


# It's in the range that humans can typically hear.
# Note that some frequencies in this range are also used for specific RF applications
print(f"{freq_hz} Hz is likely an audio frequency (within human hearing range).")
elif freq_hz > RADIO_MIN:
# Frequencies above the audio range, used for wireless communication.
print(f"{freq_hz} Hz is classified as a radio frequency.")
else:
# Very low frequencies outside normal ranges
print(f"{freq_hz} Hz is a very low frequency, potentially infrasound or ULF, outside typical audio or
radio classifications.")

# --- Example Usage ---


# Example 1: Audio frequency (e.g., A above middle C)
classify_frequency(440)

# Example 2: Radio frequency (e.g., AM radio station carrier frequency)


classify_frequency(1000000) # 1 MHz

# Example 3: Frequency in the overlapping range (e.g., 15 kHz is high audio, but also VLF radio)
classify_frequency(15000)

# Example 4: Low frequency outside normal range


classify_frequency(5)
2) Write a Python function to convert a given binary number to its equivalent gray code.
def binary_to_gray(binary_str):
"""
Converts a binary number string to its equivalent Gray code string.

Maharashtra State Board of Technical Education (K Scheme)


29
Basic Python Programming (313011)
Args:
binary_str: A string representation of the binary number (e.g., "1101").

Returns:
A string representation of the Gray code (e.g., "1011").
"""
if not binary_str:
return ""

gray_code_list = [binary_str[0]] # The most significant bit (MSB) is the same in binary and Gray code

for i in range(len(binary_str) - 1):


# XOR the current bit with the next bit
# int() converts char '0' or '1' to integer 0 or 1
# ^ is the XOR operator
# str() converts the result back to a character
xor_result = int(binary_str[i]) ^ int(binary_str[i+1])
gray_code_list.append(str(xor_result))

return "".join(gray_code_list)

# --- Example Usage ---


binary_num1 = "1101"
gray_num1 = binary_to_gray(binary_num1)
print(f"Binary: {binary_num1}, Gray: {gray_num1}")

binary_num2 = "10101"
gray_num2 = binary_to_gray(binary_num2)
print(f"Binary: {binary_num2}, Gray: {gray_num2}")
3) Write a program to find out absolute value of an input number.
# Get input from the user
number = float(input("Enter a number: "))

# Calculate the absolute value using the abs() function


absolute_value = abs(number)

# Print the result


print(f"The absolute value of {number} is {absolute_value}")
4) Write a program to check the largest number among the 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

# Example usage:
number1 = 10
number2 = 45
number3 = 20

# Call the function and print the result


result = find_largest(number1, number2, number3)
Maharashtra State Board of Technical Education (K Scheme)
30
Basic Python Programming (313011)
print(f"The largest number among {number1}, {number2}, and {number3} is: {result}")
5) Write a program to check if the input year is a leap year or not.
def is_leap(year):
"""
Checks if a given year is a leap year.

Args:
year: The year to check (integer).

Returns:
True if the year is a leap year, False otherwise.
"""
# A leap year is divisible by 4
if (year % 4) == 0:
# Unless it is divisible by 100
if (year % 100) == 0:
# In which case it must also be divisible by 400
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False

# Example usage:
try:
input_year = int(input("Enter a year: "))
if is_leap(input_year):
print(f"{input_year} is a leap year.")
else:
print(f"{input_year} is not a leap year.")
except ValueError:
print("Invalid input. Please enter a valid integer for the year.")
6) Write a program to check if a Number is Positive, Negative or Zero.
def check_number(num):
if num > 0:
print(f"{num} is a positive number.")
elif num < 0:
print(f"{num} is a negative number.")
else:
print(f"{num} is zero.")

# Example usage:
check_number(5)
check_number(-3)
check_number(0)
7) Write a program that takes the marks of 5 subjects and displays the grade.
def calculate_grade(marks):
"""
Calculates the final grade based on the average of 5 subject marks.

Args:
marks: A list or tuple containing the marks of 5 subjects.
Maharashtra State Board of Technical Education (K Scheme)
31
Basic Python Programming (313011)

Returns:
A string representing the calculated grade.
"""
if len(marks) != 5:
return "Error: Please provide exactly 5 subject marks."

# Validate if all marks are within a valid range (e.g., 0-100)


for mark in marks:
if not (0 <= mark <= 100):
return "Error: All marks must be between 0 and 100."

average = sum(marks) / len(marks)

if average >= 90:


grade = 'A'
elif average >= 80:
grade = 'B'
elif average >= 70:
grade = 'C'
elif average >= 60:
grade = 'D'
else:
grade = 'F'

return f"Average Marks: {average:.2f}\nGrade: {grade}"

# --- Example Usage ---


# You can uncomment one of the following examples to test the function:

# Example 1: Passing the marks directly to the function


# subject_marks = [85, 92, 78, 65, 88]
# result = calculate_grade(subject_marks)
# print(result)

# Example 2: Taking input from the user (more interactive)


def get_marks_from_user():
user_marks = []
print("Enter the marks for 5 subjects (0-100):")
for i in range(5):
while True:
try:
mark_input = input(f"Subject {i + 1} marks: ")
mark = int(mark_input)
if not (0 <= mark <= 100):
print("Please enter a valid mark between 0 and 100.")
continue
user_marks.append(mark)
break
except ValueError:
print("Invalid input. Please enter a number.")
return user_marks

# To run the user input version:


user_input_marks = get_marks_from_user()
Maharashtra State Board of Technical Education (K Scheme)
32
Basic Python Programming (313011)
result = calculate_grade(user_input_marks)
print(result)
X References / Suggestions for further Reading

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]

XI Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme)


33
Practical No 4: *a) Write program to display various radio frequency bands using if..elseif ladder.
*b) Write program to display resistor color code using switch statement.

I. Practical significance
Multi-way branching statements in Python, such as if-elif-else, handle complex decision- making efficiently
by outlining conditions and actions clearly. They improve code readability and are crucial in applications
like grading systems, user role management, and state transitions. This ensures robust, flexible, and user-
friendly applications.

II. Industry / Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.
III. Course Level Learning outcome
CO 2- Implement conditional and looping statements for given problem statement.

IV. Laboratory Learning outcome


LLO 4.1 Implement multi-way branching statement.

V. Relevant Affective Domain related Outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.

VI. Relevant Theoretical Background Python if-elif-else Ladder


An if-elif-else ladder is an order of if statements connected by elif statements. This enables you to check for
numerous conditions and run separate code blocks based on which condition is met.
Syntax of Python if-elif-else Ladder
if condition1: # code block 1 elif condition2:
# code block 2 elif condition3: # code block 3 else:
# default code block
Example of Python if-elif-else ladder voltage = 230
if voltage < 1.5: level = "Low"
elif 1.5 <= voltage < 3.3: level = "Medium"
elif 3.3 <= voltage < 5.0: level = "High"
elif 5.0 <= voltage < 12.0: level = "Very High"
else:
level = "Dangerously High" print(f"The voltage level is: {level}")

By understanding and effectively using the if-elif-else ladder, you can write Python programs that are capable of
making nuanced decisions based on multiple conditions, thus making your software more robust and versatile.
Python does not have a built-in switch-case statement like some other programming languages (e.g., C,
Java). However, you can achieve similar functionality using dictionaries or functions. Here are a few
methods to mimic switch-case behavior in Python.
Python Match Case Statement Syntax
The match case statement in Python is initialized with the match keyword followed by the parameter to be
matched. Then various cases are defined using the case keyword and the pattern to match the parameter.
The “_” is the wildcard character that runswhen all the cases fail to match the parameter value.
match parameter:
case pattern1:
# code for pattern 1
case pattern2:
# code for pattern 2
.
.
case patterN:
# code for pattern N
case _:
# default code block
The following code has a function named week day(). It receives an integer argument, matches it with all
possible weekday number values, and returns the corresponding name of day.
def weekday(n):
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"
print (weekday(3))
print (weekday(6))
print (weekday(7))

VII. Resources Required


Sr. Name of Resource Specification Quantity Remarks (If
No. any)
1. Computer System Computer (i3-i5 preferable As per Batch For ALL
RAM>2GB) Size Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII.
Resources used (Additional)
Sr. No. Name of Specification Quantity Remarks
Resource (If any)
1. Computer System
2. Operating System
3. Development
Software

IX. Practical related questions


Note: Below given are few sample questions for reference. Teachers must design more such
questions to ensure the achievement of identified CO.
1. Write a Python program that takes the color of a resistor as input and prints its corresponding
resistance value based on the following color code:

Black: 0 ohms Brown: 1 ohm Red: 2 ohms Orange: 3 ohms Yellow: 4 ohms Green: 5 ohms Blue: 6 ohms
Violet: 7 ohms Gray: 8 ohms White: 9 ohms def get_resistance(color):
"""
Takes the color of a resistor as input and prints its corresponding
resistance value based on a provided color code.

Args:
color (str): The name of the color as a string.

Returns:
None: Prints the result directly.
"""
color_codes = { "black": 0, "brown": 1, "red": 2, "orange": 3, "yellow": 4,
"green": 5, "blue": 6, "violet": 7, "gray": 8, "white": 9 }

# Normalize input to lowercase for robust matching


color_lower = [Link]()

if color_lower in color_codes:
value = color_codes[color_lower]
print(f"The resistance value for {color} is {value} ohms.")
else:
print(f"Error: '{color}' is not a recognized color in the provided code.")

# --- Example Usage ---


# Example 1: Valid color
get_resistance("Red")

# Example 2: Valid color (case-insensitive)


get_resistance("BROWN")

# Example 3: Invalid color


get_resistance("Pink")
2. Write a Python program that simulates the behavior of basic logic gates (AND, OR, NOT). The
program should take the type of gate and the input values as arguments and print the result.
def logic_gate_simulator(gate_type, inputs):
"""
Simulates the behavior of basic logic gates (AND, OR, NOT).

Args:
gate_type (str): The type of the logic gate ('AND', 'OR', 'NOT').
inputs (list): A list of input values (0 or 1). NOT gates require one input,
AND and OR gates can accept multiple inputs.

Prints:
The result of the logic gate operation.
"""
gate_type = gate_type.upper()

if gate_type == 'AND':
# Result is 1 only if all inputs are 1.
if all(inputs):
result = 1
else:
result = 0
print(f"Inputs: {inputs} | Gate: {gate_type} | Result: {result}")

elif gate_type == 'OR':


# Result is 1 if at least one input is 1.
if any(inputs):
result = 1
else:
result = 0
print(f"Inputs: {inputs} | Gate: {gate_type} | Result: {result}")

elif gate_type == 'NOT':


# NOT gate only operates on a single input.
if len(inputs) != 1:
print("Error: NOT gate requires exactly one input.")
return

# Inverts the input.


input_value = inputs[0]
if input_value == 0:
result = 1
elif input_value == 1:
result = 0
else:
print("Error: Invalid input for NOT gate. Use 0 or 1.")
return

print(f"Input: {input_value} | Gate: {gate_type} | Result: {result}")

else:
print(f"Error: Unknown gate type '{gate_type}'. Supported types: AND, OR, NOT.")

# --- Examples ---

# AND Gate examples


logic_gate_simulator('AND', [0, 0])
logic_gate_simulator('AND', [0, 1])
logic_gate_simulator('AND', [1, 0])
logic_gate_simulator('AND', [1, 1])
logic_gate_simulator('AND', [1, 1, 0, 1]) # Multiple inputs

print("-" * 20)

# OR Gate examples
logic_gate_simulator('OR', [0, 0])
logic_gate_simulator('OR', [0, 1])
logic_gate_simulator('OR', [1, 0])
logic_gate_simulator('OR', [1, 1])
logic_gate_simulator('OR', [0, 0, 0, 1]) # Multiple inputs

print("-" * 20)

# NOT Gate examples


logic_gate_simulator('NOT', [0])
logic_gate_simulator('NOT', [1])

print("-" * 20)

# Error handling examples


logic_gate_simulator('NOT', [0, 1]) # Too many inputs
logic_gate_simulator('XOR', [0, 1]) # Unknown gate type

3. Write a Python program that simulates a basic calculator. The program should take an operation type
(add, subtract, multiply, divide) and two numbers as inputs, then print the result.
def calculator():
"""
Simulates a basic calculator program.
"""
print("Welcome to the Basic Python Calculator!")
print("Available operations: add, subtract, multiply, divide")

try:
# Get operation type from the user
operation = input("Enter the operation type (add, subtract, multiply, divide): ").lower()

# Get the two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

if operation == 'add':
result = num1 + num2
print(f"The result of {num1} + {num2} is: {result}")
elif operation == 'subtract':
result = num1 - num2
print(f"The result of {num1} - {num2} is: {result}")
elif operation == 'multiply':
result = num1 * num2
print(f"The result of {num1} * {num2} is: {result}")
elif operation == 'divide':
if num2 == 0:
print("Error: Division by zero is not allowed.")
else:
result = num1 / num2
print(f"The result of {num1} / {num2} is: {result}")
else:
print("Error: Invalid operation type entered. Please use add, subtract, multiply, or divide.")

except ValueError:
print("Error: Invalid input. Please enter valid numbers.")
except Exception as e:
print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
calculator()

X. Exercise
Note: Faculty must ensure that every group of students use different input value. (Use blank space for
answers or attach more pages if needed)
1. Write program to display various radio frequency bands using if..elseif ladder.
#include <iostream>
#include <iomanip> // Required for setprecision

int main() {
double frequency_mhz;

// Prompt the user for input


std::cout << "Enter a frequency in MHz: ";

// Read the input frequency


if (!(std::cin >> frequency_mhz)) {
std::cout << "Invalid input. Please enter a numerical value." << std::endl;
return 1;
}

// Use an if...else if ladder to classify the frequency band


std::cout << std::fixed << std::setprecision(3);
if (frequency_mhz >= 0.003 && frequency_mhz < 0.03) {
std::cout << frequency_mhz << " MHz is in the ELF (Extremely Low Frequency) band." << std::endl;
} else if (frequency_mhz >= 0.03 && frequency_mhz < 0.3) {
std::cout << frequency_mhz << " MHz is in the SLF (Super Low Frequency) band." << std::endl;
} else if (frequency_mhz >= 0.3 && frequency_mhz < 3) {
std::cout << frequency_mhz << " MHz is in the ULF (Ultra Low Frequency) band." << std::endl;
} else if (frequency_mhz >= 3 && frequency_mhz < 30) {
std::cout << frequency_mhz << " MHz is in the VLF (Very Low Frequency) band." << std::endl;
} else if (frequency_mhz >= 30 && frequency_mhz < 300) {
std::cout << frequency_mhz << " MHz is in the LF (Low Frequency) band." << std::endl;
} else if (frequency_mhz >= 300 && frequency_mhz < 3000) {
// Example range for common FM radio and WiFi (VHF starts here)
std::cout << frequency_mhz << " MHz is in the MF (Medium Frequency) band." << std::endl;
} else if (frequency_mhz >= 3000 && frequency_mhz < 30000) {
// 3000 MHz is 3 GHz (UHF starts here)
std::cout << frequency_mhz << " MHz is in the HF (High Frequency) band." << std::endl;
} else {
// A generic response for frequencies outside the specified range
std::cout << frequency_mhz << " MHz is outside the primary defined VLF through HF bands." <<
std::endl;
}

return 0;
}
2. Write program to display resistor color code using switch statement.
def get_resistor_value(color):
"""
Function to return the numerical value of a resistor color band.
Uses a dictionary to simulate a switch statement.
"""
# Define the color codes in a dictionary
color_codes = { 'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4,
'green': 5, 'blue': 6, 'violet': 7, 'grey': 8, 'white': 9 }
# Use the dictionary's .get() method to retrieve the value.
# The second argument (None) is the default value if the color is not found.
return color_codes.get([Link](), None)
# --- Example Usage ---
# Get user input
user_color = input("Enter a resistor color (e.g., Red, Brown, etc.): ")
# Call the function and handle the result
value = get_resistor_value(user_color)
if value is not None:
print(f"The numerical value for the color '{user_color.capitalize()}' is: {value}")
else:
print(f"Error: '{user_color}' is not a recognized color code for a resistor band value.")
3. Write a Python program that converts temperatures between Celsius, Fahrenheit, and Kelvin based on
user input.
def celsius_to_fahrenheit(c):
"""Converts Celsius to Fahrenheit."""
return (c * 9/5) + 32
def celsius_to_kelvin(c):
"""Converts Celsius to Kelvin."""
return c + 273.15
def fahrenheit_to_celsius(f):
"""Converts Fahrenheit to Celsius."""
return (f - 32) * 5/9
def fahrenheit_to_kelvin(f):
"""Converts Fahrenheit to Kelvin."""
return (f - 32) * 5/9 + 273.15
def kelvin_to_celsius(k):
"""Converts Kelvin to Celsius."""
return k - 273.15
def kelvin_to_fahrenheit(k):
"""Converts Kelvin to Fahrenheit."""
return (k - 273.15) * 9/5 + 32
def convert_temperature():
"""Prompts user for input and performs the temperature conversion."""
print("Available units: C (Celsius), F (Fahrenheit), K (Kelvin)")
# Get input unit
from_unit = input("Enter the source unit (C/F/K): ").upper()
if from_unit not in ['C', 'F', 'K']:
print("Invalid source unit.")
return
# Get temperature value
try:
temp_value = float(input(f"Enter the temperature value in {from_unit}: "))
except ValueError:
print("Invalid temperature value.")
return
# Get target unit
to_unit = input("Enter the target unit (C/F/K): ").upper()
if to_unit not in ['C', 'F', 'K']:
print("Invalid target unit.")
return
# Perform conversion
if from_unit == to_unit:
print(f"Result: {temp_value:.2f} {to_unit}")
return
if from_unit == 'C':
if to_unit == 'F':
result = celsius_to_fahrenheit(temp_value)
elif to_unit == 'K':
result = celsius_to_kelvin(temp_value)
elif from_unit == 'F':
if to_unit == 'C':
result = fahrenheit_to_celsius(temp_value)
elif to_unit == 'K':
result = fahrenheit_to_kelvin(temp_value)
elif from_unit == 'K':
if to_unit == 'C':
result = kelvin_to_celsius(temp_value)
elif to_unit == 'F':
result = kelvin_to_fahrenheit(temp_value)
print(f"Result: {result:.2f} {to_unit}")
if __name__ == "__main__":
convert_temperature()

XI. References / Suggestions for further reading


1. [Link]
2. [Link]
3. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)
Basic Python Programming (313011)
Practical No.5 *a) Write a simple Python program to demonstrate use of control loops:
i) while
ii) do while
*b) Create a simple program, to demonstrate use of: for loop in Python (e.g.: various pattern building,
printing multiplication table, checking palindrome number etc.)

I. Practical significance
Control loops are essential for solving iterative problems by automating repetitive tasks and processing data
collections efficiently. They are crucial in implementing algorithms like sorting and searching and handling
dynamic input gracefully. In concurrent processing, loops manage multiple tasks simultaneously, enhancing
performance and scalability in software applications.

II. Industry / Employer Expected outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:

Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning outcome


CO2 - Implement conditional and looping statements for given problem statement.

IV. Laboratory Learning outcome


LLO 5.1 Implement control loops for solving iterative problems.

V. Relevant Affective Domain related Outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.

VI. Relevant Theoretical Background


Python control loops, specifically for loops and while loops, are essential tools for solving iterative
problems. They allow you to execute a block of code repeatedly based on specific conditions or for a certain
number of iterations. Here's an explanation of how they work and their significance in solving iterative
problems:

1. for Loops:
 for loops are used when you know the number of iterations or when iterating over
a sequence (e.g., lists, tuples, strings).
 They iterate over each item in a sequence, executing a block of code for each
iteration.
 Syntax:
for item in sequence:
# Code block to execute for each item
Example:
numbers = [1, 2, 3, 4, 5] for num in numbers:
print(num)

2. while Loops:
A while loop is used to repeatedly execute a block of code as long as a specified condition is true. It
continues iterating until the condition becomes false.
Syntax:
while condition:
# Code block to execute while condition is true
Example:
Maharashtra State Board of Technical Education (K Scheme)
42
Basic Python Programming (313011)
num = 1
while num <= 5: print(num) num += 1
Loop Control Statements:

Python provides loop control statements to modify the behavior of loops:

1. break: Terminates the loop prematurely, exiting the loop entirely.

for i in range(5): if i == 3:
break print(i)
2. continue: Skips the rest of the current iteration and moves to the next iteration.

for i in range(5): if i == 3:
continue print(i)
3. pass: Placeholder that does nothing. It is used when a statement is syntactically
required but no action is needed.
for i in range(5):
pass # Placeholder for future code

Nested Loops:
You can nest loops within each other to perform more complex iterations, such as iterating over nested lists or
performing matrix operations.
Example:
for i in range(3): for j in range(2):
print(i, j)

VII. Resources required


Sr. Name of Resource Specification Quantity Remarks (If
No. any)
1. Computer System Computer (i3-i5 preferable As per Batch For ALL
RAM>2GB) Size Experiments
2. Operating System Windows/Linux
3. Development Pyhton IDE
Software

VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

Maharashtra State Board of Technical Education (K Scheme)


43
Basic Python Programming
IX. (313011)questions
Practical related
Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1. Write a program to convert a binary number (input as a string) to its decimal equivalent
using looping constructs.
def binaryToDecimal(binaryString):
"""
Converts a binary number represented as a string to its decimal integer equivalent
using a looping construct.
"""
decimal_value = 0
# The length of the string helps determine the initial power of 2
power = len(binaryString) - 1

# Iterate through each digit in the binary string


for digit in binaryString:
# Check if the digit is '1'. Only '1's contribute to the decimal value.
if digit == '1':
# Add 2 raised to the current power to the total
decimal_value += 2**power

# Decrease the power of 2 for the next digit (moving from left to right)
power -= 1

return decimal_value

# --- Example Usage ---


binary_num_str = "10110"
decimal_result = binaryToDecimal(binary_num_str)
print(f"The binary number {binary_num_str} is equivalent to the decimal number {decimal_result}")

binary_num_str_2 = "1111111"
decimal_result_2 = binaryToDecimal(binary_num_str_2)
print(f"The binary number {binary_num_str_2} is equivalent to the decimal number {decimal_result_2}")
2. Implement a program to convert a decimal number (input as an integer) to its binary
equivalent using looping constructs.
def decimal_to_binary_loop(decimal_num):
"""
Converts a decimal integer to its binary equivalent using a loop.

Args:
decimal_num: The positive integer to convert.

Returns:
A string representation of the binary number.
"""
# Handle the special case where the input is 0
if decimal_num == 0:
return "0"

binary_result = ""
temp_num = decimal_num

# Loop while the temporary number is greater than 0


while temp_num > 0:
# Get the remainder when divided by 2 (the current bit)

Maharashtra State Board of Technical Education (K Scheme) 44


Basic Python Programming
remainder = temp_num (313011)
%2
# Prepend the bit to the result string
binary_result = str(remainder) + binary_result
# Perform integer division by 2 to move to the next bit
temp_num //= 2

return binary_result

# --- Example Usage ---


# Get input from the user
try:
user_input = int(input("Enter a positive decimal integer: "))
if user_input < 0:
print("Please enter a non-negative integer.")
else:
binary_equivalent = decimal_to_binary_loop(user_input)
print(f"The binary equivalent of {user_input} is: {binary_equivalent}")
except ValueError:
print("Invalid input. Please enter a valid integer.")

3. Implement a program to count the number of ones in a binary number (input as a string)
using looping constructs.
def count_ones(binary_string):
"""
Counts the number of ones in a binary number string using a loop.

Args:
binary_string: A string representing a binary number (e.g., '10110').

Returns:
The total count of '1's in the string as an integer.
"""
count = 0
# Iterate over each character in the string
for char in binary_string:
if char == '1':
count += 1
return count

# Example usage:
binary_input = "11010111"
ones_count = count_ones(binary_input)
print(f"The binary string is: {binary_input}")
print(f"The number of ones is: {ones_count}")

binary_input_2 = "1000000"
ones_count_2 = count_ones(binary_input_2)
print(f"\nThe binary string is: {binary_input_2}")
print(f"The number of ones is: {ones_count_2}")
4. Implement a program to calculate the output voltage of a voltage divider circuit using
given resistor values and an input voltage. Use looping constructs to iterate through different resistor
combinations and calculate the output voltage.
def calculate_voltage_divider(Vin, R1, R2):
"""
Calculates the output voltage of a voltage divider.
Formula: Vout = Vin * (R2 / (R1 + R2))

Maharashtra State Board of Technical Education (K Scheme) 45


Basic
""" Python Programming (313011)
if (R1 + R2) == 0:
return 0 # Avoid division by zero
Vout = Vin * (R2 / (R1 + R2))
return Vout

# --- Program Implementation with Looping Constructs ---

# Define lists of different values to test


input_voltages = [5.0, 9.0, 12.0] # Volts
resistor_combinations = [
{"R1": 1000, "R2": 2000}, # Ohms (1k and 2k)
{"R1": 4700, "R2": 10000}, # Ohms (4.7k and 10k)
{"R1": 220, "R2": 330} # Ohms (220 and 330)
]

print("--- Voltage Divider Calculations ---")

# Use nested loops to iterate through all combinations


for Vin in input_voltages:
for combo in resistor_combinations:
R1 = combo["R1"]
R2 = combo["R2"]

# Calculate the output voltage using the function


Vout = calculate_voltage_divider(Vin, R1, R2)

# Print the results


print(f"Input V: {Vin}V | R1: {R1}Ω | R2: {R2}Ω | Output V: {Vout:.2f}V")
print("-" * 40) # Divider for readability

X. Exercise:
Note: Faculty must ensure that every group of students use different input value. (Use blank space for
answers or attach more pages if needed)

1. Write a Python program to print all even numbers between 1 to 100 using while loop.
# Initialize a variable to start checking numbers from 1
number = 1

# Loop continues as long as 'number' is less than or equal to 100


while number <= 100:
# Check if the current number is even
# The modulo operator (%) returns the remainder of a division.
# If the remainder when divided by 2 is 0, the number is even.
if number % 2 == 0:
# If even, print the number
print(number)

# Increment the number for the next iteration of the loop


number += 1
2. Write a Python program to find the sum and reverse of n-digit numbers using for loop.
def sum_and_reverse_n_digit_number(number_str):
"""
Calculates the sum and reverse of an n-digit number using a for loop.

Maharashtra State Board of Technical Education (K Scheme) 46


Basic Python Programming (313011)
Args:
number_str: A string representation of an n-digit number.

Returns:
A tuple containing the sum of digits (int) and the reversed number (str).
"""
sum_of_digits = 0
reversed_number_str = ""

# Iterate through each digit in the input string


for digit in number_str:
# Calculate the sum of digits
# Convert each digit character back to an integer to add it
sum_of_digits += int(digit)

# Build the reversed number string by prepending the current digit


reversed_number_str = digit + reversed_number_str

return sum_of_digits, reversed_number_str

# --- Example Usage ---


# Get the n-digit number from the user as a string
n_digit_number = input("Enter an n-digit number: ")

# Check if the input is a valid number


if n_digit_number.isdigit():
total_sum, reversed_num = sum_and_reverse_n_digit_number(n_digit_number)

print(f"Original number: {n_digit_number}")


print(f"Sum of digits: {total_sum}")
print(f"Reversed number: {reversed_num}")
else:
print("Invalid input. Please enter a valid number.")

3. Write a Python program to print Fibonacci series on any number entered by the user.
def fibonacci_series(limit):
"""
Prints the Fibonacci series up to a specified limit.

The Fibonacci sequence is a series of numbers where each number


is the sum of the two preceding ones.
"""
# Initialize the first two numbers in the series
num1 = 0
num2 = 1

print(f"Fibonacci series up to {limit}:")

# Handle the case where the user enters 0 or 1


if limit <= 0:
print("Please enter a positive integer.")
elif limit == 1:
print(num1)
else:
# Generate the series using a while loop

Maharashtra State Board of Technical Education (K Scheme) 47


Basic Python
while Programming
num1 < limit: (313011)
print(num1, end=" ") # Print the current number
# Calculate the next number in the series
next_num = num1 + num2
# Update variables for the next iteration
num1 = num2
num2 = next_num

# Get input from the user


try:
user_limit = int(input("Enter a positive number to print the Fibonacci series up to that limit: "))
fibonacci_series(user_limit)
except ValueError:
print("Invalid input. Please enter an integer.")

4. Write a Python program to calculate factorial of a number.


def factorial_iterative(n):
"""Calculates the factorial of a non-negative integer using a for loop."""
if n < 0:
return "Factorial is not defined for negative numbers"
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

# Example usage:
number = 5
print(f"The factorial of {number} is {factorial_iterative(number)}")

number = 0
print(f"The factorial of {number} is {factorial_iterative(number)}")
5. Write a Python to print the LCM and GCD of two non-negative integer numbers.
import math

def calculate_gcd_lcm(a, b):


"""
Calculates the Greatest Common Divisor (GCD) and
Least Common Multiple (LCM) of two non-negative integers.

Args:
a: The first non-negative integer.
b: The second non-negative integer.

Returns:
A tuple containing (gcd, lcm).
"""
if a < 0 or b < 0:
raise ValueError("Inputs must be non-negative integers")

gcd_val = [Link](a, b)

# LCM calculation using the formula: LCM(a, b) * GCD(a, b) = |a * b|


# Avoid division by zero if both a and b are zero.

Maharashtra State Board of Technical Education (K Scheme) 48


Basic Python==
if gcd_val Programming
0: (313011)
lcm_val = 0
else:
lcm_val = abs(a * b) // gcd_val

return gcd_val, lcm_val

# --- Example Usage ---


num1 = 12
num2 = 18

gcd, lcm = calculate_gcd_lcm(num1, num2)

print(f"Numbers: {num1}, {num2}")


print(f"Greatest Common Divisor (GCD): {gcd}")
print(f"Least Common Multiple (LCM): {lcm}")

# Another example
num3 = 0
num4 = 5
gcd_zero, lcm_zero = calculate_gcd_lcm(num3, num4)
print(f"\nNumbers: {num3}, {num4}")
print(f"Greatest Common Divisor (GCD): {gcd_zero}")
print(f"Least Common Multiple (LCM): {lcm_zero}")
6. Write a Python program which will print all the Armstrong numbers between 1 to 500.
def is_armstrong(n):
"""Checks if a number is an Armstrong number."""
# Convert the number to a string to find the number of digits
s = str(n)
num_digits = len(s)
sum_of_powers = 0
temp = n

# Calculate the sum of the powers of its digits


while temp > 0:
digit = temp % 10
sum_of_powers += digit ** num_digits
temp //= 10

# If the sum equals the original number, it's an Armstrong number


return n == sum_of_powers

def find_armstrong_numbers(start, end):


"""Finds all Armstrong numbers within a given range."""
armstrong_numbers = []
for num in range(start, end + 1):
if is_armstrong(num):
armstrong_numbers.append(num)
return armstrong_numbers

# Find and print Armstrong numbers between 1 and 500


armstrongs = find_armstrong_numbers(1, 500)
print(f"Armstrong numbers between 1 and 500 are: {armstrongs}")

7. Write a Python program that takes a number and checks whether it is a palindrome or not.
def is_palindrome(number):

Maharashtra State Board of Technical Education (K Scheme) 49


Basic
""" Python Programming (313011)
Checks if a number is a palindrome.

A palindrome is a number that reads the same backward as forward.

Args:
number: The integer to check.

Returns:
True if the number is a palindrome, False otherwise.
"""
# Convert the number to a string to easily reverse it
num_str = str(number)
# Reverse the string
reversed_str = num_str[::-1]

# Check if the original string is equal to the reversed string


if num_str == reversed_str:
return True
else:
return False

# --- Example Usage ---

# Test with a palindrome number


num1 = 121
if is_palindrome(num1):
print(f"{num1} is a palindrome.")
else:
print(f"{num1} is not a palindrome.")

# Test with a non-palindrome number


num2 = 12345
if is_palindrome(num2):
print(f"{num2} is a palindrome.")
else:
print(f"{num2} is not a palindrome.")

# Test with another palindrome number


num3 = 9009
if is_palindrome(num3):
print(f"{num3} is a palindrome.")
else:
print(f"{num3} is not a palindrome.")
8. Print the following patterns using loop:
a) *
**
***
****
# Program to print a simple right triangle star pattern
rows = 5

# Outer loop to iterate through each row


for i in range(1, rows + 1):
# Inner loop to print the stars in each row

Maharashtra State Board of Technical Education (K Scheme) 50


Basic
for jPython Programming (313011)
in range(i):
print('*', end='')
# Print a new line after each row
print()
XI. References/Suggestions for further reading
1. [Link]
2. [Link]
3. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%


1. Debugging ability 20%
2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%
1. Completion and submission of practical in time 20%
2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 51


Basic Python Programming (313011)

Practical No.6 *Write Python program to perform following operations on List:


a) Create
b) Access
c) Update
d) Delete elements from list.

I. Practical significance
Lists in Python are crucial for storing and managing ordered collections of items, providing flexibility with
various data types. They support dynamic sizing, allowing for efficient addition and removal of elements.
Lists are integral to data processing tasks such as sorting, filtering, and iterating over elements. Their
versatility and built-in methods enhance code readability and efficiency in handling complex data operations.

II. Industry / Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:

Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO3-Perform operations on sequence structures in python.

IV. Laboratory Learning Outcome


LLO 6.1 Perform basic operations on the Lists.

V. Relevant Affective Domain related Outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.

VI. Relevant Theoretical Background


In Python, a list is a fundamental data structure that allows you to store and manipulate collections of items.
Lists are ordered, mutable (modifiable), and can contain elements of different data types. They are defined by
enclosing elements within square brackets [] and separating them with commas.
Here's a detailed explanation of lists in Python with examples:

1. Creating Lists:
You can create a list by simply enclosing items within square brackets. Items can be of any data type,
including integers, floats, strings, or even other lists.
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]
nested_list = [[1, 2], [3, 4], [5, 6]] empty_list = []

2. Accessing Elements:
You can access elements of a list using indexing. Indexing starts from 0 for the first element and goes up to
len(list) - 1 for the last element.
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10 (Accessing first element)
print(my_list[-1]) # Output: 50 (Accessing last element using negative indexing)

3. Slicing Lists:
You can also access a portion of a list using slicing. Slicing allows you to create a new list containing a subset
of the original list.
my_list = [10, 20, 30, 40, 50]
Maharashtra State Board of Technical Education (K Scheme) 46
Basic Python Programming (313011)
print(my_list[1:4]) # Output: [20, 30, 40] (Slice from index 1 to 3)
print(my_list[:3]) # Output: [10, 20, 30] (Slice from start to index 2)
print(my_list[2:]) # Output: [30, 40, 50] (Slice from index 2 to end)

4. Modifying Lists:
Lists are mutable, meaning you can change the elements after creating the list. You can modify elements,
append new elements, insert elements, or remove elements.
my_list = [10, 20, 30, 40, 50]
my_list[1] = 25 # Modify element at index 1 my_list.append(60) #
Append 60 to the end of the list my_list.insert(2, 35) # Insert 35 at index 2 my_list.remove(40)
# Remove the element 40
del my_list[0] # Delete element at index 0
5. List Operations:
Lists support various operations such as concatenation (+), repetition (*), and checking membership (in).

Maharashtra State Board of Technical Education (K Scheme)


list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2 # Concatenate lists repeated_list = list1 * 3 # Repeat list 3
times
is_present = 2 in list1 # Check if 2 is present in list1 (returns True)

6. List Methods:
Python provides built-in methods to perform common operations on lists, such as sorting, reversing,
counting, and finding elements.
my_list = [4, 2, 1, 3]
my_list.sort() # Sort the list in ascending order my_list.reverse() # Reverse
the elements of the list count_1 = my_list.count(1) # Count occurrences of 1 in the list index_3 =
my_list.index(3) # Get index of first occurrence of 3

7. Nested Lists:
Lists can contain other lists as elements, enabling you to create nested data structures for more complex
data representations.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2]) # Output: 6 (Accessing element in row 1, column 2)

Lists are versatile data structures in Python that play a vital role in various programming tasks, including data
processing, manipulation, and storage. Their flexibility and wide range of built-in operations make them
indispensable for many programming tasks.

VII. Resources required


Sr. Name of Resource Specification Quantity Remarks (If
No. any)
1. Computer System Computer (i3-i5 preferable As per Batch For ALL
RAM>2GB) Size Experiments
2. Operating System Windows/Linux
3. Development Pyhton IDE
Software

Maharashtra State Board of Technical Education (K Scheme) 47


Basic Python Programming (313011)
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1) Write a Python program that takes a list of numbers as input and prints the sum of all the
elements in the list.
def calculate_sum(numbers):
"""
Calculates the sum of all elements in a list of numbers using the sum() function.

Args:
numbers: A list of integers or floats.

Returns:
The total sum of the elements.
"""
total = sum(numbers)
return total

# Example Usage:
my_list = [10, 20, 30, 40, 50]
result = calculate_sum(my_list)
print(f"The list is: {my_list}")
print(f"The sum of all elements is: {result}")
2) Create a Python program that filters out even numbers from a list of integers and prints the
filtered list.
def filter_even_numbers(numbers):
"""
Filters even numbers from a list of integers.

Args:
numbers: A list of integers.

Returns:
A new list containing only the even numbers from the input list.
"""
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
return even_numbers

# Example usage:
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_list = filter_even_numbers(original_list)
Maharashtra State Board of Technical Education (K Scheme) 48
Basic Python Programming (313011)

print(f"Original list: {original_list}")


print(f"Filtered list (even numbers only): {filtered_list}")
3) Write a Python program that reverses a given list of characters and prints the reversed list.
def reverse_list_of_chars(char_list):
"""
Reverses a given list of characters and prints the results using
three different methods.
"""
print(f"Original list: {char_list}")

# Method 1: Using slicing (creates a new list)


# This is a concise way to create a new, reversed list.
reversed_list_slicing = char_list[::-1]
print(f"Reversed list (slicing): {reversed_list_slicing}")

# Method 2: Using the [Link]() method (in-place modification)


# Note: This method modifies the original list directly and returns None.
# We work with a copy here to keep the original for other methods.
list_for_in_place_reverse = char_list[:]
list_for_in_place_reverse.reverse()
print(f"Reversed list (in-place reverse() method): {list_for_in_place_reverse}")

# Method 3: Using the built-in reversed() function (returns an iterator)


# We must convert the iterator to a list to print it.
reversed_list_function = list(reversed(char_list))
print(f"Reversed list (reversed() function): {reversed_list_function}")

# Example usage:
my_list = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
reverse_list_of_chars(my_list)

print("-" * 20)

# Another example:
another_list = ['P', 'y', 't', 'h', 'o', 'n']
reverse_list_of_chars(another_list)
4) Write a Python program that duplicates a given list of strings and prints the duplicated list.
def duplicate_list(original_list):
"""
Duplicates a given list of strings and returns the new list.

Args:
original_list: The list of strings to duplicate.

Returns:
A new list containing the same elements as the original_list.
"""
# There are several ways to duplicate a list in Python:
# 1. Using slicing (common and readable):
duplicated_list = original_list[:]

# 2. Using the list() constructor:


# duplicated_list = list(original_list)

# 3. Using the copy module for shallow copies (good practice):


Maharashtra State Board of Technical Education (K Scheme) 49
Basic Python Programming (313011)
# import copy
# duplicated_list = [Link](original_list)

return duplicated_list

# Example usage:
my_list = ["apple", "banana", "cherry"]
new_list = duplicate_list(my_list)

print(f"Original
. list: {my_list}")
print(f"Duplicated list: {new_list}")

# You can verify they are different objects in memory:


print(f"Are they the same object? {my_list is new_list}")
5) Develop a Python program that takes a list of strings as input and prints the length of the
longest string in the list.
def find_length_of_longest_string(string_list):
"""
Calculates and prints the length of the longest string in a list.
Args:
string_list: A list of strings.
"""
if not string_list:
print("The list is empty.")
return
max_length = 0
for s in string_list:
if len(s) > max_length:
max_length = len(s)

print(f"The original list of strings: {string_list}")


print(f"The length of the longest string is: {max_length}")

# Example usage:
list1 = ["apple", "banana", "cherry", "dragonfruit", "elderberry"]
find_length_of_longest_string(list1)

print("-" * 20) # Separator for clarity

list2 = ["short", "longer string", "a"]


find_length_of_longest_string(list2)

X. Exercise
Note: Faculty must ensure that every group of students use different input value. (Use blank space for
answers or attach more pages if needed)

1) Create a Python program that sorts a list of strings in ascending order and prints the
sorted list.
# Function to sort a list of strings in ascending order
def sort_strings_ascending(string_list):
"""
Sorts a list ofState
Maharashtra strings in of
Board ascending
Technical(alphabetical) order.
Education (K Scheme)
Maharashtra State Board of Technical Education (K Scheme) 50
Basic Python Programming (313011)

Args:
string_list: A list of strings.

Returns:
A new list with the strings sorted in ascending order.
"""
# The built-in sorted() function returns a new sorted list
return sorted(string_list)

# Example usage
# Define the original list of strings
list_of_strings = ["banana", "apple", "cherry", "date", "apricot"]

# Sort the list using the function


sorted_list = sort_strings_ascending(list_of_strings)

# Print the original and the sorted lists to show the result
print(f"Original list: {list_of_strings}")
print(f"Sorted list (ascending): {sorted_list}")

# Another example with mixed case (note that uppercase comes before lowercase in standard ASCII sort)
mixed_case_list = ["Zebra", "apple", "Banana", "date"]
sorted_mixed_case = sort_strings_ascending(mixed_case_list)
print(f"\nOriginal mixed-case list: {mixed_case_list}")
print(f"Sorted mixed-case list (standard ASCII): {sorted_mixed_case}")

# To sort case-insensitively, you can use the 'key' parameter with [Link]
case_insensitive_list = sorted(mixed_case_list, key=[Link])
print(f"Sorted mixed-case list (case-insensitive): {case_insensitive_list}")
2) Write a Python program that takes two lists as input and concatenates them into a
single list. Then, print the concatenated list.
def concatenate_lists(list1, list2):
"""
Concatenates two lists into a single list.

Args:
list1: The first list.
list2: The second list.

Returns:
A new list containing elements from both list1 and list2.
"""
concatenated_list = list1 + list2
return concatenated_list

# Example usage:
list_a = [1, 2, 3]
list_b = ['a', 'b', 'c']

combined_list = concatenate_lists(list_a, list_b)


print(f"List A: {list_a}")
print(f"List B: {list_b}")
print(f"Concatenated List: {combined_list}")
3) Develop a Python program that searches for a specific element in a list of strings.
Print "Element found" if the element exists; otherwise, print "Element not found".
Maharashtra State Board of Technical Education (K Scheme) 51
Basic Python Programming (313011)
def search_list(string_list, target_element):
"""
Searches for a specific element in a list of strings.

Args:
string_list: The list of strings to search through.
target_element: The element to search for.
"""
# Use the 'in' operator for efficient membership testing
if target_element in string_list:
print("Element found")
else:
print("Element not found")

# Example Usage:
my_list = ["apple", "banana", "cherry", "date"]
search_item_1 = "cherry"
search_item_2 = "grape"
print(f"Searching for '{search_item_1}':")
search_list(my_list, search_item_1)
print(f"\nSearching for '{search_item_2}':")
search_list(my_list, search_item_2)
4) Develop a Python program that creates a nested list representing a 3x3 matrix of
integers. Then, print the matrix.
# Create a 3x3 matrix as a nested list
matrix_3x3 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the matrix row by row for better readability
print("3x3 Matrix:")
for row in matrix_3x3:
print(row)
# The output will look like this:
# 3x3 Matrix:
# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]
5) Create a Python program that takes a list of integers as input and prints the sublist
containing elements from index 2 to index 5.
def print_sublist(input_list):
"""
Prints the sublist containing elements from index 2 to index 5 (inclusive of index 2, exclusive of index 6).

Args:
input_list: A list of integers.
"""
try:
# Slicing the list from index 2 up to (but not including) index 6
sublist = input_list[2:6]
print(f"The sublist from index 2 to 5 is: {sublist}")
except TypeError:
print("Error: The input must be a list.")
except IndexError:
print("Error: The list is too short to extract indices 2 through 5.")
Maharashtra State Board of Technical Education (K Scheme) 52
Basic Python Programming (313011)

# Example usage with a list that has enough elements


my_list = [10, 20, 30, 40, 50, 60, 70, 80]
print_sublist(my_list)
# Example usage with a shorter list to demonstrate error handling
short_list = [1, 2, 3]
print_sublist(short_list)
XI. References/Suggestions for further reading
1. [Link]
2. [Link]
3. [Link]

XII . Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%


1. Debugging ability 20%
2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%
1. Completion and submission of practical in time 20%
2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 53


Basic Python Programming (313011)
Practical No.7 Develop Python program to perform following operations on Tuples:
a) Create
b) Access
c) Update
d) Delete Tuple elements

I. Practical significance
Tuples in Python provide immutable data structures, ensuring data integrity and security. They are efficient
for storing fixed collections and support multiple assignments for convenient data manipulation. Additionally,
tuples can be used as dictionary keys, facilitating efficient data organization and lookup operations.

II. Industry / Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:

Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO3-Perform operations on sequence structures in python.

IV. Laboratory Learning Outcome


LLO 7.1 Execute various tuple operations.

V. Relevant Affective Domain related outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.

VI. Relevant Theoretical Background


In Python, a tuple is an immutable collection of elements, meaning once created, its contents cannot be
modified. Tuples are defined by enclosing elements within parentheses () and separating them with commas.
They can contain elements of different data types, including integers, floats, strings, or even other tuples.
Here's a detailed explanation with examples:

1. Creating Tuples:
You can create a tuple by simply enclosing elements within parentheses. Tuples can have zero or more
elements.
empty_tuple = () single_element_tuple = (5,)
multiple_elements_tuple = (1, 2, 3, 'a', 'b', 'c')
nested_tuple = ((1, 2), ('a', 'b'))

2. Accessing Elements:
You can access elements of a tuple using indexing, similar to lists. Indexing starts from 0 for the first
element and goes up to len(tuple) - 1 for the last element.
my_tuple = ('apple', 'banana', 'cherry', 'date') print(my_tuple[0]) # Output: 'apple' (Accessing first element)
print(my_tuple[-1]) # Output: 'date' (Accessing last element using negative indexing)

3. Slicing Tuples:
You can also access a portion of a tuple using slicing, which creates a new tuple containing a subset of the
original tuple.
my_tuple = ('apple', 'banana', 'cherry', 'date')
print(my_tuple[1:3]) # Output: ('banana', 'cherry') (Slice from index 1 to 2) print(my_tuple[:2]) # Output:
('apple', 'banana') (Slice from start to index 1) print(my_tuple[2:]) # Output: ('cherry', 'date') (Slice from index
2 to end)
Maharashtra State Board of Technical Education (K Scheme) 54
Basic Python Programming (313011)

4. Immutable Nature:
Unlike lists, tuples are immutable, meaning their elements cannot be changed or modified after creation.
Once a tuple is created, its contents remain fixed.
my_tuple = (1, 2, 3)
# Attempting to modify a tuple will result in an error
# my_tuple[0] = 10 # This will raise a TypeError: 'tuple' object does not support item
assignment
5. Tuple Packing and Unpacking:
Tuples support multiple assignments, allowing convenient packing and unpacking of data, which simplifies
operations like function returns and concurrent processing.

# Tuple Packing my_tuple = 10, 20, 30 # Tuple Unpacking


x, y, z = my_tuple print(x) # Output: 10 print(y) # Output: 20 print(z) # Output: 30

6. Tuples as Dictionary Keys:


Tuples are hashable and can be used as keys in dictionaries, unlike lists, which makes them suitable for
dictionary keys when representing composite keys or immutable data.
my_dict = {('John', 25): 'Engineer', ('Alice', 30): 'Manager'} print(my_dict[('John', 25)]) # Output: 'Engineer'
print(my_dict[('Alice', 30)]) # Output: 'Manager'

Tuples are versatile data structures in Python, useful for representing fixed collections of elements and
ensuring data integrity in scenarios where immutability is required.

VII. Resources required


Sr. Name of Resource Specification Quantity Remarks (If
No. any)
1. Computer System Computer (i3-i5 preferable As per Batch For ALL
RAM>2GB) Size Experiments
2. Operating System Windows/Linux
3. Development Pyhton IDE
Software

VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If


any)
1. Computer System
2. Operating System
3. Development
Software

Maharashtra State Board of Technical Education (K Scheme) 55


Basic Python Programming (313011)

IX. Practical related questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1) Write a Python program that takes a tuple and an additional element as input, then creates a
new tuple with the added element. Print the original tuple and the modified tuple.
def add_element_to_tuple(original_tuple, element_to_add):
"""
Creates a new tuple by appending an element to an existing tuple.

Args:
original_tuple: The initial tuple.
element_to_add: The element to append.

Returns:
A new tuple containing all elements of the original_tuple plus the new element.
"""
# Tuples are immutable, so we create a new one using the '+' operator (concatenation)
# The element to add must be wrapped in a tuple itself (using a trailing comma)
modified_tuple = original_tuple + (element_to_add,)
return modified_tuple

# --- Example Usage ---


# 1. Define the initial tuple and the element to add
initial_tuple = (10, 20, 30, "apple")
new_element = 40.5

# 2. Call the function to create the new tuple


result_tuple = add_element_to_tuple(initial_tuple, new_element)

# 3. Print both the original and modified tuples


print(f"Original tuple: {initial_tuple}")
print(f"Modified tuple: {result_tuple}")
2) Develop a Python program that takes a tuple and an index as input, then replaces the
element at the specified index with a new value. Print the original tuple and themodified tuple.
def replace_tuple_element(original_tuple, index_to_replace, new_value):
"""
Replaces an element at a specified index in a tuple by converting it
to a list, modifying the list, and converting it back to a tuple.

Args:
original_tuple: The input tuple.
index_to_replace: The index of the element to replace.
new_value: The new value to insert at the index.

Returns:
The new modified tuple.
"""
# 1. Convert the tuple to a list
temp_list = list(original_tuple)

# 2. Modify the element at the specified index in the list


try:
temp_list[index_to_replace] = new_value
Maharashtra State Board of Technical Education (K Scheme)
56
Basic Python Programming (313011)
except IndexError:
print(f"Error: Index {index_to_replace} is out of bounds for the tuple.")
return original_tuple # Return original if modification fails

# 3. Convert the modified list back to a tuple


modified_tuple = tuple(temp_list)

return modified_tuple

# --- Example Usage ---


my_tuple = (10, 20, 30, 40, 50)
index_to_change = 2
new_element = 999

modified_tuple = replace_tuple_element(my_tuple, index_to_change, new_element)

print(f"Original Tuple: {my_tuple}")


print(f"Modified Tuple: {modified_tuple}")

# --- Example with a different index and type ---


another_tuple = ('apple', 'banana', 'cherry')
another_index = 0
another_value = 'orange'

new_fruit_tuple = replace_tuple_element(another_tuple, another_index, another_value)

print(f"\nOriginal Tuple: {another_tuple}")


print(f"Modified Tuple: {new_fruit_tuple}")
3) Create a Python program that takes a tuple and an index as input, then creates a new tuple
with the element at the specified index removed. Print the original tuple and the modified tuple.
def remove_element_at_index(original_tuple, index_to_remove):
"""
Creates a new tuple with the element at the specified index removed.

Args:
original_tuple: The input tuple.
index_to_remove: The index of the element to remove.

Returns:
A new tuple with the element at the specified index removed,
or the original tuple if the index is out of range.
"""
# Check if the index is valid
if 0 <= index_to_remove < len(original_tuple):
# Slicing the tuple to create a new tuple without the element at the specified index
# The first slice (up to the index) is concatenated with the second slice (from index + 1 to the end)
modified_tuple = original_tuple[:index_to_remove] + original_tuple[index_to_remove + 1:]
return modified_tuple
else:
print(f"Error: Index {index_to_remove} is out of range for the tuple {original_tuple}")
return original_tuple

# Example usage
my_tuple = ("apple", "banana", "cherry", "date", "elderberry")
index_to_remove_val = 2 # Index of "cherry"
Maharashtra State Board of Technical Education (K Scheme)
57
Basic Python Programming (313011)

modified_tuple_result = remove_element_at_index(my_tuple, index_to_remove_val)

print(f"Original tuple: {my_tuple}")


print(f"Modified tuple: {modified_tuple_result}")

# Example with an invalid index


invalid_index = 10
remove_element_at_index(my_tuple, invalid_index)
4) Write a Python program that takes a tuple, an index, and a new value as input, then creates a
new tuple with the element at the specified index updated with the new value. Print the original tuple and the
modified tuple.
def update_tuple_element(original_tuple, index, new_value):
"""
Creates a new tuple with the element at the specified index updated.
Args:
original_tuple: The input tuple.
index: The index of the element to update.
new_value: The new value for the specified index.
Returns:
A new tuple with the updated value, or the original tuple if the index is invalid.
"""
# Tuples are immutable, so we must convert to a list to modify
temp_list = list(original_tuple)
# Check if the index is within the valid range
if 0 <= index < len(temp_list):
temp_list[index] = new_value
# Convert back to a tuple
modified_tuple = tuple(temp_list)
return modified_tuple
else:
print(f"Error: Index {index} is out of range for the tuple.")
return original_tuple
# --- Example Usage ---
# 1. Define the inputs
my_tuple = (10, 20, 30, 40, 50)
update_index = 2
new_value = 99
# 2. Call the function to get the modified tuple
new_tuple = update_tuple_element(my_tuple, update_index, new_value)
# 3. Print the results
print(f"Original Tuple: {my_tuple}")
print(f"Modified Tuple: {new_tuple}")
# --- Example with invalid index ---
print("\n--- Invalid Index Example ---")
invalid_index = 10
invalid_tuple = update_tuple_element(my_tuple, invalid_index, 1000)
print(f"Original Tuple: {my_tuple}")
print(f"Resulting Tuple (unchanged): {invalid_tuple}")
5) Write a Python program that takes two tuples as input and concatenates them into a single
tuple. Then, print the concatenated tuple
# Function to concatenate two tuples
def concatenate_tuples(tuple1, tuple2):
"""
This function takes two tuples as input and concatenates them into a single tuple.
Maharashtra State Board of Technical Education (K Scheme)
58
Basic Python Programming (313011)

Args:
tuple1: The first tuple.
tuple2: The second tuple.
Returns:
A new tuple containing elements from both input tuples.
"""
concatenated_tuple = tuple1 + tuple2
return concatenated_tuple
# Get input from the user (example input if running as a script)
# For a real interactive program, you might use more complex input handling,
# but for demonstration, we use predefined tuples.
# Example 1
tup_a = (1, 2, 3)
tup_b = ('a', 'b', 'c')
# Example 2
# tup_a = (10, 20)
# tup_b = (30, 40, 50)
# Concatenate the tuples
result_tuple = concatenate_tuples(tup_a, tup_b)

# Print the original tuples and the result


print(f"First tuple: {tup_a}")
print(f"Second tuple: {tup_b}")
print(f"Concatenated tuple: {result_tuple}")
6) Write a Python program that takes two tuples of integers as input and calculates the
element-wise sum of corresponding elements in the tuples. Then, print the resulting tuple.
def elementwise_tuple_sum(tuple1, tuple2):
"""
Calculates the element-wise sum of two integer tuples.
Args:
tuple1: The first tuple of integers.
tuple2: The second tuple of integers.
Returns:
A new tuple containing the element-wise sums, or None if tuples have different lengths.
"""
if len(tuple1) != len(tuple2):
print("Error: Tuples must be of the same length for element-wise summation.")
return None

# Use a list comprehension and the zip function to sum corresponding elements
result_list = [a + b for a, b in zip(tuple1, tuple2)]

# Convert the resulting list back into a tuple


result_tuple = tuple(result_list)
return result_tuple

# --- Example Usage ---

# Define the input tuples


tuple_a = (1, 2, 3)
tuple_b = (4, 5, 6)

# Calculate the element-wise sum


sum_tuple = elementwise_tuple_sum(tuple_a, tuple_b)
Maharashtra State Board of Technical Education (K Scheme)
59
Basic Python Programming (313011)

# Print the result if successful


if sum_tuple is not None:
print(f"Tuple A: {tuple_a}")
print(f"Tuple B: {tuple_b}")
print(f"Element-wise sum: {sum_tuple}")

# --- Example with different lengths (error case) ---


print("\nTesting with different lengths:")
tuple_c = (10, 20)
tuple_d = (1, 2, 3)
elementwise_tuple_sum(tuple_c, tuple_d)

X. Exercise
Note: Faculty must ensure that every group of students use different input value. (Use blank space for
answers or attach more pages if needed)
1) Develop a Python program that takes a tuple of (x, y) coordinates as input and unpacks
it into separate variables. Then, calculate the distance between the two points using the distance formula.
import math

def calculate_distance(p1, p2):


"""
Calculates the distance between two points (x1, y1) and (x2, y2).

Args:
p1 (tuple): The first point as a tuple of (x1, y1) coordinates.
p2 (tuple): The second point as a tuple of (x2, y2) coordinates.

Returns:
float: The Euclidean distance between the two points.
"""
# Unpack the tuples into separate variables
x1, y1 = p1
x2, y2 = p2

# Calculate the differences in coordinates


dx = x2 - x1
dy = y2 - y1

# Apply the distance formula: sqrt((x2 - x1)^2 + (y2 - y1)^2)


distance = [Link](dx**2 + dy**2)

return distance

# --- Example Usage ---

# Define the two points as tuples of (x, y) coordinates


point1 = (1, 2)
point2 = (4, 6)

# Calculate the distance between them


dist = calculate_distance(point1, point2)

# Print the results


Maharashtra State Board of Technical Education (K Scheme)
60
Basic Python Programming (313011)
print(f"Point 1: {point1}")
print(f"Point 2: {point2}")
print(f"The distance between the points is: {dist}")
2) Create a Python program that sorts a tuple of strings in alphabetical order and prints the
sorted tuple.
def sort_tuple_alphabetically(input_tuple):
"""
Sorts a tuple of strings in alphabetical order and returns a new sorted tuple.

Args:
input_tuple: A tuple of strings to be sorted.

Returns:
A new tuple containing the strings in alphabetical order.
"""
# Convert the tuple to a list for sorting (tuples are immutable)
temp_list = list(input_tuple)

# Sort the list alphabetically in place


temp_list.sort()

# Convert the sorted list back to a tuple


sorted_tuple = tuple(temp_list)

return sorted_tuple

# --- Example Usage ---


# Define a sample tuple of strings
original_tuple = ("banana", "apple", "cherry", "date", "fig")

# Sort the tuple using the function


result_tuple = sort_tuple_alphabetically(original_tuple)

# Print the original and the sorted tuple


print(f"Original tuple: {original_tuple}")
print(f"Sorted tuple: {result_tuple}")

# Another example with mixed cases (Python sorting is case-sensitive by default)


mixed_case_tuple = ("Zebra", "apple", "Banana", "orange")
sorted_mixed_case = sort_tuple_alphabetically(mixed_case_tuple)
print(f"\nMixed case original: {mixed_case_tuple}")
print(f"Mixed case sorted: {sorted_mixed_case}")
3) Develop a Python program that searches for a specific element in a tuple of strings.
Print "Element found" if the element exists; otherwise, print "Element not found".
# Function to search for an element in a tuple of strings
def search_tuple_element(string_tuple, element_to_find):
"""
Searches for a specific element in a tuple of strings.

Args:
string_tuple: The tuple of strings to search within.
element_to_find: The specific element to search for.
"""
if element_to_find in string_tuple:
print("Element found")
Maharashtra State Board of Technical Education (K Scheme)
61
Basic Python Programming (313011)
else:
print("Element not found")

# --- Example Usage ---

# Define the tuple of strings


my_tuple = ("apple", "banana", "cherry", "date", "elderberry")

# Example 1: Search for an element that exists


search_item_1 = "cherry"
print(f"Searching for '{search_item_1}':")
search_tuple_element(my_tuple, search_item_1)

# Example 2: Search for an element that does not exist


search_item_2 = "grape"
print(f"\nSearching for '{search_item_2}':")
search_tuple_element(my_tuple, search_item_2)

# Example 3: Search for a case-sensitive match


search_item_3 = "Apple"
print(f"\nSearching for '{search_item_3}':")
search_tuple_element(my_tuple, search_item_3)
4) Develop a Python program that checks if a given element exists in a tuple of integers.
Print "Element found" if the element exists; otherwise, print "Element not found"
def check_element_in_tuple(element_to_find, integer_tuple):
"""
Checks if a given element exists in a tuple of integers.

Args:
element_to_find: The element to search for.
integer_tuple: The tuple to search within.
"""
if element_to_find in integer_tuple:
print("Element found")
else:
print("Element not found")

# --- Example Usage ---

# Define the tuple of integers


my_tuple = (10, 20, 30, 40, 50)

# Example 1: Element exists


search_element_1 = 30
print(f"Checking for element {search_element_1}...")
check_element_in_tuple(search_element_1, my_tuple) # Output: Element found

print("-" * 20)

# Example 2: Element does not exist


search_element_2 = 99
print(f"Checking for element {search_element_2}...")
check_element_in_tuple(search_element_2, my_tuple) # Output: Element not found
5) Write a Python program that compares two tuples element-wise and prints "Equal" if all
corresponding elements are equal; otherwise, print "Not equal".
Maharashtra State Board of Technical Education (K Scheme)
62
Basic Python Programming (313011)
def are_tuples_equal_elementwise(tuple1, tuple2):
# Check if the tuples have the same length first
if len(tuple1) != len(tuple2):
return False

# Iterate through both tuples simultaneously and compare elements


for elem1, elem2 in zip(tuple1, tuple2):
if elem1 != elem2:
return False

# If the loop finishes without finding any inequality, they are equal
return True

# --- Example Usage ---

tuple_a = (1, 2, 'a', 'b')


tuple_b = (1, 2, 'a', 'b')
tuple_c = (1, 2, 'a', 'c')
tuple_d = (1, 2, 'a')

# Compare tuple_a and tuple_b


if are_tuples_equal_elementwise(tuple_a, tuple_b):
print(f"Tuples {tuple_a} and {tuple_b}: Equal")
else:
print(f"Tuples {tuple_a} and {tuple_b}: Not equal")

# Compare tuple_a and tuple_c


if are_tuples_equal_elementwise(tuple_a, tuple_c):
print(f"Tuples {tuple_a} and {tuple_c}: Equal")
else:
print(f"Tuples {tuple_a} and {tuple_c}: Not equal")

# Compare tuple_a and tuple_d (different lengths)


if are_tuples_equal_elementwise(tuple_a, tuple_d):
print(f"Tuples {tuple_a} and {tuple_d}: Equal")
else:
print(f"Tuples {tuple_a} and {tuple_d}: Not equal")
6) Create a Python program that takes a tuple of integers as input and repeats each element
three times in a new tuple. Then, print the resulting tuple.
def repeat_elements(input_tuple):
"""
Repeats each element of an input tuple three times in a new tuple.
Args:
input_tuple: A tuple of integers.
Returns:
A new tuple with each element repeated three times.
"""
result_list = []
for element in input_tuple:
result_list.extend([element] * 3)
return tuple(result_list)

# Example usage:
# Create a sample tuple of integers
my_tuple = (1, 2, 3, 4)
Maharashtra State Board of Technical Education (K Scheme)
63
Basic Python Programming (313011)

# Call the function and store the result


repeated_tuple = repeat_elements(my_tuple)

# Print the resulting tuple


print(f"Original tuple: {my_tuple}")
print(f"Repeated tuple: {repeated_tuple}")

# Another example:
another_tuple = (5, 10, 15)
print(f"Original tuple: {another_tuple}")
print(f"Repeated tuple: {repeat_elements(another_tuple)}")
7) Write a Python program that takes a tuple of strings as input and prints the length of the
longest string in the tuple.
def find_length_of_longest_string(string_tuple):
"""
Calculates and prints the length of the longest string in a tuple of strings.
Args:
string_tuple: A tuple containing strings.
"""
if not string_tuple:
print("The tuple is empty.")
return

max_length = 0
for s in string_tuple:
if len(s) > max_length:
max_length = len(s)

print(f"The longest string has a length of: {max_length}")

# Example Usage:
# Example 1:
my_tuple1 = ("apple", "banana", "cherry", "date", "elderberry")
find_length_of_longest_string(my_tuple1)

# Example 2:
my_tuple2 = ("short", "longer string", "a")
find_length_of_longest_string(my_tuple2)

# Example 3:
my_tuple3 = ()
find_length_of_longest_string(my_tuple3)
8) Create a Python program that takes a tuple of strings as input and prints the second
element of the tuple.
def print_second_element(input_tuple):
"""
Prints the second element of a tuple, if it exists.

Args:
input_tuple: A tuple of strings.
"""
try:
# Access the element at index 1 (the second element)
second_element = input_tuple[1]
Maharashtra State Board of Technical Education (K Scheme)
64
Basic Python Programming (313011)
print(f"The second element is: {second_element}")
except IndexError:
print("The tuple does not have a second element (it has 0 or 1 elements).")
except TypeError:
print("Invalid input. Please provide a tuple.")

# Example usage:
# A valid tuple with at least two elements
my_tuple = ("apple", "banana", "cherry")
print(f"Testing with: {my_tuple}")
print_second_element(my_tuple)
print("-" * 20)

# A tuple with only one element (will cause an IndexError)


short_tuple = ("grape",)
print(f"Testing with: {short_tuple}")
print_second_element(short_tuple)

print("-" * 20)

# An empty tuple (will cause an IndexError)


empty_tuple = ()
print(f"Testing with: {empty_tuple}")
print_second_element(empty_tuple)

XI. References/Suggestions for further reading


1. [Link]
2. [Link]
3. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%


1. Debugging ability 20%
2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%
1. Completion and submission of practical in time 20%
2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme)


65
Basic Python Programming (313011)
Practical No.8 Write Python program to perform following operations on Set:
a) Create
b) Access
c) Update
d) Delete Access Set elements

I. Practical significance

Sets in Python provide an efficient way to store and manipulate unique elements, automatically eliminating
duplicates. They support fast membership testing, makingthem ideal for tasks like filtering out repeated items
and performing set operations like union, intersection, and difference. This makes sets particularly useful for
handlingcollections of data where uniqueness and efficient lookups are crucial.

II. Industry / Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome
through various teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.
III. Course Level Learning Outcome
CO3- Perform operations on sequence structures in python.

IV. Laboratory Learning Outcome


LLO 8.1 Implement various set operations.

V. Relevant Affective Domain related outcome(s)


1. Follow safety practices.
2. Demonstrate working as a leader / a team member.
3. Follow ethical practices.

VI. Relevant Theoretical Background


A set is an unordered collection of unique elements. This means that no element can appear more than once in a
set. Sets are mutable, meaning you can add or remove elements from them after they are created. They are
particularly useful for membership testing, removing duplicates from a sequence, and performing
mathematical set operations like union, intersection, difference, and symmetric difference.

1. Creating a Set
You can create a set by placing all the items (elements) inside curly braces {}, separated by commas, or by
using the built-in set() function.
# Creating a set using curly braces my_set = {1, 2, 3, 4, 5} print("Set:", my_set)

# Creating a set using the set() function


my_set = set([1, 2, 3, 4, 5])
print("Set:", my_set)

# Creating an empty set


empty_set = set()
print("Empty Set:", empty_set)
Maharashtra State Board of Technical Education (K Scheme)
66
2. Adding Elements to a Set
Basic Python Programming (313011)

print("Set after adding 5 and 6:", my_set)

3. Removing Elements from a Set


You can remove elements using the remove() method, discard() method, or pop() method. The remove()
method will raise a KeyError if the element is not found, while the discard() method will not.
my_set = {1, 2, 3, 4, 5} print("Original Set:", my_set)

# Removing an element my_set.remove(4)


print("Set after removing 4:", my_set)

# Discarding an element my_set.discard(3)

print("Set after discarding 3:", my_set)

# Removing an element using pop (removes an arbitrary element)


popped_element = my_set.pop()
print("Popped Element:", popped_element)
print("Set after popping an element:", my_set)

4. Set Operations
Sets support various mathematical operations.
Union: Combines elements from both sets (all unique elements).
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = [Link](set2)
print("Union:", union_set)

Intersection: Returns elements that are common in both sets.


set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = [Link](set2)
print("Intersection:", intersection_set)
Difference: Returns elements that are in the first set but not in the second. set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = [Link](set2) print("Difference:", difference_set)

Symmetric Difference: Returns elements that are in either of the sets, but not in both. set1 = {1, 2, 3}

Maharashtra State Board of Technical Education (K Scheme)


67
Basic Python Programming (313011)
set2 = {3,.........................................................................................................................................................
4, 5}
sym_diff_set = set1.symmetric_difference(set2) print("Symmetric Difference:", sym_diff_set)
Membership.........................................................................................................................................................
Testing : You can test if an element is a member of a set using the in keyword.
my_set = .........................................................................................................................................................
{1, 2, 3}
print(1 in my_set) # Output: True print(4 in my_set) # Output: False
Sets are a.........................................................................................................................................................
powerful feature in Python that help in handling collections of unique elements and performing
efficient membership tests and set operations.
.........................................................................................................................................................
VII. Resources required
.........................................................................................................................................................
Sr. Name of Resource Specification Quantity Remarks (If any)
No.
1. Computer System Computer (i3-i5 preferable As per Batch For ALL
RAM>2GB) Size Experiments
2. Operating System Windows/Linux
3. Development Pyhton IDE
Software
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If


any)
1. Computer System
2. Operating System
3. Development Software

IX. Practical related questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1. Create a Python program that takes two sets of numbers as input and returns a new set that is the
union of the two sets.
def set_union(set1, set2):
"""
Calculates the union of two sets using the union operator.

Args:
set1: The first set of numbers.
set2: The second set of numbers.

Returns:
A new set containing all unique elements from both sets.
"""
# Using the '|' operator
# return set1 | set2

# Alternatively, using the .union() method


return [Link](set2)

# --- Example Usage ---


# Define the input sets
numbers_set1 = {1, 2, 3, 4, 5}
numbers_set2 = {4, 5, 6, 7, 8}

# Call the function to find the union


union_set = set_union(numbers_set1, numbers_set2)

# Print the original sets and the resulting union set


68
Basic Python Programming (313011)
print(f"Set.........................................................................................................................................................
1: {numbers_set1}")
print(f"Set 2: {numbers_set2}")
.........................................................................................................................................................
print(f"Union of the sets: {union_set}")
2. Write a Python program that takes two sets of numbers as input and returns a new set that contains
.........................................................................................................................................................
elements that are in the first set but not in the second set.
.........................................................................................................................................................
def difference_of_sets(set1, set2):
""" .........................................................................................................................................................
Calculates the difference between two sets (elements in set1 but not in set2).
.........................................................................................................................................................
Args:
set1: The first set of numbers.
set2: The second set of numbers.

Returns:
A new set containing elements that are in set1 but not in set2.
"""
# The difference() method or the '-' operator can be used for set difference
return [Link](set2)
# Alternatively: return set1 - set2

# --- Example Usage ---

# 1. Define the input sets


set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

# 2. Call the function to find the difference (A - B)


result_set = difference_of_sets(set_a, set_b)

# 3. Print the results


print(f"Set A: {set_a}")
print(f"Set B: {set_b}")
print(f"Elements in A but not in B: {result_set}")

# Another example (B - A)
result_set_b_minus_a = difference_of_sets(set_b, set_a)
print(f"\nElements in B but not in A: {result_set_b_minus_a}")
3. Develop a Python program that takes two sets of numbers as input and returns a new set that
contains elements that are in either of the sets but not in both.
def symmetric_difference_sets(set1, set2):
"""
Calculates the symmetric difference between two sets.

The symmetric difference contains elements that are in either of the sets
but not in their intersection (i.e., not in both).

Args:
set1: The first input set.
set2: The second input set.

Returns:
A new set containing the symmetric difference elements.
"""
# Using the symmetric_difference() method or the ^ operator
# return set1.symmetric_difference(set2)
return set1 ^ set2
69
Basic Python Programming (313011)
.........................................................................................................................................................
# --- Example Usage ---
.........................................................................................................................................................
# Example.........................................................................................................................................................
1: Basic sets
s1 = {1, 2, 3, 4}
s2 = {3, 4,.........................................................................................................................................................
5, 6}
result1 = symmetric_difference_sets(s1, s2)
.........................................................................................................................................................
print(f"Set 1: {s1}")
print(f"Set.........................................................................................................................................................
2: {s2}")
print(f"Symmetric Difference: {result1}")
# Expected output: {1, 2, 5, 6}

print("-" * 20)

# Example 2: Different data types (sets can hold mixed types, but typically stick to one)
a = {10, 20, 30, 'apple'}
b = {20, 40, 'apple', 'banana'}
result2 = symmetric_difference_sets(a, b)
print(f"Set A: {a}")
print(f"Set B: {b}")
print(f"Symmetric Difference: {result2}")
# Expected output: {10, 30, 40, 'banana'}

print("-" * 20)

# Example 3: One empty set


c = {1, 2, 3}
d = set() # Empty set
result3 = symmetric_difference_sets(c, d)
print(f"Set C: {c}")
print(f"Set D: {d}")
print(f"Symmetric Difference: {result3}")
# Expected output: {1, 2, 3}
4. Create a Python program that checks if a given element is present in a set. Print "Element found"
if the element exists in the set; otherwise, print "Element not found".
# Function to check for element presence in a set
def check_element_in_set(input_set, element_to_find):
"""
Checks if a given element is present in a set.

Args:
input_set: The set to check within.
element_to_find: The element to search for.
"""
if element_to_find in input_set:
print(f"'{element_to_find}' found")
else:
print(f"'{element_to_find}' not found")

# --- Example Usage ---

# Define a sample set


my_set = {10, 20, 30, 40, 50}

# Define elements to check


element1 = 30
70
Basic Python Programming (313011)
element2 .........................................................................................................................................................
= 99
.........................................................................................................................................................
print(f"Set: {my_set}\n")
.........................................................................................................................................................
# Check for the first element
.........................................................................................................................................................
print(f"Checking for {element1}:")
check_element_in_set(my_set, element1)
.........................................................................................................................................................

print("-" *.........................................................................................................................................................
20)

# Check for the second element


print(f"Checking for {element2}:")
check_element_in_set(my_set, element2)
5. Write a Python program that checks if one set is a subset of another set. Print "Subset" if it is a
subset; otherwise, print
# Define two example sets
set_a = {1, 2, 3, 4, 5}
set_b = {2, 4, 5}

# Check if set_b is a subset of set_a using the 'issubset' method


if set_b.issubset(set_a):
print("Subset")
else:
print("Not a subset")

# Alternatively, the '<=' operator can be used:


if set_b <= set_a:
print("Subset")
else:
print("Not a subset")

X. Exercise
Note: Faculty must ensure that every group of students use different input value. (Use blank space for
answers or attach more pages if needed)
1. Write a Python program that takes a sentence and returns a set of unique words.
import string

def get_unique_words(sentence):
"""
Takes a sentence (string) and returns a set of unique,
lowercase words, with punctuation removed.
"""
# 1. Convert to lowercase to treat "Word" and "word" as the same
sentence = [Link]()

# 2. Remove punctuation by replacing each punctuation mark with an empty string


# This step ensures that "words," and "words" are treated the same
for punctuation_mark in [Link]:
sentence = [Link](punctuation_mark, "")

# 3. Split the sentence into a list of words


words_list = [Link]()

# 4. Convert the list of words into a set to get unique elements


unique_words_set = set(words_list)
71
Basic Python Programming (313011)
.........................................................................................................................................................
return unique_words_set
.........................................................................................................................................................
# --- Example Usage ---
.........................................................................................................................................................
sample_sentence = "This is a sample sentence. This sentence has sample words."
.........................................................................................................................................................
unique_words = get_unique_words(sample_sentence)
.........................................................................................................................................................
.........................................................................................................................................................
print(f"Original sentence: {sample_sentence}")
print(f"Set of unique words: {unique_words}")

# Another example:
another_sentence = "Hello world! How are you doing, world?"
unique_words_2 = get_unique_words(another_sentence)
print(f"\nOriginal sentence: {another_sentence}")
print(f"Set of unique words: {unique_words_2}")
2. Write a Python program that checks if a given element is present in a set.
def check_element_in_set(element_to_find, target_set):
"""
Checks if a given element is present in a set.

Args:
element_to_find: The element to search for.
target_set: The set to search within.

Returns:
bool: True if the element is found, False otherwise.
"""
if element_to_find in target_set:
return True
else:
return False

# --- Example Usage ---

# Define the set


my_set = {10, 20, 30, 40, 50}

# Elements to check
check_1 = 30
check_2 = 99

# Perform the checks and print results


is_present_1 = check_element_in_set(check_1, my_set)
print(f"Is {check_1} in the set? {is_present_1}")

is_present_2 = check_element_in_set(check_2, my_set)


print(f"Is {check_2} in the set? {is_present_2}")

# You can also use the 'in' keyword directly in conditional statements:
if 50 in my_set:
print("50 is definitely in the set!")
3. Write a Python program that takes multiple sets and print their intersection.
def sets_intersection(*sets_list):
"""
Calculates and prints the intersection of multiple sets.

Args:
*sets_list: A variable number of sets.

72
Basic Python Programming (313011)
""" .........................................................................................................................................................
if not sets_list:
.........................................................................................................................................................
print("No sets provided for intersection.")
return .........................................................................................................................................................

# Start with the first set as the initial intersection


.........................................................................................................................................................
intersection_result = sets_list[0]
.........................................................................................................................................................
# Iterate through the rest of the sets and perform intersection
.........................................................................................................................................................
for current_set in sets_list[1:]:
intersection_result = intersection_result.intersection(current_set)

print(f"The sets provided are: {sets_list}")


print(f"The intersection of the sets is: {intersection_result}")

# Example Usage:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {3, 4, 5, 9, 10}

sets_intersection(set1, set2, set3)

# Another example with different data types:


setA = {'apple', 'banana', 'cherry'}
setB = {'google', 'microsoft', 'apple'}
setC = {'apple', 'facebook', 'amazon'}

sets_intersection(setA, setB, setC)


4. Write a Python program that generates a set of squares of all even numbers between 1 and 10.

# Generate a set of squares of all even numbers between 1 and 10 (inclusive)

# Method 1: Using a set comprehension (Recommended for conciseness)


# This is the most Pythonic way to achieve the desired result.
# The expression (n * n) calculates the square of the number,
# the 'for n in range(1, 11)' iterates through numbers 1 to 10,
# and the 'if n % 2 == 0' filters for only the even numbers.
squares_of_evens_comprehension = {n * n for n in range(1, 11) if n % 2 == 0}

# Print the resulting set


print("Set using comprehension:", squares_of_evens_comprehension)

# Method 2: Using a traditional for loop


# This approach is more explicit and easier to understand for beginners.
squares_of_evens_loop = set() # Initialize an empty set
for n in range(1, 11):
if n % 2 == 0:
squares_of_evens_loop.add(n * n) # Add the square to the set

# Print the resulting set


print("Set using for loop:", squares_of_evens_loop)

# Expected output for both methods: {4, 16, 36, 64, 100}

73
Basic Python Programming (313011)
XI. References/Suggestions for further reading
1. [Link]
2. [Link]
3. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%


1. Debugging ability 20%
2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%
1. Completion and submission of practical in time 20%
2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme)


74
Basic Python Programming(313011)

Practical No.9: *Create a program to perform following operations on Dictionaries in Python:


a) Create
b) Access
c) Update
d) Delete
e) Looping through Dictionary

I. Practical Significance

Python dictionaries allow us to associate a value to a unique key, and then to quickly access this value .
Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered,
changeable and does not allow duplicates.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various teaching
learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO3 - Perform operations on sequence structures in python.
IV. Laboratory Learning Outcome
LLO 9.1 Execute various operations on Dictionaries.

V. Relevant Affective Domain related outcome(s)

a) Follow safety practices.


b) Demonstrate working as a leader / a team member.
c) Follow ethical practices.

VI. Relevant Theoretical Background


Python dictionary is a container of key-value pairs. It is mutable and can contain mixed types. A dictionary is an
unordered collection. Python dictionaries are called associative arrays or hash tables in other languages. The
keys in a dictionary must be immutable objects like strings or numbers. They must also be unique within a
dictionary.

a) Creating the Dictionary

The most common method is to use curly braces {} separating the keys and values by colons. For example, the
following example creates a dictionary with three items:

The syntax to define the dictionary is given below:

dict = {"name": "John", "age": 30, "city": "New York"}

b) Accessing Values in Dictionary:


To access dictionary elements, use square brackets along with the key to obtain its value. To extract values,
use the following format:

dictionary[key]

Maharashtra State Board of Technical Education (K Scheme) 75


Basic Python Programming(313011)
Example:
dict = {“name”: “John”, “age”: 30, “city”: “New York”} name = dict[“name”] # Get value assigned to the
“name” key print(name)

Output:
John

c) Updating Dictionary: You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry.

Example 1:
dict = {"name": "John", "age": 30, "city": "New York"} print(dict) # Before modification
dict["age"] = 35
print(dict) # After modification

Output Before: {'name': 'John', 'age': 30, 'city': 'New York'}


Output After: {'name': 'John', 'age': 35, 'city': 'New York'}

Example 2:
dict = {"name": "John", "age": 30, "city": "New York"} dict["gender"] = "male" # Add new key-value pair
print(dict)

Output:
{"name": "John", "age": 30, "city": "New York","gender":"male"}
d) Creating the Dictionary

The most common method is to use curly braces {} separating the keys and values by colons. For example, the
following example creates a dictionary with three items:

The syntax to define the dictionary is given below:

e) Creating the Dictionary

The most common method is to use curly braces {} separating the keys and values by colons. For example, the
following example creates a dictionary with three items:
The syntax to define the dictionary is given below:

dict = {"name": "John", "age": 30, "city": "New York"}

f) Accessing Values in Dictionary:

To access dictionary elements, use square brackets along with the key to obtain its value. To extract values, use
the following format:

dictionary[key]
Example:

dict = {“name”: “John”, “age”: 30, “city”: “New York”} name = dict[“name”] # Get value assigned to the
“name” key print(name)

Maharashtra State Board of Technical Education (K Scheme) 76


Basic Python Programming(313011)
Output:
John
g) Updating Dictionary: You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry.
Example 1:
dict = {"name": "John", "age": 30, "city": "New York"} print(dict) # Before modification
dict["age"] = 35
print(dict) # After modification

Output Before: {'name': 'John', 'age': 30, 'city': 'New York'}


Output After: {'name': 'John', 'age': 35, 'city': 'New York'}

Example 2:
dict = {"name": "John", "age": 30, "city": "New York"} dict["gender"] = "male" # Add new key-value pair
print(dict)

Output:
{"name": "John", "age": 30, "city": "New York","gender":"male"}
h) Delete Dictionary Elements:
To remove individual dictionary elements or clear the entire contents of a dictionary or to delete entire dictionary
in a single operation or to explicitly remove an entire dictionary, just use the del statement.
Example:
dict = {"name": "John", "age": 30, "city": "New York"} del dict['name']; # remove entry with key 'name'
Output:
{"age": 30, "city": "New York"} [Link](); # remove all entries in dict del dict ; # delete entire dictionary
i) Looping through Dictionary:

A dictionary can be iterated using the for loop. If you want to get both keys and the values in the output. You
just have to add the keys and values as the argument of the print statement in comma separation. After each
iteration of the for loop, you will get both the keys its relevant values in the output.

Example
dict = {"name": "John", "age": 30, "city": "New York"} for key, value in [Link]():
print(key, ' - ', value)

Output:
name - John age - 30 city – New York

VII. Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software

Maharashtra State Board of Technical Education (K Scheme) 77


Basic Python Programming(313011)

VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.

1. Write the output of the following program.

dict = {1:"Photodiode", 2:"Zener diode", 3:" Schottky diode",4: "P-N junction diode"} del dict[1];
for key, val in [Link](): print(key)
for key, val in [Link](): print(key,values)
del dictionary:
for key, val in [Link](): print(key)

2. Write the output of the following program.

dict1 = {'Amplifiers': „BJT‟, 'Transistor': „PNP‟} dict2 = {'FET':10, 'MOSFET': 5}


[Link](dict2) print(dict1)

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a Python script to iterate over dictionaries using for loops.


# Sample dictionary
student_scores = {
'Alice': 92,
'Bob': 88,
'Charlie': 95,
'David': 79
}

print("Iterating over keys only:")


# Iterate over keys (default behavior)
for name in student_scores:
score = student_scores[name]
print(f"{name}'s score is {score}")

print("\nIterating over keys using .keys():")


Maharashtra State Board of Technical Education (K Scheme) 78
Basic Python Programming(313011)
# Explicitly iterate over keys
for name in student_scores.keys():
score = student_scores[name]
print(f"{name}'s score is {score}")

print("\nIterating over values only using .values():")


# Iterate over values
for score in student_scores.values():
print(f"A student's score is {score}")

print("\nIterating over key-value pairs using .items():")


# Iterate over key-value pairs using .items() (most common and efficient)
for name, score in student_scores.items():
print(f"{name}'s score is {score}")
2. Write a Python script to change the value of a dictionary element by referring to its key.
# Sample dictionary
student_scores = {
'Alice': 85,
'Bob': 92,
'Charlie': 78
}

print("Original dictionary:", student_scores)

# --- Change the value of an element ---


# We want to update Bob's score from 92 to 95
student_scores['Bob'] = 95

print("Dictionary after changing Bob's score:", student_scores)

# --- You can also add a new key-value pair this way ---
# Add a new student, David
student_scores['David'] = 88

print("Dictionary after adding David:", student_scores)

Maharashtra State Board of Technical Education (K Scheme) 79


Basic Python Programming(313011)

XI. References/Suggestions for further reading


1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]

XII. Assessment Scheme


Performance Indicators Weightage

Process Related: 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total (25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 80


Basic Python Programming(313011)
XI. References/Suggestions for further reading

Practical No.10: *a) Create python program to demonstrate use of math built-in function.
*b) Create python program to demonstrate use of string built-in function.

I. Practical Significance

Python includes multiple math-related and string-related functions. The math built-in module is used to perform
various mathematical calculations, such as numeric, trigonometric, logarithmic, and exponential calculations.
The Python string module provides several constants that are useful for checking to see if a character, slice, or
string contains letters, digits, symbols, etc. To use these modules, we need to import the module into our code.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome

CO4 – Implement basics of object oriented programming concepts.


IV. Laboratory Learning Outcome
LLO 10.1 Use built-in mathematical functions and string functions in python.

V. Relevant Affective Domain related outcome(s)

a) Follow safety practices.


b) Demonstrate working as a leader / a team member.
c) Follow ethical practices.

VI. Relevant Theoretical Background

a) List of Math’s built-in Functions and its attributes:

Function Description
ceil(x) Return the Ceiling value. It is the smallest integer, greater or equal.

copysign(x, y) Returns x with the sign of y.

cos(x) Return the cosine of x in radians.

exp(x) Returns e**x.


factorial(x) Returns the factorial of x.
floor(x) Returns the largest integer less than or equal to x.

fmod(x, y) Returns the remainder when x is divided by y.

gcd(x, y) Returns the Greatest Common Divisor of x and y.

Maharashtra State Board of Technical Education (K Scheme) 81


Basic Python Programming(313011)
XI. References/Suggestions for further reading
log(x[, base]) Returns the Log of x, where base is given. The default base is e.

log2(x) Returns the Log of x, where base is 2.

log10(x) Returns the Log of x, where base is 10.


pow(x, y) Return the x to the power y value.
remainder(x, y) Find remainder after dividing x by y.

radians(x) Convert angle x from degrees to radian.


sqrt(x) Finds the square root of x.
sin(x) Return the sine of x in radians.
tan(x) Return the tangent of x in radians.

b) String built-in functions:


Python includes the following built-in methods to manipulate strings:

Function Description
capitalize() Converts the first character to upper case
center() Pad the string with the specified character.
count() Returns the number of occurrences of a substring in the string.
encode() Encodes strings with the specified encoded scheme
find() Returns the lowest index of the substring if it is found
format() Formats the string for printing it to console
index() Returns the position of the first occurrence of a substring in a string
isalnum() Checks whether all the characters in a given string is alphanumeric or not

isalpha() Returns “True” if all characters in the string are alphabets


isdecimal() Returns true if all characters in a string are decimal
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
islower() Checks if all characters in the string are lowercase
isnumeric() Returns “True” if all characters in the string are numeric characters
isdigit() Returns True if all characters in the string are digits
lower() Converts a string into lower case
replace() Returns a string where a specified value is replaced with a specified
upper() Converts a string into upper case
title() Converts the first character of each word to upper case

VII. Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
Maharashtra State Board of Technical Education (K Scheme) 82
Basic Python Programming(313011)
XI. References/Suggestions for further reading
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1. Write the output of the following program.
import math

x = [Link](1.4) y = [Link](1.4)

print(x) print(y)

2. Write the output of the following program.


for i in range (3,12,2): print("a".upper())

3. The function pow(x,y,z) is evaluated as:


a) (x**y)**z
b) (x**y) / z
c) (x**y) % z

……………………………………………………………………………………………………..
………………………………………………………………………………………………………
………………………………………………………………………………………………………

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a Python script to calculate factorial of a number using math built-in function.
import math

def calculate_factorial(number):
"""
Calculates the factorial of a non-negative integer using [Link]().

Args:
number: The non-negative integer for which to calculate the factorial.

Returns:
The factorial of the number, or an error message if the input is invalid.
Maharashtra State Board of Technical Education (K Scheme) 83
Basic Python Programming(313011)
XI. References/Suggestions for further reading
"""
if not isinstance(number, int) or number < 0:
return "Error: Input must be a non-negative integer."
else:
# Use the built-in [Link] function
result = [Link](number)
return f"The factorial of {number} is {result}"

# Example usage:
num = 5
print(calculate_factorial(num))

num_zero = 0
print(calculate_factorial(num_zero))

num_negative = -2
print(calculate_factorial(num_negative))

num_float = 4.5
print(calculate_factorial(num_float))
2. Bill is 30 m away from a church. The angle of elevation when he looks at the top of the church‟s
spire is 45°. If Bill‟s eye level is 1.5 m above the ground, how tall is the church spire. (Use math built-in
function)
import math

# Given values
distance = 30 # meters
angle_degrees = 45
eye_level = 1.5 # meters

# Convert angle to radians


angle_radians = [Link](angle_degrees)

# Calculate the height above eye level using trigonometry


height_above_eye = distance * [Link](angle_radians)

# Calculate the total height of the spire


total_height = height_above_eye + eye_level

# Print the result


print(f"The total height of the church spire is {total_height:.1f} m")

3. Write a Python script that accepts a string in lowercase letters and convert into upper case letters
using string module.
import string

def convert_to_uppercase(input_string):
"""
Converts a lowercase string to uppercase using the string module for translation.
Maharashtra State Board of Technical Education (K Scheme) 84
Basic Python Programming(313011)
XI. References/Suggestions for further reading

Args:
input_string: The string in lowercase letters to convert.

Returns:
The input string converted to uppercase letters.
"""
# Define the source and destination characters for translation
lowercase_chars = string.ascii_lowercase
uppercase_chars = string.ascii_uppercase

# Create the translation table (a mapping of lowercase to uppercase characters)


translation_table = [Link](lowercase_chars, uppercase_chars)

# Apply the translation to the input string


uppercase_string = input_string.translate(translation_table)

return uppercase_string

# Example usage:
# The user ensures the input is already in lowercase as per the prompt's requirement
user_input = "hello world, this is a test!"

converted_output = convert_to_uppercase(user_input)

print(f"Original String: {user_input}")


print(f"Uppercase String: {converted_output}")

# Another example:
user_input_two = "python scripting is fun."
converted_output_two = convert_to_uppercase(user_input_two)
print(f"\nOriginal String: {user_input_two}")
print(f"Uppercase String: {converted_output_two}")
4. Write a Python script that uses find() function to search for the “language” string from the original
string "Python is a powerful language" and returns its index in the Python string.
# Original string
original_string = "Python is a powerful language"

# Substring to find
substring_to_find = "language"

# Use the find() method to search for the substring


# The find() method returns the starting index of the first occurrence of the substring
# If the substring is not found, it returns -1
index_of_substring = original_string.find(substring_to_find)

# Print the result


if index_of_substring != -1:
print(f"The string '{substring_to_find}' was found at index: {index_of_substring}")
Maharashtra State Board of Technical Education (K Scheme) 85
Basic Python Programming(313011)
XI. References/Suggestions for further reading
else:
print(f"The string '{substring_to_find}' was not found in the original string.")

1. [Link]
2. [Link]
3. [Link] python/functions/functions-from-
math-module/
4. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 86


Basic Python Programming(313011)
Basic Python Programming(313011)

Practical No.11 Write python programs to define function with arguments.

a) Calculate factorial of a number

b) Swapping of two variables

I. Practical Significance

Functions help to decompose a large program into small segments which makes program easy to
understand, maintain and debug. If repeated code occurs in a program. Function canbe used to include
those codes and execute when needed by calling that function. This practical will make learner reuse code
instead of rewriting the same code multiple times.
II. Industry/Employer Expected Outcome
The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO4 - Implement basics of object oriented programming concepts.
IV. Laboratory Learning Outcome
LLO 11.1 Create user defined functions in Python.

V. Relevant Affective Domain related outcome(s)

a) Follow safety practices.


b) Demonstrate working as a leader / a team member.
c) Follow ethical practices.

VI. Relevant Theoretical Background


Functions are useful in programming because they eliminate needless and excessive copying and pasting of
code throughout a program. Functions also help organize your code.

How to Define a Function in Python: Syntax:

def function_name(parameters): function body


Basic Python Programming(313011)

Example:

def hello_world_func(): print("hello world")


Python Function Arguments:
The data/information in the functions can be passed as the arguments or [Link] arguments are specified in the
parentheses and are separated by commas.
VII. Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

Maharashtra State Board of Technical Education (K Scheme) 87


Basic Python Programming(313011)
1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.

1. Write the output of the following program.


def find_square(num): result = num * num return result

square = find_square(3) print('Square:', square)


The output of the corrected code is
9
2. Write error and give justification for the same.
def Interest(P,R,T=7):
I = (P*R*T)/100
print(I)

Interest(20000,.08,15) #Line 1
Interest(T=10,20000,.075) #Line 2
Interest(50000,.07) #Line 3
Interest(P=10000,R=.06,Time=8) #Line 4
Interest(80000,T=10) #Line 5

In the provided Python code,


Line 2 (Interest(T=10,20000,.075)) and Line 4 (Interest(P=10000,R=.06,Time=8)) will cause
errors, with Line 2 failing due to Keyword argument T followed by positional arguments, and Line 4
failing because Time is not a defined parameter; Line 5 will also error out for missing the positional
argument R.
Here's a breakdown of the errors:
 Line 2: Interest(T=10,20000,.075)
o Error: SyntaxError: positional argument follows keyword argument.
o Justification: You cannot place positional arguments (like 20000, .075) after keyword
arguments (like T=10) in a function call. Python expects all positional arguments first, then keyword
arguments.
 Line 4: Interest(P=10000,R=.06,Time=8)
o Error: TypeError: Interest() got an unexpected keyword argument 'Time'.
Maharashtra State Board of Technical Education (K Scheme) 88
Basic Python Programming(313011)
o Justification: The function Interest is defined with parameters P, R, and T. There is no
parameter named Time, so passing Time=8 results in an error.
 Line 5: Interest(80000,T=10)
o Error: TypeError: Interest() missing 1 required positional argument: 'R'.
o Justification: The function requires P and R (since T has a default), but only P (as 80000)
and T (as a keyword) are provided, leaving R unassigned

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a Python script to calculate factorial of a number.

def factorial(n):
"""
Calculates the factorial of a non-negative integer.

Args:
n: A non-negative integer.

Returns:
The factorial of the number n.
"""
# Check if the number is negative
if n < 0:
return "Factorial does not exist for negative numbers"
# Check if the number is 0 or 1, as their factorial is 1
elif n == 0 or n == 1:
return 1
# Calculate the factorial iteratively for positive numbers
else:
result = 1
for i in range(1, n + 1):
result *= i
return result

# Example usage:
number_to_calculate = 5
print(f"The factorial of {number_to_calculate} is {factorial(number_to_calculate)}")

number_to_calculate = 0
print(f"The factorial of {number_to_calculate} is {factorial(number_to_calculate)}")

number_to_calculate = -1
print(f"The factorial of {number_to_calculate} is {factorial(number_to_calculate)}")
2. Write a Python script for swapping of two variables.

Maharashtra State Board of Technical Education (K Scheme) 89


Basic Python Programming(313011)
XI. References/Suggestions for further reading
1. [Link]
2. [Link]
3. [Link]
4. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 90


Basic of Python Programming (313011)

Practical No.12 Write programs to define function with default arguments.

I. Practical Significance
Default function parameters allow named parameters to be initialized with default values if no valueor
undefined is passed. Default arguments in Python represent the function arguments that will be used if no
arguments are passed to the function call.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcomethrough various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO4 - Implement basics of object oriented programming concepts.
IV. Laboratory Learning Outcome
LLO 12.1 Implement function with default arguments.

V. Relevant Affective Domain related outcome(s)

d) Follow safety practices.


e) Demonstrate working as a leader / a team member.
f) Follow ethical practices.

VI. Relevant Theoretical Background


Default arguments in a function are parameters with a predefined value set by the function definition. When
calling a function, if no argument is provided for a parameter with a default value, the default value will be
used. In this way, the function is more flexible and does not require each argument to be specified.
Syntax:
def function_name(parameter1=default_value1, parameter2=default_value2,
...):# Function body
# The code that uses the parameters
# A parameter's default value will be used if no value is provided

Example:
def function(a = 24, b, c):print('Values are:') print(a)
print (b) print (c)
function(10, 4)
VII. Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Maharashtra State Board of Technical Education (K Scheme) 91


Basic of Python Programming (313011)
Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.

1. Write the output of the following program.

def student(firstname, lastname='Mark', standard='Fifth'): print(firstname, lastname, 'studies in', standard,


'Standard')

student("John") student("Jane", "Smith")


student("Bob", "Johnson", "Sixth")

Output

John Mark studies in Fifth Standard


Jane Smith studies in Fifth Standard
Bob Johnson studies in Sixth Standard

2. Write the errors and give justification for the same.


X = 100
def Change(P=10,Q=25): global X
if P%6==0:
X+=100
else:
X+=50
Sum=P+Q+X
print(P,'#',Q,'$',Sum) Change()
Change(18,50) Change(30,100)

There are no errors in the provided Python code


. The program is syntactically correct and handles variable scope properly, allowing it to run and produce
output successfully

Output
10 # 25 $ 185
18 # 50 $ 318
30 # 100 $ 480

Maharashtra State Board of Technical Education (K Scheme) 92


Basic of Python Programming (313011)

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a Python script that accepts price and discount rates as arguments in a function which returns
the new price based on the discount rate. The default discount rate is 3%.
def calculate_discounted_price(original_price, discount_rate=3):
"""
Calculates the new price after applying a discount.

Args:
original_price (float or int): The initial price of the item.
discount_rate (float or int): The percentage rate of the discount.
Default is 3.

Returns:
float: The new price after the discount is applied.
"""
if original_price < 0 or discount_rate < 0:
raise ValueError("Price and discount rate cannot be negative.")

# Calculate the discount amount


discount_amount = original_price * (discount_rate / 100)

# Calculate the new price


new_price = original_price - discount_amount

# Return the new price, rounded to two decimal places


return round(new_price, 2)

# --- Example Usage ---

# Example 1: Using the default discount rate (3%)


price_1 = 100.00
new_price_1 = calculate_discounted_price(price_1)
print(f"Original Price: ${price_1}")
print(f"Discount Rate: 3%")
print(f"New Price: ${new_price_1}")
# Expected Output: New Price: $97.0

print("-" * 20)

# Example 2: Specifying a custom discount rate (15%)


price_2 = 550.75
custom_rate = 15
new_price_2 = calculate_discounted_price(price_2, custom_rate)
print(f"Original Price: ${price_2}")
print(f"Discount Rate: {custom_rate}%")
print(f"New Price: ${new_price_2}")

Maharashtra State Board of Technical Education (K Scheme) 93


Basic of Python Programming (313011)
# Expected Output: New Price: $468.14

print("-" * 20)

# Example 3: Specifying a zero discount rate (no change)


price_3 = 20.00
rate_zero = 0
new_price_3 = calculate_discounted_price(price_3, rate_zero)
print(f"Original Price: ${price_3}")
print(f"Discount Rate: {rate_zero}%")
print(f"New Price: ${new_price_3}")
# Expected Output: New Price: $20.0
2. Write a Python script to calculate Gross Salary of Employee by taking salary as a function that
accepts Basic Salary,TA,DA,HRA as arguments(use default value of TA =4% and DA=8%).
3.

def calculate_gross_salary(basic_salary, hra, ta=0.04, da=0.08):


"""
Calculates the gross salary of an employee.

Args:
basic_salary (float or int): The employee's basic salary.
hra (float or int): House Rent Allowance.
ta (float): Travel Allowance percentage (default is 4%).
da (float): Dearness Allowance percentage (default is 8%).

Returns:
float: The calculated gross salary.
"""
# Ensure inputs are numbers and percentages are handled correctly
if not isinstance(basic_salary, (int, float)) or not isinstance(hra, (int, float)):
raise ValueError("Basic salary and HRA must be numeric values.")

# Calculate TA and DA amounts


ta_amount = basic_salary * ta
da_amount = basic_salary * da

# Gross Salary = Basic Salary + HRA + TA + DA


gross_salary = basic_salary + hra + ta_amount + da_amount

return gross_salary

# Example Usage:

# Example 1: Using default TA and DA values


basic_sal_1 = 50000
hra_1 = 15000
gross_sal_1 = calculate_gross_salary(basic_sal_1, hra_1)
print(f"Employee 1 Gross Salary: {gross_sal_1:.2f}")

Maharashtra State Board of Technical Education (K Scheme) 94


Basic of Python Programming (313011)
# Example 2: Specifying custom TA and DA percentages
basic_sal_2 = 60000
hra_2 = 18000
# TA = 5% (0.05), DA = 10% (0.10)
gross_sal_2 = calculate_gross_salary(basic_sal_2, hra_2, ta=0.05, da=0.10)
print(f"Employee 2 Gross Salary: {gross_sal_2:.2f}")

# Example 3: Different basic salary and HRA with default percentages


basic_sal_3 = 35000
hra_3 = 10500
gross_sal_3 = calculate_gross_salary(basic_sal_3, hra_3)
print(f"Employee 3 Gross Salary: {gross_sal_3:.2f}")
XI. References/Suggestions for further reading
1. [Link]
2. [Link]
3. [Link]
4. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 95


Basic of Python Programming (313011)

Practical No.13: *Create a program to demonstrate use of: Built-in module (e.g. numeric,
mathematical functional and programming module) in Python.
I. Practical Significance

Python's built-in modules for file handling and input/output (I/O) operations offer a wide range of tools and
functions for reading, writing, and manipulating files and data streams. These modules are essential for
working with files, whether for data processing, text manipulation, or datastorage.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO5 - Create modules and packages for given purpose.
IV. Laboratory Learning Outcome
LLO 13.1 Use built-in python mathematical modules.

V. Relevant Affective Domain related outcome(s)

a) Follow safety practices.


b) Demonstrate working as a leader / a team member.
c) Follow ethical practices.

VI. Relevant Theoretical Background

 There are several built-in modules in Python, which you can import whenever you like. A module is a
collection of Python objects such as functions, classes, and so on. Python interpreter is bundled with a
standard library consisting of large number of built-in modules.
 Built-in modules are generally written in C and bundled with Python interpreter in precompiled form. A
built-in module may be a Python script (with .py extension) containing useful utilities.
 A module may contain one or more functions, classes, variables, constants, or any other Python
resources.

I. Numeric and Mathematical Modules:


This module provides numeric and math-related functions and data types.
Following are the modules which are classified as numeric and mathematical modules.
(i) numbers (Numeric abstract base classes).
(ii) math (Mathematical functions).
(iii) cmath (Mathematical functions for complex numbers).
(iv) decimal (Decimal fixed point and floating point arithmetic).
(v) fractions (Rational numbers).
(vi) random (Generate pseudo-random numbers).
(vii) statistics (Mathematical statistics functions).

II. Functional Programming Modules:


• These modules provide functions and classes that support a functional programming style and
general operations on callables.
Following are modules which comes under functional programming modules.
(i) itertools (functions creating iterators for efficient looping).
(ii) functools (higher-order functions and operations on callable objects).
(iii) operator (standard operators as functions).
VII. Resources Required
Maharashtra State Board of Technical Education (K Scheme) 98
Basic of Python Programming (313011)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software
IX. Practical related Questions
Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.

1. Write the output of the following program.


import math
def circle_area(r): return [Link]*r**2
radius = 3
fract = fractions.
Fraction(deci)
print(fract)
Output------28.26

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a Python script to calculate the DC output voltage(Vdc) of Half wave rectifier using Formula:
Vdc=(Vm/π) where Vm is the peak value of output voltage using math module.

import math

def calculate_half_wave_vdc(vm):
"""
Calculates the DC output voltage (Vdc) of a half-wave rectifier.

Args:
vm (float): The peak value of the output voltage (Vm) in volts.

Returns:
float: The calculated DC output voltage (Vdc) in volts.
"""
if vm < 0:
raise ValueError("Peak voltage (Vm) must be a non-negative value.")

# Formula: Vdc = Vm / π
vdc = vm / [Link]
return vdc
Maharashtra State Board of Technical Education (K Scheme) 98
Basic of Python Programming (313011)

# --- Example Usage ---


# Assuming a peak output voltage of 10 volts
peak_voltage_vm = 10.0

# Calculate the DC voltage


dc_voltage_vdc = calculate_half_wave_vdc(peak_voltage_vm)

# Print the result


print(f"For a peak voltage (Vm) of {peak_voltage_vm} V:")
print(f"The DC output voltage (Vdc) of the half-wave rectifier is approximately {dc_voltage_vdc:.4f} V")

# Another example with a different peak voltage


peak_voltage_vm_2 = 25.5
dc_voltage_vdc_2 = calculate_half_wave_vdc(peak_voltage_vm_2)
print(f"\nFor a peak voltage (Vm) of {peak_voltage_vm_2} V:")
print(f"The DC output voltage (Vdc) of the half-wave rectifier is approximately {dc_voltage_vdc_2:.4f} V")

2. Write a Python script to calculate the Area of cross section of the wire, A = π*d2/4 =
m2 where d is the diameter of wire.

import math

# Prompt the user to enter the diameter of the wire in meters


diameter_str = input("Enter the diameter of the wire in meters (e.g., 0.001 for 1 mm): ")

try:
# Convert the input string to a float
d = float(diameter_str)

# Check if the diameter is a valid, non-negative number


if d <= 0:
print("Diameter must be a positive value.")
else:
# Calculate the area using the formula A = π * d² / 4
A = [Link] * d**2 / 4

# Print the result, formatting it to a reasonable number of decimal places


print(f"The area of the cross-section is: {A:.8f} m²")

except ValueError:
# Handle cases where the user enters non-numeric data
print("Invalid input. Please enter a numerical value for the diameter.")

import statistics

# Sample dataset (a list of numbers)


data = [12, 15, 13, 12, 18, 20, 15, 14, 13, 12]

# --- Calculate Measures of Central Tendency ---

# Calculate the mean (average value)


mean_value = [Link](data)

Maharashtra State Board of Technical Education (K Scheme) 98


Basic of Python Programming (313011)
# Calculate the median (middle value)
median_value = [Link](data)

# Calculate the mode (most often value)


try:
mode_value = [Link](data)
except [Link] as e:
# Handle the case where there is no unique mode (e.g., all values appear once)
mode_value = f"Cannot find a unique mode: {e}"

# --- Calculate Measures of Variability ---

# Calculate the standard deviation (spread of values)


# For a sample of data (most common use case)
std_dev_sample = [Link](data)

# For an entire population (if your data represents every single possible value)
# std_dev_population = [Link](data)

# --- Print the results ---

print(f"Dataset: {data}")
print("-" * 30)
print(f"Mean (Average Value): {mean_value:.2f}")
print(f"Median (Middle Value): {median_value:.2f}")
print(f"Mode (Most Often Value): {mode_value}")
print(f"Standard Deviation (Sample): {std_dev_sample:.2f}")
# print(f"Standard Deviation (Population): {std_dev_population:.2f}")

2. Write the output of the following program.


import fractions
for deci in ['0.6', '2.5', '2.3', '4e-1']:

3/5
5/2
23/10
2/5

XI. References/Suggestions for further reading


1. [Link]
2. [Link]
3. [Link]
4. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

Maharashtra State Board of Technical Education (K Scheme) 98


Basic of Python Programming (313011)
1. Debugging ability 20%
2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 98


Basic of Python Programming (313011)

Practical No.14 Write program to create a user-defined module (e.g.: building calculator)in python.
I. Practical Significance
Python modules assist us in organizing and grouping content through the use of files and folders. Python
modules come into play in this modular programming method, where we have separated the code into discrete
components. User-defined modules in Python are those modules that are created by the users to make their
projects easy and simple.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various teaching
learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO5 - Create modules and packages for given purpose.
IV. Laboratory Learning Outcome
LLO 14.1 Write user-defined module in python.

V. Relevant Affective Domain related outcome(s)

d) Follow safety practices


e) Demonstrate working as a leader / a team member.
f) Follow ethical practices

VI. Relevant Theoretical Background

Modules in Python are simply files with the “.py” extension that contain Python code such as Python functions,
methods, classes, or variables that may be imported into
another Python program. A Python module is a file that contains Python commands and definitions. A Python
module can be imported by another Python script usingthe import statement. Once a module is imported,
its contents can be accessed using the dot notation (e.g., module_name.function_name). This allows the
functionality definedin the module to be used in other parts of the program.

return x*x
Once you have created the module file, you can use it in another Python script by importing it using the import
statement:
import my_module
result = my_module.square(5) print(result)
Output:
25

VII. Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Maharashtra State Board of Technical Education (K Scheme) 101


Basic of Python Programming (313011)

Sr. No. Name of Specification Quantity Remarks


Resource (If any)
1. Computer System
2. Operating System
3. Development
Software
Save this code in the file [Link] person1 = {
"name": "John", "age": 36, "country": "Norway"
}

import mymodule

a = mymodule.person1["age"] print(a)

2. Tick the correct statement which correctly describes a module.


a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a
program
c) Defines the specification of how it is to be used
d) Any program that reuses code

3. Tick the statement which is not an advantage of using modules.


a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c) Provides a means of reducing the size of the program
d) Provides a means of testing individual parts of the program
1
person1 = {
"name": "John", "age": 36, "country": "Norway"
}

36

2
b) Design and implementation of specific functionality to be incorporated into a program
3
c) Provides a means of reducing the size of the program
2. Write a Python script to create a user defined module to design calculator.

# Filename: employee_utils.py

def get_employee_details():
"""
Asks the user for personal details of an employee and returns them as a dictionary.
"""
print("--- Enter Employee Details ---")
name = input("Enter full name: ")
Maharashtra State Board of Technical Education (K Scheme) 102
Basic of Python Programming (313011)
employee_id = input("Enter Employee ID: ")
department = input("Enter Department: ")
job_title = input("Enter Job Title: ")
salary = input("Enter Salary: ")

# Store the details in a dictionary


employee_details = {
"Name": name,
"Employee ID": employee_id,
"Department": department,
"Job Title": job_title,
"Salary": salary
}
return employee_details

def display_employee_details(details):
"""
Displays the given employee details in a formatted manner.
"""
if not details:
print("\nNo employee details to display.")
return

print("\n--- Employee Details ---")


# Iterate over the dictionary items and print them
for key, value in [Link]():
print(f"{key}: {value}")

2
# Filename: calculator_module.py

def add(a, b):


"""Returns the sum of two numbers."""
return a + b

def subtract(a, b):


"""Returns the difference of two numbers."""
return a - b

def multiply(a, b):


"""Returns the product of two numbers."""
return a * b

def divide(a, b):


"""Returns the quotient of two numbers, handling division by zero."""
if b == 0:
return "Error: Division by zero is not allowed"
return a / b

def power(a, b):


"""Returns a raised to the power of b."""
return a ** b

Maharashtra State Board of Technical Education (K Scheme) 103


Basic of Python Programming (313011)
XI. References/Suggestions for further reading
1. [Link]
2. [Link]
3. [Link]
4. [Link]

XII. Assessment Scheme

Performance Indicators Weight age

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 104


Basic of Python Programming (313011)

Practical No.15: *Develop Python program to demonstrate use of NumPy


package for creating, accessing and performing different array operations.

I. Practical Significance

NumPy can be used to perform a wide variety of mathematical operations on arrays. It adds powerful data
structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous
library of high- level mathematical functions that operate on these arrays and matrices.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various
teaching learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO5 - Create modules and packages for given purpose.
IV. Laboratory Learning Outcome
LLO 15.1 Use python built-in packages.

V. Relevant Affective Domain related outcome(s)

a) Follow safety practices.


b) Demonstrate working as a leader / a team member.
c) Follow ethical practices.

VI. Relevant Theoretical Background

NumPy stands for "Numerical Python". It provides a high-performance multidimensional array object, and
tools for working with these arrays.

An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers
and represented by a single variable. NumPy's array class is called ndarray. It is also known by the alias array.

In NumPy arrays, the individual data items are called elements. All elements of an array should be of the same
type. Arrays can be made up of any number of dimensions.
In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total number of
elements in that direction.
The size of an array is the total number of elements contained in an array in all the dimension. The size of
NumPy arrays are fixed; once created it cannot be changed again.
Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are that they
are fast, easy to work with, and give users the opportunity to perform calculations across entire arrays.

a) Creating Numpy: To create a NumPy use ndarray object by using the array()
function

Maharashtra State Board of Technical Education (K Scheme) 105


Basic of Python Programming (313011)

Install Numpy by using a python library called pip by using the command :

pip install numpy .

To use NumPy you need to import Numpy:

import numpy as np # alias np

b) Accessing and performing different array operations:

Example 1: For NumPy with array object.

import numpy as np

a=[Link]([1,2,3]) # one dimensional array

print(a)

Output:

[1 2 3]

Example 2:

arr=[Link]([[1,2,3],[4,5,6]]) # two dimensional array

print(arr)

Output:

[[1 2 3]
[4 5 6]]

Example 3: arr=[Link]([[1,2,3],[4,5,6]]) a=[Link](3,2)


print(a) array([[1, 2],

[3, 4],
[5, 6]])

VII. Resources Required

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

Maharashtra State Board of Technical Education (K Scheme) 106


Basic of Python Programming (313011)
1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1. Write the output of the following program.

import numpy as np
arr = [Link]((2, 3),dtype=float) # 2 rows and 3 columns print (arr)

Output [[0. 0. 0.]


[0. 0. 0.]]

2. Write the output of the following program.

import numpy as np
arr = [Link]((3, 3)) # 3 rows and 3 columns print (arr)
Output
[[0.92345678 0.12345678 0.78901234]
[0.45678901 0.89012345 0.23456789]
[0.67890123 0.34567890 0.56789012]]

3. Insert the correct method for creating a NumPy array.

arr = np. ([1, 2, 3, 4, 5])

Correct Method
import numpy as np

# Create the array


arr = [Link]([1, 2, 3, 4, 5])

# Print the array


print(arr) # Output: [1 2 3 4 5]

# Access an element (e.g., the third element, index 2)


print(arr[2]) # Output: 3

# Check its data type


print([Link]) # Output: int64 (or similar integer type)

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a Python NumPy program to create a 3x3 identity matrix.


2. Write a Python NumPy program to create a 4x4 matrix with values ranging from 2 to 10.
[Space for Answers]

1
Maharashtra State Board of Technical Education (K Scheme) 107
Basic of Python Programming (313011)

import numpy as np

# Create a 3x3 identity matrix using the [Link]() function


# The function takes an integer argument 'n' for the size (n x n) of the matrix
identity_matrix = [Link](3)

# Print the resulting identity matrix


print(identity_matrix)

2
import numpy as np

# Create a 1D array with values from 2 to 17 (16 values in total: 10 - 2 + 1)


# The arange function is inclusive of the start value and exclusive of the stop value
values_1d = [Link](2, 18)

# Reshape the 1D array into a 4x4 matrix


matrix_4x4 = values_1d.reshape(4, 4)

# Print the resulting matrix


print(matrix_4x4)

XI. References/Suggestions for further reading


1. [Link]
2. [Link]
3. [Link]
4. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

1. Debugging ability 20%


2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 108


Practical No.16 Write program to demonstrate the use of user defined packages in Python.

I. Practical Significance
Packages make it significantly easier to reuse and maintain the code within a project and across different
projects. Packages are used to avoid name conflicts, and to write a better maintainable code. Packages are
divided into two categories: Built-in Packages (packages from the Java API) User-defined Packages (create
your own packages). User-defined packages are the packages that are defined by the user.

II. Industry/Employer Expected Outcome


The aim of this course is to attain the following industry/employer expected outcome through various teaching
learning experiences:
Develop programs using python to solve wide-reaching electronics engineering related problems.

III. Course Level Learning Outcome


CO5 - Create modules and packages for given purpose.
IV. Laboratory Learning Outcome
LLO 16.1 Implement user defined packages in python.

V. Relevant Affective Domain related outcome(s)

a) Follow safety practices.


b) Demonstrate working as a leader / a team member.
c) Follow ethical practices.

VI. Relevant Theoretical Background


In Python, A user-defined package is a package that you create yourself, as opposed to one of the built-in
packages that are included with Python by default. Creating a user-defined package is a way to organize your
code and make it more modular and reusable.
User-defined packages are those packages that are designed or created by the developer to categorize classes
and packages. It can be imported into other classes and used the same as we use built-in packages.
1. First, we create a directory and give it a package name, preferably related to its operation.
Directory name=Cars

2. Then we put the classes and the required functions in it.


Filename=[Link] class Maruti:
def init (self): [Link]=['800','Alto','WagonR']
def PModel(self): print("Models of Maruti") for model in [Link]:

print('\t%s ' % model)


Filename=Mahindra.p class Mahindra

def init (self):


[Link]=['Scorpio','Bolero','Xylo']

def PModel(self): print("Models of Mahendra") for model in [Link]:


print('\t%s ' % model)

3. Finally we create an init .py file inside the directory, to let Python know that the directory is a
package.
Filename= init .py from Maruti import Maruti
from Mahindra import Mahindra
4. To access package car, create [Link] file and access classes from directory car
Filename=[Link]
Maharashtra State Board of Technical Education (K Scheme) 109
from Maruti import Maruti
from Mahindra import Mahindra

ModelMaruti=Maruti() [Link]()

ModelMahindra=Mahindra() [Link]()

Output:
Models of Maruti 800
Alto WagonR
Models of Mahindra
Scorpio Bolero Xylo

VII. Resources Required

Sr. No. Name of Specification Quantity Remarks


Resource (If any)
1. Computer System Computer (i3-i5 preferable As per Batch Size For ALL
RAM>2GB) Experiments
2. Operating System Windows/Linux
3. Development Python IDE
Software
VIII. Resources used (Additional)

Sr. No. Name of Resource Specification Quantity Remarks (If any)

1. Computer System
2. Operating System
3. Development
Software

IX. Practical related Questions

Note: Below given are few sample questions for reference. Teachers must design more such questions to
ensure the achievement of identified CO.
1. Fill in the blanks:
Suppose you have a package named “pkg” with two modules mod1 and mod2. mod1 has a function func1()
and mod2 has a function func2().
Complete the following Python code to import and use these functions:

mod1.func1()
from pkg.mod2 baz()

for first blank


a) import pkg
b) from pkg import mod1
c) from pkg.mod1 import func1 for second blank
a) import func2
b) import func2 as fn
c) import fn

Maharashtra State Board of Technical Education (K Scheme) 110


2. Fill in the blanks:

Using the following package pkg following structure:

import mod1 from the subpackage sub_pkg1 by using the following statement: import

a) mod1
b) mod1 from pkg.sub_pkg1
c) sub_pkg1.mod1 from pkg
d) pkg. sub_pkg1.mod1
……………………………………………………………………………………………………..
………………………………………………………………………………………………………
………………………………………………………………………………………………………

X. Exercise
Note: Faculty must ensure that every group of students use different input value.
(Use blank space for answers or attach more pages if needed)

1. Write a python script to create a python package with the name “calculator” with modules
addition, subtraction, multiplication, and division each module contain separate function for performing
specific mathematical operations and import modules from the “calculator” packages and display the output.
2. Write a python script to create a python package with the name “mypackage”
and two modules [Link] and [Link] and display the output.

[Space for Answers]


1
# This function adds two numbers
def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link]")

Maharashtra State Board of Technical Education (K Scheme) 111


while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")

# check if choice is one of the four options


if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input"
2

import os

# Define the package and module names


package_name = "mypackage"
module1_name = "[Link]"
module2_name = "[Link]"

# Create the main package directory


try:
[Link](package_name, exist_ok=True)
print(f"Created directory: {package_name}/")
except OSError as e:
print(f"Error creating directory {package_name}/: {e}")

# Create the required __init__.py file inside the package


init_file_path = [Link](package_name, "__init__.py")
with open(init_file_path, "w") as f:
[Link]("# This makes 'mypackage' a Python package\n")
print(f"Created file: {init_file_path}")

# Create the [Link] module file


module1_path = [Link](package_name, module1_name)
with open(module1_path, "w") as f:
[Link]("def circle_area(radius):\n")
[Link](" return 3.14159 * radius * radius\n")
[Link]("\n")
Maharashtra State Board of Technical Education (K Scheme) 112
[Link]("def square_area(side):\n")
[Link](" return side * side\n")
print(f"Created file: {module1_path}")

# Create the [Link] module file


module2_path = [Link](package_name, module2_name)
with open(module2_path, "w") as f:
[Link]("def add(a, b):\n")
[Link](" return a + b\n")
[Link]("\n")
[Link]("def subtract(a, b):\n")
[Link](" return a - b\n")
print(f"Created file: {module2_path}")

print("\nPython package 'mypackage' created successfully!")


print("Structure overview:")
print(f"{package_name}/")
print(f"|-- __init__.py")
print(f"|-- {module1_name}")
print(f"|-- {module2_name}")

# --- Example Usage (Optional) ---


# To demonstrate the package works, you can try importing and using it.
# This assumes the current directory is in your Python path.

try:
import [Link] as area
import [Link] as math

print("\n--- Testing the package ---")


radius = 5
print(f"Area of circle with radius {radius}: {area.circle_area(radius)}")
side = 4
print(f"Area of square with side {side}: {area.square_area(side)}")
print(f"Sum of 5 and 3: {[Link](5, 3)}")
print(f"Difference of 5 and 3: {[Link](5, 3)}")

except ImportError as e:
print(f"\nError importing package for testing. Make sure the current directory is in your PYTHONPATH:
{e}")

XI. References/Suggestions for further reading

1. [Link]
2. [Link]
3. [Link]
4. [Link]

XII. Assessment Scheme

Performance Indicators Weightage

Process Related : 15 Marks 60%

Maharashtra State Board of Technical Education (K Scheme) 113


1. Debugging ability 20%
2. Correctness of Program codes 30%
3. Quality of output achieved (LLO mapped) 10%
Product Related: 10 Marks 40%

1. Completion and submission of practical in time 20%


2. Answer to exercise questions 20%
Total ( 25 Marks) 100 %

Marks Obtained Dated signature of


Teacher
Process Related (15) Product Related (10) Total (25)

Maharashtra State Board of Technical Education (K Scheme) 114

Common questions

Powered by AI

User-defined Python modules help manage program complexity by organizing code into reusable components, promoting modular programming. They are implemented by creating separate `.py` files containing functions and classes, which can be imported as needed. This approach simplifies large programs by dividing them into logical sections, as seen in the creation of custom modules like `calculator_module.py` .

Converting a tuple to a list is beneficial when the data needs to be modified, such as adding, removing, or changing elements, since tuples are immutable. This is achieved by passing the tuple to the `list()` function, allowing for operations like modifications or reordering. This flexibility is illustrated in operations like modifying or sorting tuples .

Tuples in Python are immutable, so to modify an element at a specific index, the tuple should be converted to a list. The modification is done on the list, which is then converted back to a tuple. This involves converting the tuple to a list, modifying the required index, and converting it back to a tuple, as demonstrated by the function `replace_tuple_element` .

NumPy provides powerful data structures and a vast library of mathematical functions for efficient numerical operations on arrays and matrices. It supports various mathematical operations, enhancing performance and simplicity in processing large datasets, which is valuable for engineering and scientific computations .

To determine if an integer is a palindrome, the number is converted to a string to facilitate reversing. The reversed string is then compared to the original. If they match, the number is a palindrome; otherwise, it isn't. This is implemented in the function `is_palindrome(number)` which returns True if the number equals its reversed string, otherwise False .

Lists in Python are used for storing ordered collections of items, providing flexibility with various data types. They support dynamic sizing, allowing efficient addition and removal of elements. Lists facilitate data processing tasks like sorting and filtering, and their built-in methods enhance code readability and efficiency in handling complex data operations .

To sort a tuple of strings alphabetically in Python, you convert the tuple to a list, sort the list using `sort()`, and convert it back to a tuple. Python's sorting is case-sensitive, meaning uppercase letters are sorted before lowercase ones. This can be demonstrated using the function `sort_tuple_alphabetically` .

Statistical functions such as mean, median, and mode are pivotal in summarizing and understanding data distributions. The `statistics` module enables the calculation of these measures, providing insights into data tendencies, central values, and commonality. These functions are widely utilized in data analysis for decision-making and pattern recognition .

To add a new element to a tuple, which is immutable, you concatenate the original tuple with a new one containing the element. This is done using the `+` operator, as shown in the function `add_element_to_tuple`, which appends an element by creating a new tuple .

The Euclidean distance between two points in 2D space is calculated using the formula \(\sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}\). This involves unpacking the points into their coordinates, computing the differences, squaring them, adding them up, and finally taking the square root using `math.sqrt`. This method is crucial for various fields such as data analysis and graphics programming .

You might also like