Operators in Python
* Arithmetic Operators
* Relational Operators
* Logical Operators
* Bitwise Operators
* Assignment Operators
* Membership Operators
Python arithmetic operators demonstration with basic mathematical operations
Explanation
- Addition operator (+) adds two numbers together, producing 11 from 5 and 6
- Subtraction operator (-) finds the difference between two numbers, resulting in -1
- Multiplication operator (*) calculates the product of two numbers, giving 30
- Division operator (/) performs floating-point division, returning 2.5 for 5 divided by 2
- Modulus operator (%) returns the remainder after division, yielding 1 when dividing 5 by 2
- Exponentiation operator (**) raises a number to a power, producing 25 when calculating 5 squared
Output
Demonstrating Python's relational operators for comparing numerical values
Explanation
- The code evaluates six different relational comparisons between the numbers 4 and 5 using Python's comparison operators
- Each print statement outputs the boolean result (True or False) of the specified relationship between the two numbers
- The greater than (>) operator checks if 4 is larger than 5, returning False
- The less than (<) operator checks if 4 is smaller than 5, returning True
- The equality (==) and inequality (!=) operators demonstrate how to check for exact value matching or differences between values
Output
Understanding Python's logical operators AND, OR, and NOT with boolean operations
Explanation
- The
andoperator returns the first falsy value or the last value if all are truthy, demonstrating short-circuit evaluation where it stops at the first falsy operand - The
oroperator returns the first truthy value or the last value if all are falsy, also using short-circuit evaluation by stopping at the first truthy operand - The
notoperator performs logical negation, converting truthy values to False and falsy values to True - These operators work with any truthy/falsy values, not just boolean literals, making them versatile for conditional logic
- The output shows that
1 and 0returns0,1 or 0returns1, andnot 0returnsTrue
Output
Understanding bitwise operations in Python with AND, OR, XOR, NOT, left shift, and right shift operators
Explanation
- Bitwise AND (&) compares each bit of two numbers and returns 1 only if both bits are 1, demonstrating binary digit comparison
- Bitwise OR (|) returns 1 if at least one of the compared bits is 1, showing how binary values combine
- Bitwise XOR (^) produces 1 when bits differ and 0 when they're identical, useful for toggling bits and encryption
- Bitwise NOT (~) inverts all bits of a number, converting positive integers to negative using two's complement representation
- Left shift (<<) and right shift (>>) operators move bits horizontally to multiply or divide by powers of two respectively
Output
Understanding the Use of Assignment Operators in Python for Variable Manipulation
Explanation
- The code demonstrates various assignment operators in Python, which modify the value of a variable based on its current value.
- The
+=operator adds a specified value (2) to the variableaand updates it, resulting in4. - The
*=operator multiplies the current value ofa(2) by 2, updating it to4. - The
/=operator divides the current value ofa(2) by 2, resulting in1.0(float). - The
//=operator performs floor division ona(2) by 2, updating it to1. - The
%=operator calculates the modulus ofa(2) by 2, resulting in0.
Output
Demonstrating the usage of membership operators in Python for checking element presence
Explanation
- The code uses the
inandnot inmembership operators to check if specific elements exist within various data structures. - The first two print statements check if the character 'D' and 'A' are present in the string 'Delhi', returning
Truefor 'D' andFalsefor 'A'. - The third print statement checks if the integer
1is in the list[1, 2, 3, 4], which returnsTrue. - The fourth print statement verifies if the key 'name' exists in a dictionary, returning
Truesince 'name' is a key in the provided dictionary. - The last print statement checks for the presence of the value 'Madhu' in the same dictionary, returning
Falseas 'Madhu' is not a key.
Output
Calculate the sum of the digits in a user-provided three-digit number
Explanation
- Prompts the user to input a three-digit number and converts it to an integer.
- Extracts each digit from the number using the modulus operator and integer division.
- Computes the sum of the extracted digits (units, tens, and hundreds).
- Outputs the total sum of the digits to the console.
Output
If-else in Python
Simple email and password authentication system with credential validation
Explanation
- The code prompts users to enter their email address and password through console input
- It validates the entered credentials against hardcoded values using a logical AND condition
- Upon successful authentication, it greets the user by their email address
- If either the email or password doesn't match the expected values, it displays an error message
- This demonstrates basic input handling and conditional logic for user authentication
Output
User authentication check using email and password in Python
Explanation
- The code prompts the user to input their email address and password.
- It checks if the provided email matches a predefined email and if the password is correct.
- If both the email and password are correct, it welcomes the user.
- If the email is correct but the password is incorrect, it notifies the user of the incorrect password.
- For any other email input, it indicates that the credentials are incorrect.
Output
User authentication process with email and password validation in Python
Explanation
- Prompts the user to input their email address and password for authentication.
- Checks if the provided email matches a predefined value and validates the password.
- If the email is correct but the password is incorrect, it prompts the user to re-enter the password.
- If the re-entered password is correct, it grants access; otherwise, it indicates a second failure.
- If the email does not match, it informs the user of incorrect credentials.
Output
Finding the minimum value among three integers using conditional logic
Explanation
- Takes three integer inputs from user interaction through stdin prompts
- Uses nested conditional statements (if/elif/else) to compare all three numbers systematically
- Compares first number against the other two to determine if it's the smallest
- If first number isn't smallest, compares the remaining two numbers to find the minimum
- Outputs the smallest number with a descriptive message to console
Output
Interactive arithmetic calculator with menu-driven operation selection
Explanation
- Takes two integer inputs from user for mathematical operands and one string input for the desired operation
- Uses conditional statements (if/elif/else) to evaluate the operator and perform corresponding arithmetic calculation
- Handles four basic operations: addition, subtraction, division, and multiplication with appropriate output display
- Provides error handling for invalid operation inputs by displaying an incorrect operation message
- Demonstrates fundamental input/output operations combined with decision-making logic in Python programming
Output
Modules in Python
* math
* keywords
* constant
* random
Mathematical operations using Python's built-in math module functions
Explanation
- The code demonstrates basic mathematical operations including factorial calculation, floor and ceiling rounding, and square root computation
- math.factorial(5) calculates the product of all positive integers up to 5, returning 120
- math.floor(6.4) returns the largest integer less than or equal to 6.4, which is 6
- math.ceil(6.4) returns the smallest integer greater than or equal to 6.4, which is 7
- math.sqrt(5) computes the square root of 5, returning approximately 2.236
Output
Retrieve the list of reserved keywords in Python programming language
Explanation
- The
import keywordstatement imports thekeywordmodule, which provides functions related to Python's keywords. - The
keyword.kwlistattribute returns a list of all the reserved keywords in Python, which cannot be used as identifiers (like variable names). - This list is useful for developers to avoid naming conflicts and to understand the syntax rules of the Python language.
- The keywords include terms like
if,else,for,while, and many others that have special meanings in Python.
Output
Generate a random integer between 1 and 100 using Python's random module
Explanation
- The code imports the
randommodule, which provides functions for generating random numbers. - It uses the
randintfunction to generate a random integer within a specified range, inclusive of both endpoints. - The
printfunction outputs the generated random integer to the console. - In this case, the range is set from 1 to 100, meaning any integer within this range can be produced.
Output
Retrieve and display the current date and time using Python's datetime module
Explanation
- The code imports the
datetimemodule, which provides classes for manipulating dates and times. - It calls the
now()method from thedatetimeclass to get the current local date and time. - The result is printed to the console, showing the exact moment the code is executed.
- This snippet is useful for logging events or timestamps in applications.
Output
This code snippet retrieves a list of available modules in Python's standard library.
Explanation
- The
help()function is a built-in Python function that provides interactive help. - By passing the string
'modules'tohelp(), it triggers the display of all available modules in the current Python environment. - This can be useful for discovering libraries and modules that can be imported for various functionalities.
- The output will be a list of modules, which may include both standard library modules and any installed third-party packages.
- This command is typically run in a Python interactive shell or script to aid in development and exploration.
Loops in Python
* While Loop
* For Loop
This Python code generates a multiplication table for a user-defined number using a while loop.
Explanation
- The user is prompted to input a number, which is converted to an integer and stored in the variable
number. - A variable
iis initialized to 1, which will be used to iterate through the numbers 1 to 10. - A while loop runs as long as
iis less than 11, printing the multiplication result ofnumberandiin a formatted string. - After each iteration,
iis incremented by 1 to progress through the multiplication table. - The output displays the multiplication results in the format "number * i = result".
Output
This Python code demonstrates the use of a while loop with an else clause to indicate when a condition is no longer met.
Explanation
- Initializes a variable
xwith a value of 1. - The while loop continues to execute as long as
xis less than 3, printing the current value ofxand incrementing it by 1 in each iteration. - Once
xreaches 3, the loop terminates, and the else block executes, printing 'Limit crossed'. - The else clause is executed only when the while loop completes normally (not interrupted by a break statement).
Output
A simple number guessing game that provides feedback on user guesses until the correct number is found.
Explanation
- The code imports the
randommodule to generate a random integer between 1 and 100, which serves as the target number for the guessing game. - It prompts the user to input their guess and initializes a counter to track the number of attempts.
- A
whileloop continues to execute as long as the user's guess does not match the randomly generated number, providing hints to guess higher or lower. - Once the correct number is guessed, the loop exits, and the total number of attempts is printed to the user.
- This interactive game allows users to practice their guessing skills while receiving immediate feedback on their inputs.
Output
This code snippet demonstrates how to use a for loop to print numbers from 1 to 10.
Explanation
- The
forloop iterates over a sequence generated byrange(1, 11), which produces numbers from 1 to 10. - The variable
itakes on each value in the range during each iteration of the loop. - The
print(i)statement outputs the current value ofito the console. - This loop will execute a total of 10 times, displaying each number on a new line.
Output
This code snippet prints odd numbers from 1 to 10.
Explanation
- The
range(1, 11, 2)function generates a sequence of numbers starting from 1 to 10, incrementing by 2. - The loop iterates over this sequence, assigning each value to the variable
i. - The
print(i)statement outputs the current value ofiduring each iteration. - As a result, the output will be the odd numbers: 1, 3, 5, 7, and 9.
Output
This code snippet demonstrates how to iterate through a range of numbers with a specified step size.
Explanation
- The
range(1, 11, 4)function generates numbers starting from 1 up to, but not including, 11, with a step of 4. - The loop will produce the values 1, 5, and 9, as these are the only numbers in the specified range that fit the criteria.
- The
print(i)statement outputs each value ofito the console during each iteration of the loop. - This approach is useful for generating sequences where a specific interval is required between numbers.
Output
This code snippet counts down from 10 to 1 and prints each number.
Explanation
- The
forloop iterates over a range of numbers starting from 10 down to 1. - The
range(10, 0, -1)function generates numbers starting at 10, ending before 0, with a step of -1. - Each iteration prints the current value of
i, resulting in a countdown display. - The output will be the numbers 10 through 1, each on a new line.
Output
This code iterates through each character in the string 'Delhi' and prints them individually.
Explanation
- The
forloop iterates over each character in the string 'Delhi'. - The variable
itakes on the value of each character in the string during each iteration. - The
print(i)statement outputs the current character to the console. - This results in each character of 'Delhi' being printed on a new line.
Output
This code snippet iterates through a list of numbers and prints each one sequentially.
Explanation
- The code uses a
forloop to iterate over a predefined list of integers from 1 to 10. - Each integer in the list is accessed one at a time and printed to the console.
- This demonstrates a basic use of loops in Python for iterating through collections.
- The output will display each number on a new line, from 1 to 10.
Output
Iterating through a dictionary to print its keys in Python
Explanation
- The code uses a
forloop to iterate over a dictionary containing two key-value pairs: 'name' and 'age'. - During each iteration, the variable
itakes on the value of each key in the dictionary. - The
print(i)statement outputs the current key to the console. - As a result, the output will display 'name' followed by 'age', each on a new line.
- This demonstrates how to access and display dictionary keys without retrieving their associated values.
Output
Program - The current population of a town is 10000. The population of the town is increasing at the rate of 10% per year. You have to write a program to find out the population at the end of each of the last 10 years.
This code simulates a declining population over a series of iterations.
Explanation
- Initializes a variable
curr_popwith a starting population of 10,000. - Uses a for loop to iterate from 10 down to 1, printing the current iteration number and the population.
- In each iteration, the population is reduced by dividing it by 1.1, simulating a decline.
- The loop runs a total of 10 times, showing the population decrease at each step.
Output
Sequence Sum
1/1! + 2/2! + 3/3!
This code calculates the sum of the series 1/n! for a given integer n.
Explanation
- The user is prompted to input an integer value, which is converted to an integer and stored in the variable
n. - Two variables,
resultandfact, are initialized to 0 and 1 respectively;resultwill hold the final sum, whilefactwill be used to compute factorial values. - A for loop iterates from 1 to
n, calculating the factorial of each number and updatingresultby adding the fraction of the current indexiover its factorialfact. - After the loop completes, the final computed value of
resultis printed, representing the sum of the series.
Output
Nested Loops
Generating unique pairs of numbers within a specified range
Explanation
- The outer loop iterates through numbers 1 to 4, assigning each value to
i. - The inner loop also iterates through numbers 1 to 4, assigning each value to
j. - For each combination of
iandj, the code prints the pair as a tuple. - This results in a total of 16 unique pairs being printed, covering all combinations of the two ranges.
Output
Pattern (Number)
*
**
***
This code generates a right-angled triangle pattern using asterisks based on user input for the number of rows.
Explanation
- The user is prompted to enter the number of rows for the triangle pattern.
- A nested loop structure is used, where the outer loop iterates through each row from 1 to the specified number of rows.
- The inner loop prints asterisks (
*) for each column in the current row, increasing the count of asterisks with each subsequent row. - The
end=''parameter in the print function prevents a newline after each asterisk, allowing them to be printed on the same line. - After completing each row, a
print()statement is called to move to the next line for the subsequent row's output.
Output
This code generates a right-angled triangle pattern using asterisks based on user input for the number of rows.
Explanation
- The code prompts the user to input the desired number of rows for the triangle.
- It converts the input into an integer and stores it in the variable
rows. - A
forloop iterates from 1 to the specified number of rows, inclusive. - In each iteration, it prints a line of asterisks, where the number of asterisks corresponds to the current iteration number.
- This results in a right-angled triangle shape, with each row containing an increasing number of asterisks.
Output
Pattern (Number)
1
121
12321
1234321
Generate a symmetrical pattern of numbers based on user-defined rows
Explanation
- The code prompts the user to input the number of rows for the pattern.
- It uses a nested loop structure where the outer loop iterates through each row from 1 to the specified number of rows.
- The first inner loop prints numbers in ascending order from 1 to the current row number.
- The second inner loop prints numbers in descending order from the current row number minus one back to 1.
- Each completed row is followed by a newline, creating a symmetrical pattern of numbers.
Output
Loop Control Statement
* Break
* Continue
* Pass
This code snippet demonstrates the use of the break statement to exit a loop prematurely.
Explanation
- The loop iterates over a range of numbers from 1 to 9.
- When the loop variable
iequals 5, thebreakstatement is triggered. - The
breakstatement terminates the loop, preventing any further iterations. - As a result, the numbers 1 through 4 are printed, while 5 and subsequent numbers are not.
- This showcases how to control loop execution based on a condition.
Output
Python program to find and display prime numbers within a specified range using nested loops
Explanation
- The code prompts users to input lower and upper bounds to define a range of numbers to check for primes
- It uses nested loops where the outer loop iterates through each number in the given range
- The inner loop checks divisibility of each number by all integers from 2 up to (but not including) the number itself
- When a divisor is found, the inner loop breaks and the else clause is skipped, meaning non-prime numbers are filtered out
- Prime numbers that pass all divisibility tests are printed to the console
Output
Using the continue statement to skip iterations in a Python loop
Explanation
- The code creates a loop that iterates through numbers from 1 to 9 using range(1,10)
- When the loop variable i equals 5, the continue statement immediately jumps to the next iteration without executing the print statement
- This demonstrates how continue can be used to bypass specific conditions, such as skipping unavailable items in a product catalog
- The output shows all numbers from 1 to 9 except 5, illustrating the skip behavior of the continue statement
- The comment suggests a practical application where continue might be used to skip products that are out of stock
Output
Understanding the pass statement in Python loops for conditional execution
Explanation
- The code uses a for loop to iterate through numbers 1 to 9, demonstrating how pass acts as a null operation that does nothing when encountered
- When the loop variable equals 5, the pass statement is executed but has no effect on program flow or output
- The pass keyword serves as a placeholder where Python syntax requires a statement but no action is needed
- This pattern is commonly used for error handling scenarios where you want to skip certain conditions without breaking the loop structure
- The output shows all numbers from 1 to 9 printed sequentially, with pass having no visible impact on the execution flow
Output
Problem 1: Write a program that will give you in hand monthly salary after deduction on CTC - HRA(10%), DA(5%), PF(3%) and taxes deduction as below:
Salary(Lakhs) : Tax(%)
- Below 5 : 0%
- 5-10 : 10%
- 10-20 : 20%
- aboove 20 : 30%
Calculate net monthly salary based on annual CTC with progressive tax brackets
Explanation
- Takes user input for annual cost to company (CTC) and applies different multipliers based on salary ranges
- Uses conditional statements to determine the appropriate multiplier: 82% for below 500k, 72% for 500k-1M, 62% for 1M-2M, and 52% for above 2M
- Calculates the net annual salary by multiplying CTC with the applicable percentage and divides by 12 to get monthly amount
- Rounds the final monthly salary to two decimal places for clean output formatting
Output
Problem 2: Write a program that take a user input of three angles and will find out whether it can form a triangle or not.
Validate if three angles can form a triangle based on user input
Explanation
- Prompts the user to input three angles and converts them to integers.
- Checks if the sum of the three angles equals 180 degrees, which is a requirement for triangle formation.
- Ensures that all angles are positive values, as negative angles cannot form a triangle.
- Prints a message indicating whether the provided angles can form a triangle or not based on the conditions checked.
Output
Problem 3: Write a program that will take user input of cost price and selling price and determines whether its a loss or a profit.
Determine Profit, Loss, or No Gain from Selling Price and Cost Price in Python
Explanation
- Prompts the user to input the cost price and selling price as integers.
- Compares the cost price with the selling price to determine the financial outcome.
- Prints "Profit" if the selling price is higher than the cost price.
- Prints "Loss" if the selling price is lower than the cost price.
- Prints "No Loss No Gain" if both prices are equal, indicating a break-even situation.
Output
Problem 4: Write a menu-driven program -
- cm to ft
- km to miles
- USD to INR
- exit
This code snippet provides a simple unit conversion menu for users to select various conversions.
Explanation
- The code prompts the user to select a conversion option from a menu, including centimeters to feet, kilometers to miles, and USD to INR.
- Based on the user's choice, it takes the necessary input value and performs the corresponding conversion calculation.
- The conversion formulas used are: 1 cm = 0.032 ft, 1 km = 0.62 miles, and 1 USD = 90 INR.
- If the user selects an invalid option, the program exits without performing any conversion.
- The use of
floatensures that the input values can be decimal numbers, allowing for more precise conversions.
Output
Problem 5 - Exercise 12: Display Fibonacci series up to 10 terms.
Note: The Fibonacci Sequence is a series of numbers. The next number is found by adding up the two numbers before it. The first two numbers are 0 and 1. For example, 0, 1, 1, 2, 3, 5, 8, 13, 21. The next number in this series above is 13+21 = 34
This code generates and prints the first ten numbers of the Fibonacci sequence.
Explanation
- Initializes two variables,
num1andnum2, to represent the first two numbers in the Fibonacci sequence (0 and 1). - Uses a
forloop to iterate 10 times, corresponding to the first ten Fibonacci numbers. - In each iteration, it prints the current value of
num1, which starts at 0 and updates in each loop. - Calculates the next Fibonacci number by summing
num1andnum2, then updatesnum1andnum2for the next iteration. - The loop effectively builds the sequence by shifting the values of
num1andnum2forward.
Output
Problem 6 - Find the factorial of a given number.
Write a program to use the loop to find the factorial of a given number.
The factorial (symbol: !) means to multiply all whole numbers from the chosen number down to 1.
For example: calculate the factorial of 5
Output:
This code calculates the factorial of a user-provided integer input.
Explanation
- The user is prompted to enter an integer, which is converted from a string to an integer using
int(). - A variable
factis initialized to 1 to hold the result of the factorial calculation. - A
forloop iterates from 1 to the entered number (inclusive), multiplyingfactby each integer in this range. - Finally, the computed factorial is printed to the console.
Output
Problem 7 - Reverse a given integer number.
Example:
Input:
Output:
This code reverses the digits of an input number and prints the result.
Explanation
- The user is prompted to enter a number, which is then converted to an integer.
- A while loop iterates as long as the number is greater than zero, extracting the last digit using the modulus operator.
- The last digit is appended to the reversed number by multiplying the current reversed value by 10 and adding the last digit.
- The original number is reduced by removing the last digit using integer division.
- Finally, the reversed number is printed to the console.
Output
Problem 8: Take a user input as integer N. Find out the sum from 1 to N. If any number if divisible by 5, then skip that number. And if the sum is greater than 300, don't need to calculate the sum further more. Print the final result. And don't use for loop to solve this problem.
Example 1:
Input:
Output:
This code calculates the sum of numbers up to a given input while skipping multiples of five and stopping at a threshold.
Explanation
- The user is prompted to enter a number, which is converted to an integer and stored in variable
N. - A loop iterates through numbers from 1 to
N, checking each number to see if it is a multiple of 5; if so, it skips to the next iteration. - The current number is added to a cumulative sum unless adding it exceeds 300, in which case the last added number is subtracted and the loop breaks.
- Finally, the resulting sum is printed, which is the total of all valid numbers below
Nthat are not multiples of five and do not cause the sum to exceed 300.
Output
Problem 9: Write a program that keeps on accepting a number from the user until the user enters Zero. Display the sum and average of all the numbers.
This code calculates the sum and average of user-inputted numbers until zero is entered.
Explanation
- Initializes two variables,
sumandcount, to store the cumulative total and the number of inputs, respectively. - Enters an infinite loop where it prompts the user to input a number.
- If the user inputs
0, the loop breaks, stopping further input. - Adds the input number to
sumand incrementscountfor each valid input. - After exiting the loop, it prints the total sum and the average of the numbers, rounded to two decimal places.
Output
###Problem 9: Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.
This code generates a list of numbers between 2000 and 3200 that are divisible by 7 but not by 5.
Explanation
- Initializes an empty list
Lto store the qualifying numbers. - Iterates through the range of numbers from 2000 to 3200 using a for loop.
- Checks if each number is divisible by 7 and not divisible by 5 using conditional statements.
- Appends the qualifying numbers (converted to strings) to the list
L. - Finally, prints the numbers in
Las a comma-separated string.
Output
###Problem 10: Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a space-separated sequence on a single line.
This code generates a list of even-digit numbers between 1000 and 3000.
Explanation
- Initializes an empty list
Lto store numbers with only even digits. - Iterates through each number
ifrom 1000 to 3000. - For each number, checks each digit by extracting the last digit using modulo operation and verifies if it is even.
- If any digit is found to be odd, it sets a flag to
Falseand breaks the loop. - If all digits are even, the number is converted to a string and added to the list
L, which is then printed as a comma-separated string.
Output
###Problem 11: A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
The numbers after the direction are steps.
!means robot stop there.
Please write a program to compute the distance from current position after a sequence of movement and original point.
If the distance is a float, then just print the nearest integer.
Example:
Input:
Output:
This code calculates the final distance of a robot from the origin based on user-defined movements.
Explanation
- Initializes the robot's position at the origin (0,0) in a 2D space.
- Continuously prompts the user for input to specify movement direction and steps until the user inputs '!' to terminate.
- Parses the input to determine the direction (UP, DOWN, LEFT, RIGHT) and the number of steps to move in that direction.
- Updates the robot's position based on the specified direction and steps.
- Finally, computes and prints the Euclidean distance from the origin using the formula √(x² + y²).
Output
###Problem 12:Write a program to print whether a given number is a prime number or not
This code checks if a given number is prime or not.
Explanation
- The user is prompted to input a number, which is then converted to an integer.
- A boolean variable
flagis initialized toTrue, assuming the number is prime until proven otherwise. - A for loop iterates from 2 to one less than the input number, checking for divisibility.
- If the number is divisible by any of these integers,
flagis set toFalse, and the loop breaks. - Finally, the program prints "Prime" if
flagremainsTrue, otherwise it prints "Not Prime".
Output
###Problem 13:Print all the Armstrong numbers in a given range.
Range will be provided by the user
Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
This Python code snippet demonstrates how to read a CSV file and calculate the average of a specific column.
Explanation
- The code utilizes the
pandaslibrary to handle CSV file operations efficiently. - It reads the CSV file into a DataFrame, allowing for easy data manipulation and analysis.
- A specific column is selected to compute its average using the
mean()function. - The result is printed to the console, providing a quick summary of the data analysis.
###Problem 14:Calculate the angle between the hour hand and minute hand.
Note: There can be two angles between hands; we need to print a minimum of two. Also, we need to print the floor of the final result angle. For example, if the final angle is 10.61, we need to print 10.
Input: H = 9 , M = 0 Output: 90 Explanation: The minimum angle between hour and minute hand when the time is 9 is 90 degress.
This Python code snippet demonstrates how to read a CSV file and calculate the average of a specific column.
Explanation
- The code utilizes the
pandaslibrary to handle CSV file operations efficiently. - It reads the CSV file into a DataFrame, allowing for easy data manipulation and analysis.
- A specific column is selected to compute its average using the
mean()function. - The result is printed to the console, providing a quick summary of the data analysis.
###Problem 15:Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by providing the x and y coordinates of two points: the left top corner and the right bottom corner of the rectangle. Two rectangles sharing a side are considered overlapping. (L1 and R1 are the extreme points of the first rectangle and L2 and R2 are the extreme points of the second rectangle).
Note: It may be assumed that the rectangles are parallel to the coordinate axis.
This Python code snippet demonstrates how to read a CSV file and calculate the average of a specific column.
Explanation
- The code utilizes the
pandaslibrary to handle CSV file operations efficiently. - It reads the CSV file into a DataFrame, allowing for easy data manipulation and analysis.
- A specific column is selected to compute its average using the
mean()function. - The result is printed to the console, providing a quick summary of the data analysis.
Next in this series: Python Strings: Methods, Formatting & f-Strings Guide →

