Practical Writeup Format[1]
Practical Writeup Format[1]
Learning Objectives:
1. Add Two Numbers: Learn to use variables and arithmetic operators to perform addition and handle user input.
2. Find the Square Root: Objective: Understand how to use built-in functions, like math.sqrt(), to calculate square roots.
3. Calculate the Area of a Triangle: Objective: Apply geometric formulas in programming by calculating the area using base and
height inputs.
4. Check if a Number is Odd or Even: Objective: Implement conditional statements to determine if a number is odd or even using the
modulus operator.
Theory:
1. Basic Concepts
Variables: In Python, variables are used to store data values. In this program, number1 and number2 are variables that hold the
user’s input.
Data Types: The program uses floating-point numbers (float) to allow for decimal inputs. This choice ensures that users can
input both whole numbers and fractions.
Functions: A function in Python is a reusable block of code that performs a specific task. The add_numbers function
encapsulates the logic for adding two numbers, promoting code reusability and modularity.
2. Input Handling
Input Function: The input() function captures user input as a string. To perform arithmetic operations, we convert these strings
to floats using the float() function. This conversion is crucial because mathematical operations cannot be performed on string
types.
3. Arithmetic Operations
Addition: The core operation in this program is addition, represented by the + operator in Python. The expression num1 +
num2 computes the sum of the two numbers passed as arguments to the function.
4. Output
Print Function: The print() function displays output to the console. In this case, it formats a string to show the result of the
addition clearly.
Execution Flow
1) Function Definition: The program begins by defining the add_numbers function, which takes two parameters (num1 and num2)
and returns their sum.
2) User Input:
a. The program prompts the user to enter the first number using input(), which is converted to a float.
b. It repeats this step for the second number.
3) Function Call: After obtaining both numbers, the program calls the add_numbers function, passing in number1 and number2.
The result of this function call (the sum) is stored in the variable result.
4) Display Result: Finally, the program prints out a formatted message displaying the sum of the two numbers.
1. Basic Concepts
Square Root Definition: The square root of a number xx is a value yy such that y2=xy2=x. For example, the square root of 9
is 3 because 3×3=93×3=9. This operation is fundamental in mathematics and has applications in various fields such as
geometry, physics, and statistics.
Mathematical Principle: The mathematical notation for square roots is denoted as xx. For positive real numbers, there
exists a principal square root that is non-negative. However, negative numbers do not have real square roots in
conventional mathematics.
2. Python Concepts
Importing Modules: The program utilizes the math module, which provides access to mathematical functions defined by
the C standard library. To use the functions in this module, it must be imported at the beginning of the script using import
math.
Function Definition: The find_square_root function encapsulates the logic for calculating the square root. It takes one
parameter (the number) and returns its square root using the math.sqrt() function.
Input Handling: The program prompts the user for input using input(), which captures data as a string. This string is then
converted to a floating-point number using float(), allowing for decimal inputs.
Error Handling: Before calculating the square root, the program checks if the input number is negative. Since real square
roots are not defined for negative numbers, it provides an appropriate message if this condition is met.
Execution Flow
1. Importing Required Libraries: The program starts by importing the math module to access mathematical functions.
2. Definition: It defines the find_square_root function that uses math.sqrt() to compute and return the square root of a given
number.
3. Function User Input:
The program prompts the user to enter a number for which they want to find the square root.
The input is captured as a string and converted into a float for calculation.
4. Error Checking: Before proceeding with the calculation, it checks if the input number is negative:
If negative, it prints an error message indicating that square roots cannot be computed for negative numbers.
If non-negative, it calls the find_square_root function with the user-provided number and stores the result.
5. Display Result: Finally, it prints out the calculated square root in a formatted message.
1. Basic Concepts
Triangle Definition: A triangle is a polygon with three edges and three vertices. The area of a triangle can be calculated using
various formulas depending on the information available (e.g., base and height, or side lengths).
Area Formula: The most common formula for calculating the area of a triangle when the base and height are known is
This formula is derived from the concept that a triangle can be viewed as half of a rectangle.
2. Python Concepts
Function Definition: The program defines a function area_of_triangle that takes two parameters (base and height) and returns
the computed area. Functions in Python promote code reusability and modularity.
Input Handling: The program captures user input using the input() function, which returns data as a string. This string is then
converted to a floating-point number using float(), allowing for decimal inputs.
Output Display: The program uses the print() function to display the calculated area in a user-friendly format.
Execution Flow
1. Function Definition: The program starts by defining the area_of_triangle function that implements the area formula.
2. User Input:
It prompts users to enter values for the base and height of the triangle.
The inputs are captured as strings and converted into floating-point numbers for calculation.
3. Function Call: After obtaining both inputs, it calls the area_of_triangle function with these values and stores the result in a
variable named area.
4. Display Result: Finally, it prints out the calculated area in a formatted message.
1. Basic Concepts
An even number is any integer that is divisible by 2 without leaving a remainder (e.g., -4, -2, 0, 2, 4).
An odd number is an integer that, when divided by 2, leaves a remainder of 1 (e.g., -3, -1, 1, 3).
2. Mathematical Principle
The determination of whether a number is odd or even can be expressed mathematically using the modulus operator:
3. Python Concepts
Function Definition: The program defines a function check_odd_even that takes an integer as input and returns
whether it is "Even" or "Odd". This encapsulation allows for better organization and reusability of code.
Input Handling: The program uses the input() function to capture user input. Since input() returns data as a string,
it converts this string to an integer using int(), enabling arithmetic operations.
Conditional Statements: The program employs an if statement to control the flow based on whether the input
number is even or odd. This demonstrates how Python handles decision-making processes.
Execution Flow
1. Function Definition: The program begins by defining the check_odd_even function that implements the logic for
determining if a number is odd or even.
2. User Input:
3. Function Call: After obtaining the user input, it calls the check_odd_even function with this value and stores the
result in the variable result.
4. Display Result: Finally, it prints out whether the number is odd or even in a formatted message.
Code:
Output:
Learning Outcomes:
1. Add Two Numbers: Develop the ability to perform basic arithmetic operations and handle user input in Python.
2. Find the Square Root: Gain proficiency in using built-in functions to perform mathematical calculations.
3. Calculate the Area of a Triangle: Learn to apply geometric formulas programmatically to solve real-world problems.
4. Check if a Number is Odd or Even: Understand how to implement conditional logic to evaluate numerical properties in Python.
Conclusion:
Viva Questions:
1. Can you explain how you would handle user input for adding two numbers in Python, and what data type conversions are
necessary?
2. What would happen if you tried to find the square root of a negative number in Python, and how can you handle such cases in
your program?
3. Why is it necessary to divide the product of the base and height by 2 when calculating the area of a triangle, and how does this
relate to the area of a rectangle?
4. Can you describe how the modulus operator works in determining whether a number is odd or even, and provide an example of
its use in a conditional statement?
Aim:
Learning Objectives:
1. Understand Conditional Statements: Learn how to use if, else, and logical operators to control program flow based on
conditions.
2. Implement Basic Algorithms: Gain experience in implementing an algorithm to determine whether a year is a leap year based
on specific rules.
3. Input Handling: Practice taking user input and converting it to the appropriate data type (integer).
2. Utilize Built-in Functions: Learn to use Python's built-in max() function for finding the largest value among multiple inputs.
3. List and Tuple Unpacking: Gain familiarity with handling multiple inputs using lists and unpacking them into function
arguments.
1. Looping Constructs: Develop skills in using loops (for/while) to iterate over a range of numbers.
2. Mathematical Logic: Understand the concept of prime numbers and how to implement logic to check primality.
3. Efficient Algorithms: Learn about optimizing algorithms by checking divisibility only up to the square root of the number.
2. Error Handling: Understand how to handle edge cases, such as negative input, by implementing conditional checks.
1. Unit Conversion: Learn about unit conversion and how to apply mathematical formulas in programming.
2. Function Definition: Practice defining functions that take parameters and return calculated results.
3. Input and Output: Enhance skills in handling user input and formatting output for clarity.
Theory:
For example:
2. Conditional Statements
In Python, conditional statements (if, elif, and else) are used to execute code based on certain conditions. The basic structure of
an if statement allows the program to evaluate whether a condition is true or false and execute corresponding blocks of code.
3. Logical Operators
Logical operators such as and, or, and not are used to combine multiple conditions. In the context of checking for leap years, you will
often use these operators to evaluate whether multiple criteria are satisfied.
4. Input Handling
Python provides built-in functions like input() for taking user input. The input received from users is typically in string format, so it must
be converted to an integer using int() when performing arithmetic operations.
The complete program combines all these elements into a cohesive unit. Here’s how the program works step-by-step:
1. Prompt the user to enter a year.
4. Print whether the entered year is a leap year or not based on the evaluation.
The task is to compare three numerical values and identify the largest one. This can be approached in several ways, including using
conditional statements or built-in functions. The basic logic involves comparing each number against the others to determine which is the
greatest.
2. Conditional Statements
Conditional statements (if, elif, and else) are essential for controlling the flow of a program based on specific conditions. In this case, you
will use these statements to compare the three numbers.
3. Using Functions
Defining functions in Python allows you to encapsulate code into reusable blocks. This promotes modularity and makes your code easier
to read and maintain. In this case, you can define a function that takes three numbers as arguments and returns the largest.
4. Input Handling
Python provides built-in functions like input() for taking user input. When users provide input, it is typically in string format, so you must
convert it to an appropriate numerical type (e.g., integer or float) for comparison.
To find the largest number among three inputs, you can use a series of conditional checks:
Alternatively, you can leverage Python's built-in max() function, which simplifies finding the maximum value among multiple inputs.
A prime number is defined as a natural number greater than 1 that has no positive divisors other than 1 and itself. In other
words, a prime number can only be divided evenly (without leaving a remainder) by 1 and the number itself.Examples of
Prime Numbers:
5
7
11
Non-Prime Numbers:
4 (divisible by 1, 2, and 4)
6 (divisible by 1, 2, 3, and 6)
If nn is exactly 2, it is prime.
For odd numbers greater than 2, check for factors from 3 up to the square root of nn.
3. Conditional Statements
Conditional statements (if, elif, and else) are used to control the flow of the program based on specific conditions. In this
case, you will use these statements to evaluate whether a number meets the criteria for being prime.
4. Looping Constructs
Loops are crucial for iterating over a range of numbers. In this case, you will use a loop to check for factors of the given number. The most
efficient way to check for factors is to iterate from 2 up to the square root of nn, as any factor larger than the square root would have a
corresponding smaller factor.
5. Input Handling
Python provides built-in functions like input() for taking user input. The input received from users is typically in string format, so it must
be converted to an integer using int() when performing arithmetic operations.
1. Understanding Factorial
The factorial of a non-negative integer nn is the product of all positive integers less than or equal to nn. It is denoted by n!n!.
Mathematical Definition:
n!=n×(n−1)×(n−2)×...×2×1n!=n×(n−1)×(n−2)×...×2×1
Examples:
5!=5×4×3×2×1=1205!=5×4×3×2×1=120
3!=3×2×1=63!=3×2×1=6
1!=11!=1
0!=10!=1
2. Recursive vs. Iterative Approaches
Recursive Approach: A function that calls itself to solve smaller instances of the same problem.Example Recursive Definition:
Iterative Approach: Using loops to calculate the factorial by multiplying numbers from 1 to nn.
Both methods are valid; however, recursion can lead to stack overflow for large values due to deep recursion, while iteration is generally
more memory efficient.
3. Conditional Statements
Conditional statements (if, elif, and else) are essential for controlling the flow of the program based on specific conditions. In this case,
you will use these statements to handle special cases like negative inputs and base cases for recursion.
4. Looping Constructs
Loops are crucial for iterating through a range of numbers. In an iterative approach, you would use a loop to multiply numbers from 1 up
to nn.
Code:
Output:
Learning Outcomes:
1. Understand how to determine if a year is a leap year based on specific divisibility rules.
2. Learn to compare multiple values and identify the largest using built-in functions.
3. Gain knowledge on how to check for prime numbers using iteration and mathematical properties.
4. Understand how to calculate the factorial of a number using iterative methods.
5. Learn how to convert units of measurement from kilometers to miles using multiplication.
Course Outcomes:
1. Implement Conditional Logic: Develop programs that utilize conditional statements to determine properties of numbers, such
as identifying leap years and checking for prime numbers.
2. Utilize Built-in Functions: Leverage Python's built-in functions and libraries to perform operations like finding the maximum
value among multiple inputs and calculating factorials.
3. Understand Mathematical Concepts: Apply fundamental mathematical concepts through programming, including divisibility
rules for leap years and prime number verification.
4. Perform Unit Conversions: Write functions to convert between different units of measurement, demonstrating an
understanding of real-world applications of programming.
5. Enhance Problem-Solving Skills: Strengthen problem-solving abilities by breaking down complex tasks into manageable
functions and using iterative logic to achieve desired outcomes.
Conclusion:
Viva Questions:
2. What method did you use to find the largest number among three inputs?
Aim:
a. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
e. A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox
jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.
Learning Objectives:
Objective: Understand how to define functions in Python and utilize conditional statements.
Skills Developed:
Objective: Learn how to calculate the length of different data types (lists and strings) in Python.
Skills Developed:
Understanding the difference between mutable (lists) and immutable (strings) data types.
Objective: Explore string manipulation techniques to determine if a string reads the same forwards and backwards.
Skills Developed:
Skills Developed:
Skills Developed:
Iterating through strings and using sets for efficient membership testing.
Theory:
Functions in Python
A function is a named block of code designed to perform a specific task. Functions help organize code into manageable sections and can
be reused throughout a program. In Python, functions are defined using the def keyword followed by the function name and parentheses
containing any parameters.
When defining a function, you can specify parameters that allow you to pass data into the function. The function can then process this
data and return a value using the return statement.
To create a function that checks if a character is a vowel, we need to follow these steps:
1. Define the Function: Use the def keyword to create a function that takes one parameter (the character).
2. Check for Vowels: Use conditional statements (if, elif, else) to determine if the input character matches any of the defined
vowels.
3. Return Boolean Values: Return True if the character is a vowel and False otherwise.
Lists:
A list in Python is a mutable, ordered collection of items. It can contain elements of different data types (e.g., integers, strings,
other lists).
Lists are defined using square brackets [], with elements separated by commas.
Strings:
A string is an immutable sequence of characters. Strings are used to represent text data.
Strings are defined using single quotes ', double quotes ", or triple quotes ''' or """.
Functions in Python
What is a Function?
A function is a reusable block of code that performs a specific task. Functions help keep code organized and can be called multiple times
with different inputs.
Functions can take parameters (inputs) and return values (outputs). When defining a function, you specify its parameters within
parentheses after the function name.
To create a function that computes the length of a given list or string, we need to follow these steps:
1. Define the Function: Use the def keyword to create a function that accepts one parameter, which will be either a list or a string.
2. Use Built-in Functions: Python provides a built-in function called len() that returns the number of items in an object. This
function works for both lists and strings.
3. Return the Length: The function should return the length computed by the len() function.
A palindrome is a sequence of characters that read the same forwards and backwards. This concept is not only interesting from a
linguistic perspective but also serves as a fundamental exercise in programming, particularly in string manipulation and algorithmic
thinking. In Python, checking if a string is a palindrome involves understanding string properties, indexing, and control flow.
Understanding Palindromes
Definition of a Palindrome: A palindrome is a word, phrase, number, or other sequences of characters that remains unchanged when
reversed. Examples include:
Characteristics:
The simplest method to check for palindromes involves reversing the string and comparing it to the original.
Functions in Python
A function is a named block of code designed to perform a specific task. Functions help organize code into manageable sections and can
be reused throughout a program. In Python, functions are defined using the def keyword followed by the function name and parentheses
containing any parameters.
When defining a function, you can specify parameters that allow you to pass data into the function. The function can then process this
data and return a value using the return statement.
To create a function that checks if a string is a palindrome, we need to follow these steps:
1. Define the Function: Use the def keyword to create a function that accepts one parameter (the string to be checked).
2. Normalize the String: Convert the string to lowercase and remove non-alphanumeric characters. This ensures that the check is
case-insensitive and ignores spaces and punctuation.
4. Compare Strings: Check if the reversed string is equal to the normalized string.
5. Return Boolean Value: Return True if they are equal (indicating it is a palindrome) and False otherwise.
Introduction
Reversing the order of words in a string is a common programming task that helps develop skills in string manipulation, list handling, and
understanding of Python's built-in methods. This operation involves breaking down a string into its constituent words, reversing their
order, and then reconstructing the string. This task is not only useful in various applications but also serves as an excellent exercise for
beginner programmers.
Strings:
A string is a sequence of characters used to represent text data in Python. Strings are immutable, meaning their content cannot
be changed after creation.
Strings can include letters, numbers, spaces, punctuation, and other special characters.
Words:
Words are typically defined as sequences of characters separated by spaces. For example, in the sentence "Hello World",
"Hello" and "World" are two distinct words.
What is a Function?
A function is a reusable block of code that performs a specific task. Functions help keep code organized and can be called multiple times.
with different inputs.
Functions can take parameters (inputs) and return values (outputs). When defining a function, you specify its parameters within
parentheses after the function name.
To create a function that reverses the order of words in a given string, we need to follow these steps:
1. Define the Function: Use the def keyword to create a function that accepts one parameter (the input string).
2. Split the String into Words: Use the split() method to break the string into a list of words. By default, split() separates by
whitespace.
3. Reverse the List of Words: Use list slicing or the reverse() method to reverse the order of words in the list.
4. Join the Words Back into a String: Use the join() method to combine the reversed list back into a single string with spaces
separating the words.
Introduction
A pangram is a sentence that contains every letter of the English alphabet at least once. The classic example of a pangram is: "The quick
brown fox jumps over the lazy dog." Pangram checking is an interesting problem that combines string manipulation, set operations, and
logical reasoning. Creating a pangram checker function in Python helps develop skills in data validation and character analysis.
Understanding Pangrams
Definition of a Pangram:
A pangram must include all 26 letters of the English alphabet (A-Z, case insensitive).
Perfect Pangrams: Sentences that use each letter exactly once (e.g., "Mr Jock, TV quiz PhD, bags few lynx").
Common Pangrams: Sentences that may repeat letters but still include every letter at least once.
Characteristics:
The challenge lies in efficiently determining whether a given string contains all the required letters.
What is a Function?
A function is a reusable block of code that performs a specific task. Functions help keep code organized and can be called multiple times.
with different inputs.
Functions can take parameters (inputs) and return values (outputs). When defining a function, you specify its parameters within
parentheses after the function name.
To create a function that checks if a string is a pangram, we need to follow these steps:
1. Define the Function: Use the def keyword to create a function that accepts one parameter (the input string).
2. Normalize the String: Convert the string to lowercase to ensure uniformity when checking for letters.
3. Use Sets for Character Tracking: Create a set to store unique alphabetic characters found in the input string.
4. Iterate Over the String: Loop through each character in the normalized string and add it to the set if it is an alphabetic
character.
5. Check Set Size: After processing the string, check if the size of the set is 26 (the number of letters in the English alphabet).
6. Return Boolean Value: Return True if the set contains all 26 letters; otherwise, return False.
Code:
Output:
Learning Outcomes:
Outcome: Learners will be able to define and implement a function that checks if a character is a vowel.
Skills Developed:
Proficiency in writing reusable functions with clear parameters and return values.
Outcome: Learners will demonstrate the ability to compute the length of a list or string using a custom function.
Skills Developed:
Outcome: Learners will be able to create a function that determines if a string is symmetrical or a palindrome.
Skills Developed:
Knowledge of string manipulation techniques, including reversing strings and normalization (handling case sensitivity).
Outcome: Learners will demonstrate the ability to reverse the order of words in a given string using a custom function.
Skills Developed:
Outcome: Learners will be able to write a function that checks if a sentence is a pangram by verifying the presence of all letters
in the English alphabet.
Skills Developed:
Course Outcomes:
Develop foundational programming skills in Python, particularly in defining and using functions.
Enhance their problem-solving abilities through practical applications involving strings and lists.
Build a solid understanding of essential programming concepts that can be applied to more complex challenges in future
projects.
Conclusion:
Viva Questions:
1. What is the purpose of the function you wrote to check for vowels?
2. What is the purpose of the function you wrote to check for vowels?
3. How does your function handle different data types?
4. What is a palindrome? Can you give an example?
5. What does your word reversal function accomplish?
6. How do you determine if a sentence is a pangram in your function?
Aim:
a. Write a program that takes two lists and returns True if they have at least one common member.
b. Write a Python program to print a specified list after removing the 0th, 2nd, 4th and 5th elements.
Learning Objectives:
1. Understanding Lists: Familiarize with Python lists, their properties, and manipulation.
2. Iteration Techniques: Learn to use loops for iterating through list elements, including nested loops.
3. Set Operations: Discover efficient membership testing and intersection using sets.
2. List Comprehension: Write concise code using list comprehensions for filtering elements.
3. Indexing Knowledge: Grasp zero-based indexing and its implications in list modifications.
4. List Methods: Familiarize with methods like pop() and del, understanding their use cases.
6. Critical Thinking: Evaluate different approaches to modifying lists and select the best one.
Theory:
Introduction to Lists
In Python, a list is an ordered collection of items that can contain elements of different types, including integers, strings, or even other
lists. Lists are mutable, meaning their contents can be changed after creation.
Comparing Lists for Common Elements
When tasked with determining if two lists share at least one common member, there are several approaches one can take:
1. Nested Loops: This method involves iterating through each element of the first list and checking it against each element of the
second list. If a match is found, we can conclude that the lists have a common member.
2. Set Intersection: A more efficient method involves converting both lists into sets and using the intersection operation to find
common elements. This approach leverages the fact that set operations are generally faster than list operations.
3. List Comprehension: Another elegant solution utilizes list comprehension to create a new list containing only the common
elements.
Modifying lists by removing elements is another common task in Python. Lists allow for dynamic changes, including adding or removing
items based on their index positions.
To remove specific elements from a list (e.g., the 0th, 2nd, 4th, and 5th elements), we can use various techniques:
1. Using List Comprehension: This method creates a new list that excludes specified indices.
2. Using del Statement: Another method involves using the del statement to remove items directly by their indices.
3. Using pop() Method: The pop() method removes an element at a specified index and returns it. However, this method modifies
the original list sequentially and may lead to index errors if not handled carefully.
Code:
Output:
Learning Outcomes:
1. Proficiency in List Operations: Learners will demonstrate the ability to manipulate and compare lists effectively in Python.
2. Enhanced Iteration Skills: Students will be able to apply various iteration techniques, including loops and comprehensions, to
solve problems involving list comparisons.
3. Understanding of Set Theory: Learners will understand the advantages of using sets for efficient membership testing and will
be able to implement set operations in their code.
4. Application of Conditional Logic: Students will gain experience in using conditional statements to determine the presence of
common elements in lists.
5. Performance Awareness: Learners will be able to analyze and compare the efficiency of different algorithms for finding
common members, recognizing the importance of time complexity.
6. Improved Problem-Solving Abilities: Students will enhance their ability to approach and solve coding challenges systematically.
Course Outcomes:
1. Proficient Use of Python Syntax: Students will demonstrate an understanding of Python syntax and semantics, enabling them
to write clear and effective Python programs.
2. List Manipulation Skills: Learners will acquire the ability to manipulate lists, including the implementation of operations such as
searching for common elements and modifying lists by removing specified indices.
3. Application of Control Structures: Students will effectively use control flow statements (loops and conditionals) to solve
programming problems, enhancing their logical reasoning and problem-solving skills.
4. Understanding Data Structures: Learners will gain proficiency in using core data structures such as lists, tuples, and
dictionaries, understanding their properties and appropriate use cases.
5. Problem-Solving Competence: Students will develop the ability to approach and solve real-world problems through
programming, applying learned concepts to practical challenges.
6. Code Optimization Awareness: Learners will recognize the importance of algorithm efficiency, comparing different methods for
solving problems based on performance considerations.
7. Foundational Object-Oriented Programming Skills: Students will be introduced to object-oriented programming concepts in
Python, preparing them for more advanced programming tasks.
8. Error Handling Techniques: Learners will understand how to implement error handling in their programs, improving code
robustness and reliability.
9. Critical Thinking Development: Students will enhance their critical thinking abilities by evaluating multiple approaches to
coding challenges and selecting the most effective solutions.
Conclusion:
Viva Questions:
1. What is the purpose of using sets when checking for common members between two lists in Python? How does it improve
performance?
2. Explain how you can remove elements from a list at specific index positions. What method would you use to remove the 0th,
2nd, 4th, and 5th elements from a list?
3. Can you describe how list comprehensions work in Python? Provide an example of how you would use a list comprehension to
filter out certain elements from a list.
4. What are some potential errors you might encounter when modifying a list by index? How can you avoid these errors in your
code?
Aim:
a. Write a Python script to sort (ascending and descending) a dictionary by value.
b. Write a Python program to sum all the items in a dictionary.
Learning Objectives:
Understand Dictionary Structure: Gain familiarity with how dictionaries store data in key-value pairs and the implications of
their unordered nature prior to Python 3.7, where order is maintained based on insertion.
Utilize Built-in Functions: Learn to use Python's built-in sorted() function to sort dictionaries. This includes understanding how
to apply the key parameter with a lambda function to specify that sorting should be based on values rather than keys.
Implement Sorting Logic: Develop skills in writing functions that can sort dictionaries in both ascending and descending order
by using the reverse parameter of the sorted() function.
Practical Application: Apply these concepts by creating a script that demonstrates sorting a sample dictionary, enhancing
problem-solving skills through coding practice.
Comprehend Data Types: Understand the structure of dictionaries and how to access their values. Recognize that dictionary
values can be numeric, which is essential for summation.
Utilizing built-in functions like sum() combined with values() method to simplify the process.
Code Implementation: Create a program that effectively sums all items in a given dictionary, reinforcing coding skills and
understanding of aggregate functions.
Error Handling: Develop awareness of potential issues (e.g., non-numeric values) and implement basic error handling or
validation techniques.
Theory:
to Python 3.7, dictionaries were unordered collections, meaning the order of items was not guaranteed.
However, starting from Python 3.7, dictionaries maintain the order of insertion, which facilitates sorting
operations.
The primary tool for sorting in Python is the built-in sorted() function. This function can sort any inerrable and
returns a new sorted list. When sorting dictionaries, it is crucial to extract the items (key-value pairs) for
sorting based on values.
1. Extracting Items: Use the .items() method on the dictionary to retrieve its key-value pairs as tuples.
This method returns a view object that displays a list of a dictionary's key-value tuple pairs.
2. Sorting with sorted(): Pass the items to the sorted() function along with a key parameter that
specifies how the sorting should be done. A lambda function can be used to indicate that sorting
should occur based on the second element of each tuple (the value).
3. Creating a New Dictionary: Since dictionaries cannot be sorted in place, convert the sorted list of
tuples back into a dictionary using the dict() constructor.
4. Sorting Order: To sort in descending order, set the reverse parameter of sorted() to True.
A dictionary in Python is a mutable, unordered collection of key-value pairs. Each key is unique and maps to a
corresponding value. Dictionaries are widely used for storing data where relationships between keys and
values are important.
Python provides a built-in function called sum() that is specifically designed to sum up elements of an iterable
(like lists, tuples, or sets). To sum the values in a dictionary, you will typically use this function in conjunction
with the dictionary's .values() method.
1. Accessing Values: Use the .values() method on the dictionary to retrieve all the values as a view
object. This view can be easily converted into an iterable format that can be processed by
the sum() function.
2. Summing Values: Pass the result of .values() to the sum() function to calculate the total of all
numeric values in the dictionary.
3. Handling Non-Numeric Values: It’s important to ensure that all values in the dictionary are numeric (integers or floats). If there
are non-numeric values, you may need to implement error handling or filtering to avoid exceptions during summation.
Code:
Output:
Learning Outcomes:
1. Understanding Data Structures: Learners will become familiar with Python dictionaries, including their structure (key-value
pairs) and properties (unordered nature prior to Python 3.7).
2. Utilizing Built-in Functions: Students will learn to use Python's built-in sorted() function effectively, understanding its
parameters and how to apply it to sort dictionary items based on values.
3. Implementing Sorting Logic: Participants will develop skills in writing scripts that can sort dictionaries in both ascending and
descending order by manipulating the reverse parameter of the sorted() function.
4. Lambda Functions: Learners will gain experience in using lambda functions as key arguments in sorting operations, enhancing
their ability to write concise and efficient code.
5. Creating New Dictionaries: Students will understand how to convert sorted lists of tuples back into dictionaries, reinforcing the
concept that dictionaries cannot be sorted in place.
6. Practical Application: By completing this task, learners will enhance their problem-solving skills through practical coding
exercises, applicable in real-world data manipulation scenarios.
1. Accessing Dictionary Values: Learners will understand how to retrieve values from a dictionary using the .values() method,
which is essential for performing operations on the data stored within.
2. Using the sum() Function: Participants will become proficient in utilizing the built-in sum() function to aggregate numerical
values, reinforcing their understanding of iterables in Python.
3. Handling Non-Numeric Values: Students will learn about data validation techniques, including checking for numeric types
before summation, which is crucial for robust programming practices.
4. Error Handling Skills: By addressing potential issues with non-numeric values, learners will develop basic error handling
strategies that improve code reliability and user experience.
5. Practical Implementation: Completing this task provides hands-on experience with dictionary operations and reinforces the
importance of data aggregation in programming.
6. Real-World Application: The ability to sum items in a dictionary is a valuable skill for data analysis and reporting tasks across
various domains, such as finance, inventory management, and statistical analysis.
Course Outcomes:
1. Proficiency in Data Structures: Students will demonstrate an understanding of Python dictionaries, including their structure and
how to manipulate them effectively for data organization and retrieval.
2. Application of Built-in Functions: Learners will be able to utilize built-in Python functions such as sorted() and sum(), applying
these functions to solve problems involving data aggregation and ordering.
3. Implementation of Sorting Algorithms: Students will gain the ability to implement sorting algorithms that allow for both
ascending and descending order sorting of dictionary values, enhancing their algorithmic thinking.
4. Error Handling and Data Validation: Learners will develop skills in implementing error handling techniques, ensuring
robustness in their code when dealing with potential non-numeric values during summation.
5. Practical Coding Skills: By completing hands-on coding exercises, students will enhance their practical programming skills,
enabling them to write clean, efficient, and functional Python scripts.
6. Problem Solving and Analytical Thinking: The course will foster problem-solving abilities through real-world applications of
sorting and summing operations, encouraging analytical thinking in data manipulation tasks.
7. Understanding of Functional Programming Concepts: Through the use of lambda functions and higher-order functions,
students will grasp fundamental concepts of functional programming within Python.
8. Preparation for Advanced Topics: Mastery of these foundational skills will prepare students for more advanced topics in
Python programming, such as data analysis, machine learning, or software development.
Conclusion:
Viva Questions:
Aim:
Learning Objectives:
Understanding Concepts: Learn the definitions and mathematical concepts of Highest Common Factor (HCF) and Lowest
Common Multiple (LCM).
Input Handling: Gain experience in taking user input for two integers.
Algorithm Implementation: Implement algorithms to compute HCF using the Euclidean method and derive LCM from HCF.
Output: Display the results clearly, showing both HCF and LCM.
Character Encoding: Understand what ASCII values are and how characters are represented in computers.
Using Built-in Functions: Learn to use Python's built-in ord() function to convert a character to its ASCII value.
User Interaction: Practice taking input from the user and displaying the output in a user-friendly format.
Basic Operations: Familiarize with basic arithmetic operations (addition, subtraction, multiplication, division).
Control Structures: Use control structures (like if-else statements) to handle user choices for different operations.
Functionality Implementation: Implement functions for each arithmetic operation to promote code reusability.
User Input and Output: Develop skills in handling user input dynamically and providing clear output based on calculations.
Theory:
a. Program to Find LCM and HCF.
Definitions
Highest Common Factor (HCF): Also known as the Greatest Common Divisor (GCD), the HCF of two or more
integers is the largest positive integer that divides each of the integers without leaving a remainder. For example,
the HCF of 12 and 18 is 6.
Lowest Common Multiple (LCM): The LCM of two or more integers is the smallest positive integer that is divisible
by each of the integers. For instance, the LCM of 12 and 18 is 36.
Mathematical Relationships
The relationship between HCF and LCM can be expressed with the formula:
HCF(A,B)×LCM(A,B)=A×B
This means that the product of the HCF and LCM of two numbers equals the product of those two numbers. This relationship can be used
to find one value if the other is known.
Take the remainder and repeat the process until the remainder is zero.
18÷12=118÷12=1 remainder 66
12÷6=212÷6=2 remainder 00
LCM(A,B)=A×BHCF(A,B)LCM(A,B)=HCF(A,B)A×B
This method leverages the relationship between HCF and LCM for efficient computation.
HCF: Write each number as a product of its prime factors. The HCF is obtained by multiplying the lowest powers of all
common prime factors.
LCM: Similarly, for LCM, multiply all prime factors using their highest powers.
Example Calculation
12 = 22 × 31
18= 21× 32
HCF=2min(2,1)× 3min(1,2)=21×31=6
LCM=2max(2,1)×3max(1,2)=22×32=36
Overview of ASCII
ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns unique numeric values to
characters, allowing for consistent representation and communication of text data in computers and other devices. Originally developed
in the early 1960s, ASCII uses a 7-bit binary system to represent 128 characters, including:
Digits (0-9)
The standard ASCII character set includes codes ranging from 0 to 127, where codes from 0 to 31 are reserved for control characters, and
codes from 32 to 127 represent printable characters. For example:
Binary Representation
Each ASCII character is represented in binary format. While the original ASCII encoding used 7 bits, modern systems typically use an 8-bit
representation to maintain compatibility with byte-oriented architectures. This means that each character can be represented as a binary
number, allowing computers to process and store text efficiently.For instance:
The binary representation of 'A' is 01000001, which corresponds to the decimal value 65.
The binary representation of 'a' is 01100001, corresponding to the decimal value 97.
Functions in Python
In Python, the built-in function ord() is used to obtain the ASCII value of a given character. This function takes a single character as an
argument and returns its corresponding ASCII integer value. Conversely, the chr() function can be used to convert an ASCII value back into
its corresponding character.
Applications of ASCII
Character Comparisons: Using ASCII values for sorting and comparing strings.
A simple calculator is a program that performs basic arithmetic operations such as addition, subtraction, multiplication, and division. It
serves as an excellent introductory project for beginners in programming, allowing them to apply fundamental concepts of programming
logic, user input handling, and control structures.
The four primary operations that a simple calculator typically supports are:
1. Addition (+): The process of calculating the total of two or more numbers. For example, 5+3=8.
2. Subtraction (−): The operation of finding the difference between two numbers. For example, 10−4=6.
3. Multiplication (×): The operation of scaling one number by another. For example, 7×2=14.
4. Division (÷): The process of splitting a number into equal parts. For example, 20÷5=4. Special care must be taken to handle
division by zero, which is undefined.
Program Structure
1. User Input: The program prompts the user to enter two numbers and choose an operation. This can be achieved using
the input() function in Python.
2. Control Structures: Based on the user's choice of operation, the program uses conditional statements (if-elif-else) to execute
the corresponding arithmetic operation.
3. Function Implementation: To promote code organization and reusability, each arithmetic operation can be encapsulated in its
own function. For example:
def divide(x, y): return x / y (with error handling for division by zero)
4. Output: After performing the calculation, the program displays the result to the user in a clear and understandable format.
Error Handling
Error handling is an essential aspect of building a robust calculator program. Common scenarios include:
Division by Zero: Attempting to divide by zero should be handled gracefully by checking if the divisor is zero before performing
the division.
Invalid Input: If the user inputs non-numeric values or an unsupported operation, the program should provide appropriate
feedback and prompt for correct input.
Code:
Output:
Learning Outcomes:
Understanding Mathematical Concepts: Learners will grasp the definitions and significance of Highest Common Factor (HCF)
and Lowest Common Multiple (LCM), including their applications in number theory and real-world problems.
Algorithm Development: Students will develop skills in creating algorithms to compute HCF and LCM using various methods,
such as the Euclidean algorithm for HCF and the relationship between HCF and LCM.
Python Implementation: Participants will learn to implement these algorithms in Python, enhancing their programming
proficiency by using loops, conditionals, and functions.
Debugging Skills: As they encounter and resolve issues in their code, learners will improve their debugging techniques,
fostering a deeper understanding of programming logic.
Character Encoding Knowledge: Students will understand the ASCII encoding standard, including how characters are
represented numerically in computers.
Use of Built-in Functions: Learners will become familiar with Python's built-in functions, specifically ord() for obtaining ASCII
values and chr() for converting ASCII values back to characters.
String Manipulation Skills: The task will enhance learners' abilities to manipulate strings and handle user input effectively,
contributing to their overall programming competence.
Application of Concepts: Participants will see practical applications of ASCII values in text processing, character comparisons,
and data encoding.
Basic Arithmetic Operations: Learners will reinforce their understanding of fundamental arithmetic operations (addition,
subtraction, multiplication, division) and how to implement them programmatically.
Control Structures Proficiency: Students will gain experience using control structures (if-else statements) to direct program
flow based on user input, which is crucial for interactive applications.
Functionality Design: Participants will learn to design and implement functions for each arithmetic operation, promoting
modular programming practices that enhance code readability and reusability.
Error Handling Techniques: The project will teach learners how to handle errors gracefully (e.g., division by zero), improving
their ability to create robust applications that can manage unexpected user inputs.
Course Outcomes:
Upon successful completion of the Python programming course, particularly focusing on the tasks of finding LCM and HCF, determining
ASCII values, and building a simple calculator, students will achieve the following outcomes:
Students will understand and apply fundamental mathematical concepts, including HCF and LCM, enhancing their
ability to solve problems involving divisibility and multiples.
Learners will develop skills to design and implement algorithms for computing HCF and LCM using various methods,
including the Euclidean algorithm, thereby reinforcing their problem-solving abilities.
Students will gain knowledge of character encoding standards, specifically ASCII, and learn to manipulate character
data effectively using Python's built-in functions.
Participants will acquire skills to create interactive applications that take user input, process it, and provide output,
enhancing their understanding of user interface design in programming.
Learners will become adept at implementing error handling techniques to manage exceptions (e.g., division by zero)
and improve the robustness of their applications.
Students will learn to write modular code by defining functions for each operation in the calculator program,
promoting code reusability and clarity.
Participants will effectively use control structures (if-else statements) to manage program flow based on user choices,
reinforcing their understanding of conditional logic in programming.
Students will demonstrate proficiency in Python syntax, including variable declaration, data types (integers, strings),
loops, and function definitions.
The course will lay a strong foundation for more advanced topics in programming, such as object-oriented
programming and data structure manipulation.
Viva Questions:
Aim:
a. Write a python program to access a range of items in an array by using the slicing operator.
b. Write a Python program To create an array of numeric values.
Learning Objectives:
Understanding Data Structures: Gain familiarity with lists as a fundamental data structure in Python, recognizing how they can
be used similarly to arrays in other programming languages.
Mastering Slicing Syntax: Learn the syntax and functionality of the slicing operator, including how to specify start and end
indices to access subarrays (slices) within a list.
Extracting Subsets of Data: Develop the ability to extract specific subsets of data from larger datasets, which is essential for
data manipulation and analysis.
Practical Application: Apply slicing techniques in practical scenarios, such as retrieving specific sections of data for further
processing or analysis.
Creating and Initializing Arrays: Understand how to create and initialize arrays (or lists) in Python, including the use of both
standard lists and the array module for specific numeric types.
Data Type Awareness: Learn about different data types that can be stored in arrays, focusing on numeric values and their
representation in Python.
Utilizing Built-in Libraries: Gain experience using Python's built-in libraries, such as the array module, to handle numeric data
efficiently.
Basic Input/Output Operations: Develop skills in displaying array contents using print statements and converting between
different data structures (e.g., converting an array to a list).
Foundation for Advanced Data Structures: Lay the groundwork for understanding more complex data structures and
operations in Python, such as lists of lists, multidimensional arrays, or external libraries like NumPy.
Theory:
In Python, the primary data structure used to store collections of items is called a list. Lists are versatile and can hold items of different
data types, including integers, floats, strings, and even other lists. While Python does not have a built-in array type like some
other programming languages (e.g., C or Java), lists serve a similar purpose and are often used interchangeably with arrays.
Slicing Operator
The slicing operator in Python allows you to access a subset of elements from a list.
start: The index of the first element you want to include in the slice. If omitted, it defaults to the beginning of the list (index 0).
end: The index of the first element you want to exclude from the slice. If omitted, it defaults to the end of the list.
step: This optional parameter specifies the increment between each index in the slice. If omitted, it defaults to 1.
Indexing
Python uses zero-based indexing, meaning that the first element of a list is at index 0, the second element is at index 1, and so forth.
Negative indexing can also be used to access elements from the end of the list, where -1 refers to the last element, -2 refers to
the second last, and so on.
Practical Applications
String Manipulation: Slicing can also be applied to strings in Python since strings are immutable sequences of characters.
Sub setting Data Structures: In more complex data structures (like lists of lists), slicing can help access sublists easily.
Introduction to Arrays
In Python, an array is a data structure that allows you to store multiple values of the same type in a single variable. Arrays are particularly
useful for handling collections of data, especially when performing mathematical operations or data analysis. While Python does
not have a built-in array type like some other programming languages, it provides several ways to create and manipulate arrays,
primarily through the array module and libraries like NumPy.
The array module in Python provides a way to create arrays that are more memory-efficient than lists when dealing with numeric data.
Arrays created using this module can only contain elements of the same type, which helps optimize performance and memory
usage.
Creating an Array
2. Define the type of elements the array will hold using a type code.
'f': Float
Arrays offer several advantages over lists when dealing with numeric data:
Memory Efficiency: Arrays consume less memory than lists since they store elements of a single data type.
Performance: Operations on arrays are generally faster due to their contiguous memory allocation and optimized processing
capabilities.
Functionality: Libraries such as NumPy provide extensive functionality for numerical computations, including mathematical
operations, statistical analysis, and more.
NumPy is a powerful library in Python that provides support for creating and manipulating arrays. It allows for multidimensional arrays
and offers a wide range of mathematical functions.
This array can be used for various mathematical operations and analyses.
Practical Applications
Scientific Computing: Performing complex calculations efficiently using libraries like NumPy.
Code:
Output:
Learning Outcomes:
1. Understanding Slicing Syntax: Students will learn the syntax and functionality of the slicing operator in Python, enabling them
to access specific subsets of data within arrays (or lists) efficiently.
2. Data Manipulation Skills: Learners will develop skills in manipulating and extracting portions of data, which is essential for data
analysis and processing tasks.
3. Familiarity with Indexing: Participants will gain an understanding of zero-based indexing and how to use both positive and
negative indices to access elements from arrays.
4. Practical Application of Slicing: Students will apply slicing techniques in practical scenarios, enhancing their ability to work with
large datasets by extracting relevant information without modifying the original array.
5. Performance Awareness: Learners will become aware of performance considerations when using slicing, understanding how it
can create views instead of copies, which can improve memory efficiency.
1. Creating and Initializing Arrays: Students will learn how to create and initialize arrays (or lists) in Python, including the use of
the array module for numeric data types.
2. Data Type Understanding: Learners will understand different data types that can be stored in arrays and how to specify these
types using type codes in the array module.
3. Utilization of Libraries: Participants will gain experience using built-in libraries such as NumPy for creating and manipulating
arrays, enhancing their programming toolkit for numerical computations.
4. Basic Input/Output Operations: Students will develop skills in displaying array contents and converting between different data
structures (e.g., converting an array to a list).
5. Foundation for Advanced Data Structures: Learners will establish a foundation for understanding more complex data
structures and operations in Python, preparing them for future learning in data science or numerical analysis.
Course Outcomes:
Upon successful completion of the Python programming course, particularly focusing on tasks related to accessing a range of items in an
array using the slicing operator and creating an array of numeric values, students will achieve the following outcomes:
Students will demonstrate the ability to create, initialize, and manipulate arrays (or lists) in Python, including
accessing elements through indexing and slicing techniques.
Learners will understand and apply the slicing operator to extract specific subsets of data from arrays, enhancing their
skills in data retrieval and manipulation.
Participants will gain a solid understanding of basic data structures in Python, particularly lists and arrays, and their
respective use cases in programming.
Students will learn to create and manage arrays of numeric values efficiently, preparing them for tasks involving
mathematical computations and data analysis.
The course will lay a strong foundation for more advanced topics in data structures and algorithms, such as
multidimensional arrays, NumPy arrays, and data manipulation techniques used in data science.
7. Problem-Solving Skills:
Students will enhance their problem-solving abilities by applying array manipulation techniques to solve practical
programming challenges and real-world scenarios.
Participants will be introduced to libraries like NumPy for efficient array handling and numerical computations,
preparing them for future work in scientific computing or data analysis.
Conclusion:
Viva Questions: