0% found this document useful (0 votes)
7 views12 pages

Practical Writeups Python

The document outlines a series of Python programming experiments aimed at teaching fundamental concepts such as user input, arithmetic operations, and geometric calculations. Each experiment includes learning objectives, theoretical explanations, methods for implementation, and expected outcomes. The document also emphasizes the importance of error handling and input validation in programming.

Uploaded by

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

Practical Writeups Python

The document outlines a series of Python programming experiments aimed at teaching fundamental concepts such as user input, arithmetic operations, and geometric calculations. Each experiment includes learning objectives, theoretical explanations, methods for implementation, and expected outcomes. The document also emphasizes the importance of error handling and input validation in programming.

Uploaded by

ss1411354
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Experiment No.

—1:

Aim: To write a Python program that adds two numbers entered by the user.

Tools & Technologies used: Python 3.x, Visual Studio Code

Learning Objectives:

1. Learn to take user input in Python.


2. Understand basic arithmetic operations.
3. Display the output using the print() function.

Theory:

Addition is a fundamental arithmetic operation that combines two numbers (operands) into a single result (sum).

Mathematical Representation:

Sum = Number 1+Number 2

2. Addition in Programming:

Addition in programming is a simple operation where the + operator is used to sum two values. These values can be:

1. Integers – e.g. 3+5=8

2. Floats (Decimals) – e.g. 2.5+4.1 =6.6

3. Mixed Types – Python can handle operations between integers and floats automatically. Example: 4+2.5=6.5 .

Python interprets the input based on the data type, which needs careful handling for accurate results.

3. User Input in Python:

 Python takes input using the input() function, which reads user input as a string by default.
 To perform arithmetic operations, you must convert the string input into a numerical type (e.g., int or float) using int() or float()
functions.
 Example:

num1 = input("Enter a number: ") # Default: String

num1 = int(num1) # Convert to integer

4. Handling Different Types of Numbers:

1. Integers (Whole Numbers):

No decimal part. Example: 5,-10.


2. Floating-Point Numbers (Decimals):

Includes a fractional part. Example:3.14, 0.75 .

Python supports both, and you can ensure precision by working with floats for decimal inputs.

5. Error Handling for User Input:

 To prevent program crashes due to invalid input (e.g., letters instead of numbers), exception handling with try-except blocks
can be used:
 try:

num1 = float(input("Enter a number: "))

except ValueError:

print("Invalid input. Please enter a valid number.")

6. Real-Life Applications of Addition in Programming:

1. Financial Applications: Summing transactions, calculating totals or balances.


2. Data Analysis: Aggregating numbers for averages, sums, or trends.
3. Gaming Applications: Keeping track of scores or points.
4. Scientific Computations: Summing measurements or results.

7. Properties of Addition in Mathematics and Programming:

1. Commutative Property:

a+b=b+a

2. Associative Property:

(a + b) + c = a + (b + c)

3. Identity Property:

Adding 0 to a number doesn’t change its value: a+0=a.

Python faithfully implements these mathematical properties.

Code:

Output:
Learning Outcomes:

1. Ability to write programs involving user input and simple calculations.


2. Understanding of how to work with data types like integers and floating-point numbers in Python.
3. Familiarity with executing Python scripts and analyzing outputs.

Course Outcomes:

1. Apply fundamental Python concepts to solve basic problems.


2. Demonstrate proficiency in basic input and output operations.
3. Enhance problem-solving and algorithmic skills.

Conclusion:

The program successfully adds two user-input numbers and displays the result, reinforcing the understanding of basic Python concepts.

Viva Questions:

1. What function is used to take input in Python?


2. Why did we use float() instead of int() in the program?
3. Can you modify this program to add three numbers?
4. How does Python handle the addition of floating-point numbers?
5. What will happen if you enter a string instead of a number?

For Faculty use:


Correction Parameters Formative Timely Completion of Attendance Learning
Assessment[40%] Practical[40%] Attitude[20%]
Experiment No.—2:

Aim: Write a Python program to find the square root.

Tools & Technologies used: Python 3.10, Visual Studio Code

Learning Objectives:

1. Learn to calculate mathematical functions like square roots.


2. Explore Python's mathematical operations and built-in libraries.

Theory:

What is a Square Root?

The square root of a number is a value such that . For example, the square root of 16 is 4, as .

Mathematical Representation:

 A square root is denoted by , and in Python, we compute it using either the ** operator or the math.sqrt() function.
 For non-negative numbers, the square root exists and is a real number. For negative numbers, square roots exist in the complex
domain.

Methods to Calculate Square Roots in Python:

1. Using ** operator:
Python allows us to calculate the square root of a number by raising it to the power of .

Example: x ** 0.5.

2. Using math.sqrt() function:

Python's math module provides a function sqrt() for calculating the square root more efficiently and precisely.

Example: math.sqrt(x).

Handling Negative Numbers:

The square root of a negative number cannot be calculated in the real domain using the above methods. However, Python’s cmath
(complex math) module can handle square roots of negative numbers, representing them as complex numbers.

Code:

Output:

Learning Outcomes:

1. Ability to calculate square roots using various Python methods.


2. Understanding the use of Python libraries like math.
3. Familiarity with type conversion for arithmetic operations.

Course Outcomes:

1. Develop basic programs utilizing mathematical functions.


2. Enhance skills in using Python's built-in libraries.
3. Strengthen foundational programming concepts.

Conclusion:

The program provides multiple methods to calculate the square root:

1. For real numbers using ** operator and math.sqrt().

2. For handling negative numbers using cmath.sqrt().

It highlights Python's versatility in solving mathematical problems efficiently.


Viva Questions:

1. What is the purpose of the math.sqrt() function?


2. How does Python's ** operator calculate powers?
3. What are the differences between math.sqrt() and ** operator in terms of precision?
4. Can you calculate the square root of negative numbers in Python? Why or why not?
5. Modify the program to handle cases when the user enters a negative number.

For Faculty use:


Correction Parameters Formative Timely Completion of Attendance Learning
Assessment[40%] Practical[40%] Attitude[20%]

Experiment No.—3:

Aim: Write a Python program to calculate the area of a triangle.

Tools & Technologies used: Python 3.10, Visual Studio Code

Learning Objectives:

1. Understand and implement basic geometrical formulas in Python.


2. Develop error handling to validate inputs.

Theory:

A triangle is a closed figure with three sides and three vertices. The area of a triangle represents the amount of space enclosed by its

three sides. Depending on the type of input data, there are multiple ways to calculate the area:

Geometric Concepts

1. Types of Triangles:

 Equilateral Triangle: All sides are equal.


 Isosceles Triangle: Two sides are equal.
 Scalene Triangle: All sides are different.
 Right-angled Triangle: One angle is 90° (area can be calculated directly using base and height).
2. Triangle Inequality Theorem:

For any three sides , , and to form a valid triangle:

a + b > c, a + c > b, b + c > a

Methods to Calculate the Area

1. Base and Height Formula:

For triangles where the base (b) and height (h) are given:

Area= ½*b*h
h: The perpendicular height from the opposite vertex to the base.

This formula is straightforward and often used for right-angled triangles.

2. Heron’s Formula:

Used when the lengths of all three sides (, , and ) are provided. It is based on the semi-perimeter ():

s = {a + b + c}/2
Area =(s(s-a)* s(s-b)* s(s-c))1/2
Key Points of Heron’s Formula:

 Applicable to any type of triangle.


 Useful when base and height are not provided.
 More computationally intensive than the base-height formula.

3. Area of a Right-Angled Triangle:

For a right triangle with base (b) and perpendicular height (h):

Area= ½*b*h
4. Special Formula for an Equilateral Triangle:

For an equilateral triangle with side length (a):

Area= 31/2/4 *a2

Handling Edge Cases:

1. Invalid Inputs: Ensure that the sides satisfy the triangle inequality theorem.

2. Negative or Zero Input: Base, height, or side lengths cannot be zero or negative. These cases must be validated.

3. Complex Scenarios: For curved triangles (spherical geometry), other mathematical approaches are required, beyond the scope of this
program.
Computational Concepts

1. Mathematical Libraries:

 Python's math.sqrt() function is used to compute the square root.


 If more precise or complex mathematical operations are needed, libraries such as NumPy or SymPy can be used.

2. Time Complexity:

 Base-height formula is computed in .


 Heron’s formula involves multiple multiplications and one square root calculation, making it slightly more computationally
expensive.

3. Input Validation:

 Check if all inputs are positive numbers.


 Validate if the given sides can form a triangle.

Importance of Calculating Triangle Area

 The computation of triangle area has practical applications in:


 Construction and architectural design
 Determining the size of land plots (surveying).
 Computer graphics and simulations.
 Physics and engineering problems involving motion or pressure distribution over a triangular region.

Code:

Output:

Learning Outcomes:

1. Calculate the area of a triangle using different methods.


2. Implement conditional statements and mathematical operations in Python.
3. Build a reusable and modular code structure.

Course Outcomes:

1. Apply mathematical computations in Python programming.


2. Understand the importance of input validation for accurate results.
3. Learn advanced geometrical problem-solving techniques.

Conclusion:

The program calculates the area of a triangle using two methods:

1. Base and height formula for right or specific triangles where the base and height are given.
2. Heron’s formula, which is applicable for any triangle when all three sides are known.

It reinforces geometric problem-solving and demonstrates how mathematical formulas can be implemented programmatically.

Viva Questions:

1. What is the formula for calculating the area of a triangle using base and height?
2. How does Heron’s formula work for calculating the area?
3. How do you verify if three sides form a valid triangle?
4. Why is it necessary to use the math.sqrt() function in Heron’s formula?
5. Can you modify the program to handle invalid or zero input values for sides?
6. For Faculty use:

Correction Parameters Formative Timely Completion of Attendance Learning


Assessment[40%] Practical[40%] Attitude[20%]

Experiment No.—4:

Aim: To write a Python program to determine whether a given number is odd or even.

Tools & Technologies used:

Language: Python 3.x

IDE: Any Python-compatible text editor like Visual Studio Code, PyCharm, or Jupyter Notebook.

Libraries: None

Learning Objectives:

1. Understand the use of the modulo operator for divisibility checks.

2. Learn basic decision-making in Python using conditional statements.

Theory:

An even number is any integer divisible by 2 without leaving a remainder. Examples: -6,-2,0,2,4,8 etc.

Mathematical representation:
n % 2 = 0 (for +ve numbers)

2. Characteristics of Even and Odd Numbers:

 Zero (0):

0, so 0 is considered an even number.

 Negative Integers:

The rules for odd and even numbers apply to negative integers as well. For example:

 -4(even),
 -5 (odd in absolute value).

3. Importance in Mathematics:

 Properties of Even Numbers:

 Adding two even numbers results in an even number. Example: 4+6=10


 Multiplying two even numbers always yields an even number. Example: 2*8=16

Properties of Odd Numbers:

 Adding two odd numbers results in an even number. Example: 3+5=8


 Multiplying two odd numbers results in an odd number. Example: 3*5=15

4. Use of the Modulo Operator in Programming:

 The modulo operator (%) calculates the remainder of the division of one number by another.

Example: 7 (remainder is 1, so it’s odd).

 Python provides an efficient way to use % to determine even/odd status.

5. Applications in Programming and Real-World Problems:

 Conditional Logic: Identifying even or odd numbers is critical in algorithms like sorting, filtering, and distributing tasks.
 Memory Allocation: In computer architecture, even and odd memory addresses may be treated differently.
 Pattern Recognition: Creating number sequences, dividing tasks, or applying rules in games and simulations.

6. Alternative Approach to Finding Even/Odd Numbers (Without %):

You can also determine whether a number is even or odd by dividing it by 2 and checking the integer part:

If n/2 is an integer, then n text is even; otherwise, it's odd.


7. Real-Life Analogy:

Odd and even numbers are used in real-life scenarios like:

 Grouping: Even distribution (e.g., pairs of items).


 Scheduling: Dividing tasks alternately for efficiency.
 Data Clustering: Splitting datasets into groups for analysis.

Code:

Output:

Learning Outcomes:

1. Write programs that perform checks based on divisibility conditions.

2. Implement Python’s input-output features effectively.

3. Develop basic problem-solving skills in programming.

Course Outcomes:

1. Apply mathematical concepts in programming.

2. Demonstrate conditional statements and modular operations.

3. Build logical thinking and program flow control

Conclusion:

The program successfully checks if a number is odd or even by using the modulo operator %. It reinforces the understanding of basic
mathematical operations and conditional statements in Python.

Viva Questions:

1. What is the difference between odd and even numbers?

2. What does the % operator do in Python?

3. Why is zero considered an even number?

4. Can this program be modified to handle non-integer inputs? How?

5. Write a variation of this program to check whether a number is divisible by 3.


For Faculty use:
Correction Parameters Formative Timely Completion of Attendance Learning
Assessment[40%] Practical[40%] Attitude[20%]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy