Operators in Python
* Arithmetic Operators
* Relational Operators
* Logical Operators
* Bitwise Operators
* Assignment Operators
* Membership Operators
Example 1
Explanation
- Performs basic arithmetic operations on numbers 5 and 6 using Python's mathematical operators
- Uses addition (+), subtraction (-), multiplication (*), division (/), floor division (//), modulus (%), and exponentiation (**)
- Prints the result of each operation to the console
- Floor division (//) returns the quotient without decimal places
- Modulus (%) returns the remainder after division, and exponentiation (**) raises the first number to the power of the second
Output
Example 2
Explanation
- This code demonstrates relational operators that compare two values and return boolean results (True/False)
- It uses six different comparison operators: greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equal to (==), and not equal to (!=)
- Each print statement evaluates one comparison operation between the numbers 4 and 5
- The output shows False for 4>5, True for 4<5, False for 4>=5, True for 4<=5, False for 4==5, and True for 4!=5
- These operators are fundamental for making decisions and controlling program flow based on value comparisons
Output
Example 3
Explanation
- The code demonstrates Python's logical operators:
and,or, andnotwith simple integer values - Uses the
print()function to display the results of logical operations between integers - In Python,
andreturns the first falsy value or last value if all are truthy - In Python,
orreturns the first truthy value or last value if all are falsy - The
notoperator converts a value to its boolean opposite (True becomes False and vice versa)
Output
Example 4
Explanation
- Performs bitwise operations on integers by treating them as binary numbers
- Uses bitwise AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>) operators
- Shows how binary digits are compared and manipulated at the bit level
- Left shift (<<) moves bits to the left, effectively multiplying by powers of 2
- Right shift (>>) moves bits to the right, effectively dividing by powers of 2
Output
Example 5
Explanation
- Assigns initial value of 2 to variable
a, then uses augmented assignment operators to modifyain place - Uses
+=operator to add 2 toaand reassign the result back toa - Uses
*=operator to multiplyaby 2 and reassign the result back toa - Uses
/=operator to divideaby 2 and reassign the result back toa - Uses
//=operator to perform floor division ofaby 2 and reassign the result back toa
Output
Example 6
Explanation
- Checks if elements exist within sequences or collections using the
inandnot inoperators - Tests membership in different data types: string 'Delhi', list [1,2,3,4], and dictionary {'name': 'Madhu', 'age': 30}
- The
inoperator returns True if the left operand exists as a substring, list element, or dictionary key - First two prints show 'D' is found in 'Delhi' (True) but 'A' is not found (False)
- Last three prints show 1 is found in the list (True), 'name' is found as a dictionary key (True), but 'Madhu' is not found as a key (False) since it's a value
Output
Example 7
Explanation
- Takes a 3-digit number as input from user and stores it as integer in variable
number - Extracts individual digits using modulo operator (%) and integer division (//) operations
- First digit extraction: gets last digit with
number%10, then removes it withnumber//10 - Repeats process twice more to extract all three digits into variables a, b, and c
- Prints the sum of all three extracted digits to console
Output
If-else in Python
Example 8
Explanation
- Takes user input for email and password using input() function
- Checks if entered credentials match hardcoded values using conditional if statement
- Uses logical AND operator to validate both email and password together
- Prints welcome message if credentials are correct, otherwise shows error message
- Has no return value but produces console output based on user input validation
Output
Example 9
Explanation
- Takes email and password input from user and checks if they match predefined credentials
- Uses if/elif/else conditional statements to validate login attempts
- Compares email against 'madhu.kumar245@gmail.com' and password against '1234'
- Prints different messages based on whether email matches, password matches, or neither matches
- Displays welcome message, password error, or general credential error depending on input validation results
Output
Example 10
Explanation
- Takes email and password input from user and validates against hardcoded credentials
- Uses if/elif/else conditional statements to check email and password match
- Prints different messages based on whether email matches, password matches, or neither match
- Has nested conditional logic to allow one retry attempt for incorrect password
- Outputs welcome message, error messages, or access denied message based on validation results
Output
Example 11
Explanation
- Takes three integer inputs from user and stores them in variables a, b, and c
- Uses conditional statements (if/elif/else) to compare the three numbers and find the smallest
- Compares a with both b and c first, then compares b with c if a isn't the smallest
- Prints which number is the smallest based on the comparisons made
- Side effect is displaying the result to console showing the minimum value among the three inputs
Output
Example 12
Explanation
- Takes two numbers and an operation as user input to perform basic arithmetic calculations
- Uses input() function to get user data and converts strings to integers with int()
- Implements if-elif-else conditional logic to handle four different mathematical operations
- Prints the result of the calculation or an error message for invalid operations
- Has no loops or complex data structures, just simple decision making based on user input
Output
Modules in Python
* math
* keywords
* constant
* random
Example 13
Explanation
- Imports the built-in math module to access mathematical functions
- Calculates and prints the factorial of 5 (which is 5×4×3×2×1 = 120)
- Uses math.floor() to round down 6.4 to the nearest integer (6.0)
- Uses math.ceil() to round up 6.4 to the nearest integer (7.0)
- Computes and prints the square root of 5 (approximately 2.236)
Output
Example 14
Explanation
- This code imports the
keywordmodule and accesses itskwlistattribute to get a list of all Python reserved keywords - The
keyword.kwlistprovides a predefined list containing all words that have special meaning in Python syntax - Common keywords like
if,else,for,while,def,class,import,from,try,exceptare included in this list - The code doesn't perform any operations but simply retrieves and displays the complete list of Python keywords
- This is useful for developers to understand which words cannot be used as variable names or identifiers in Python programs
Output
Example 15
Explanation
- Imports the random module to generate pseudo-random numbers
- Uses randint() function to produce a random integer between 1 and 100 (inclusive)
- Prints a single random number from the specified range to the console
- Each execution will likely produce a different output number between 1-100
- The random module uses a deterministic algorithm but appears random for most applications
Output
Example 16
Explanation
- Imports the datetime module to work with dates and times in Python
- Uses datetime.datetime.now() to get the current date and time from the system
- Prints the current date and time in year-month-day hour:minute:second.microsecond format
- The function returns a datetime object representing the exact moment when the code executes
- Output shows something like "2023-12-07 14:30:45.123456" depending on when it's run
Output
Example 17
Explanation
- The code calls the built-in
help()function with the argument'modules'. - This command displays a list of all available modules in the current Python environment.
- It provides a brief description of each module, helping users understand what is available for import.
- The output is typically a long list printed to the console, which may include standard library modules and installed third-party packages.
Loops in Python
* While Loop
* For Loop
Example 18
Explanation
- Prompts the user to enter a number and converts the input to an integer.
- Initializes a counter variable
ito 1 and uses awhileloop to iterate as long asiis less than 11. - Inside the loop, it prints the multiplication table for the entered number, showing the product of the number and the current value of
i. - Increments
iby 1 in each iteration to progress through the table. - The expected output is the multiplication table of the entered number from 1 to 10.
Output
Example 19
Explanation
- Initializes a variable
xwith the value 1. - Enters a
whileloop that continues as long asxis less than 3. - Prints the current value of
xand increments it by 1 in each iteration. - Once
xreaches 3, the loop exits and theelseblock executes, printing 'Limit crossed'. - Expected output:
Output
Example 20
Explanation
- Generates a random number between 1 and 100 as the target "jackpot" value
- Takes user input guesses and compares them to the jackpot number in a loop
- Provides feedback telling the user if their guess is too high, too low, or correct
- Increments a counter for each guess attempt until the correct number is guessed
- Prints the total number of attempts when the user finally guesses correctly
Output
Example 21
Explanation
- This code uses a for loop to iterate through numbers from 1 to 10
- The
range(1,11)function generates a sequence of integers starting at 1 and ending before 11 - The
print()function outputs each number on a separate line - The loop executes 10 times, once for each number in the range
- Expected output is the numbers 1 through 10 printed vertically, each on its own line
Output
Example 22
Explanation
- Loops through numbers starting at 1, ending before 11, with step size of 2
- Prints each number in the sequence: 1, 3, 5, 7, 9
- Uses range() function with three parameters: start=1, stop=11, step=2
- Creates an odd-numbered sequence from 1 to 9 inclusive
- Outputs one number per line to console
Output
Example 23
Explanation
- Loop iterates through numbers starting at 1, ending before 11, with step size of 4
- Range function generates sequence: 1, 5, 9
- Print statement outputs each number on a separate line
- Key APIs used: range() with three arguments (start, stop, step) and print()
- Expected output shows numbers 1, 5, and 9 printed vertically
Output
Example 24
Explanation
- This code creates a countdown from 10 to 1 by iterating through a range in reverse order
- The
range(10,0,-1)function generates numbers starting at 10, ending before 0, with a step of -1 (decrementing) - The
print()function outputs each number on a new line as the loop progresses - Key APIs used are
range()for generating the sequence andprint()for displaying output - Expected output is the numbers 10 through 1 printed vertically, each on its own line
Output
Example 25
Explanation
- Loops through each character in the string 'Delhi' one by one
- Prints each individual character on a separate line
- Uses Python's for loop syntax with a string as the iterable
- Characters printed are: D, e, l, h, i (one per line)
- No return value or side effects beyond printing to console
Output
Example 26
Explanation
- Loops through each number in the list [1,2,3,4,5,6,7,8,9,10] and prints each number on a separate line
- Uses a for loop with the range function implicitly through the list literal
- Prints numbers 1 through 10 in sequential order, one per line
- The variable
itakes on each value from the list during each iteration - Output shows each integer from 1 to 10 displayed vertically in the console
Output
Example 27
Explanation
- Code iterates through dictionary keys using for loop
- Uses built-in
print()function to display each key on separate lines - Dictionary
{'name':'Madhu', 'age':30}has two keys: 'name' and 'age' - Loop prints only the keys, not the values, since iterating over dict yields keys by default
- Output shows: name (on first line) and age (on second line)
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.
Example 28
Explanation
- Code prints countdown from 10 to 1 along with current population value, then reduces population by 10% each iteration
- Uses
range(10,0,-1)to generate descending sequence from 10 down to 1 - Applies division by 1.1 to simulate 10% population decrease in each loop iteration
- Prints two values per line: the countdown number and current population amount
- Population value gets updated each time through loop, creating exponential decay effect
Output
Sequence Sum
1/1! + 2/2! + 3/3!
Example 29
Explanation
- Takes user input to get a number n and calculates a mathematical series sum
- Uses a loop to compute factorial of each number from 1 to n and accumulates the sum of i divided by i!
- The fact variable stores running factorial values to avoid recalculating from scratch each iteration
- Prints the final accumulated result which represents the sum 1/1! + 2/2! + 3/3! + ... + n/n!
- Side effect is displaying the computed sum to console output
Output
Nested Loops
Example 30
Explanation
- This code uses nested loops to generate all combinations of two numbers from 1 to 4
- The outer loop variable
iiterates from 1 to 4 (inclusive) - The inner loop variable
jalso iterates from 1 to 4 (inclusive) for each value ofi print(i,j)outputs each pair of numbers on separate lines- Expected output shows all 16 combinations: (1,1), (1,2), (1,3), (1,4), (2,1), (2,2), etc.
Output
Pattern
*
**
***
Example 31
Explanation
- Takes user input for number of rows and creates a pattern of asterisks in increasing order
- Uses nested loops where outer loop controls row count and inner loop prints asterisks per row
- The
end=''parameter in print() prevents newline after each asterisk, creating horizontal patterns - Each row prints one more asterisk than previous row, forming a right triangle pattern
- Final output shows a pyramid of asterisks with user-specified height
Output
Example 32
Explanation
- Takes user input to determine how many rows of stars to print
- Uses a for loop to iterate from 1 up to the number of rows (inclusive)
- Prints increasing numbers of asterisk characters on each line (1 star on first line, 2 stars on second, etc.)
- The
input()function gets user text input and converts it to an integer - The
print()function displays the star pattern with each iteration adding one more star
Output
Pattern
1
121
12321
1234321
Example 33
Explanation
- Takes user input for number of rows and creates a pattern of numbers that increases then decreases
- Uses nested loops where outer loop controls row count, inner loops print ascending then descending numbers
- First inner loop prints numbers from 1 to current row number
- Second inner loop prints numbers from row number minus 1 down to 1
- Creates a symmetric number pattern like 1, 121, 12321 for each row
Output
Loop Control Statement
* Break
* Continue
* Pass
Example 34
Explanation
- Code uses a for loop to iterate through numbers 1 to 9
- When the variable i equals 5, the break statement immediately exits the loop
- Print statement only executes for values 1, 2, 3, and 4 before loop terminates
- Range function generates sequence from 1 up to (but not including) 10
- Output shows numbers 1, 2, 3, 4 printed vertically, then loop stops before reaching 5
Output
Example 35
Explanation
- Takes two integer inputs from user to define a range of numbers to check
- Uses nested loops to test each number in the range for primality by checking divisibility from 2 up to the number itself
- The inner loop breaks when a divisor is found, indicating the number is not prime
- When the inner loop completes without breaking (else clause executes), the number is printed as prime
- Prints all prime numbers within the specified range to the console
Output
Example 36
Explanation
- The code iterates through numbers 1 to 9 using a for loop.
- When the loop variable
iequals 5, thecontinuestatement skips the current iteration, preventing 5 from being printed. - The
print(i)function outputs the current value ofifor all iterations except wheniis 5. - The expected output will be the numbers 1, 2, 3, 4, 6, 7, 8, and 9, each printed on a new line.
Output
Example 37
Explanation
- The code iterates through numbers 1 to 9 using a for loop.
- When the loop variable
iequals 5, thepassstatement is executed, which does nothing and allows the loop to continue. - The
print(i)statement outputs the current value ofifor each iteration except wheniis 5. - The expected output is the numbers 1, 2, 3, 4, 6, 7, 8, and 9 printed on separate lines, skipping the number 5.
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%
Example 38
Explanation
- The code calculates the monthly in-hand salary based on the user's annual Cost to Company (CTC) input.
- It uses conditional statements (
if,elif,else) to determine the applicable salary percentage based on the CTC range. - The salary is calculated by multiplying the CTC by a specific percentage depending on the CTC bracket.
- The final monthly salary is printed, rounded to two decimal places, by dividing the annual salary by 12.
- Expected output is a message displaying the calculated monthly salary based on the input CTC.
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.
Example 39
Explanation
- The code checks if three angles can form a valid triangle based on user input.
- It uses the
input()function to collect three angles and converts them to integers withint(). - The condition checks if the sum of the angles equals 180 and if all angles are positive.
- If the conditions are met, it prints "forms a triangle"; otherwise, it prints "doesnt form a triangle".
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.
Example 40
Explanation
- Prompts the user to input cost price and selling price, converting them to integers.
- Compares the cost price and selling price to determine if there is a profit, loss, or no gain/loss.
- Uses conditional statements (
if,elif,else) to evaluate the relationship between the two prices. - Outputs 'Profit' if selling price is higher, 'Loss' if lower, and 'No Loss No Gain' if they are equal.
Output
Problem 4: Write a menu-driven program -
- cm to ft
- km to miles
- USD to INR
- exit
Example 41
Explanation
- The code presents a menu for the user to convert between centimeters to feet, kilometers to miles, or USD to INR.
- It uses the
input()function to gather user choices and values for conversion. - Based on the user's selection, it performs the appropriate conversion using simple arithmetic operations.
- The conversions are printed to the console, displaying the results for the selected option.
- If the user selects '4' or any invalid option, the program exits without performing any conversion.
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
Example 42
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, printing the current value ofnum1in each iteration. - Calculates the next Fibonacci number by adding
num1andnum2, then updatesnum1andnum2for the next iteration. - The expected output is the first 10 numbers of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
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:
Example 43
Explanation
- Prompts the user to enter a number and converts the input to an integer.
- Initializes a variable
factto 1, which will hold the factorial result. - Uses a
forloop to iterate from 1 to the entered number, multiplyingfactby each integer in the range. - Calculates the factorial of the entered number and stores it in
fact. - Prints the final factorial value to the console.
Output
Problem 7 - Reverse a given integer number.
Example:
Input:
Output:
Example 44
Explanation
- Prompts the user to enter a number and converts it to an integer.
- Initializes a variable
revto store the reversed number. - Uses a
whileloop to extract the last digit of the number, append it torev, and remove the last digit fromnumber. - The loop continues until
numberbecomes 0, effectively reversing the digits. - Outputs the reversed number after the loop completes.
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:
Example 45
Explanation
- Takes user input to get a number N and initializes sum to 0
- Loops through numbers from 1 to N (inclusive) using range() function
- Skips numbers divisible by 5 using continue statement
- Adds remaining numbers to sum variable one by one
- Stops adding when sum exceeds 300, then subtracts the last added number and prints final sum value
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.
Example 46
Explanation
- Code repeatedly asks user to enter numbers until they input 0, collecting sum and count of entered numbers
- Uses
int(input())to get integer input from user andbreakstatement to exit loop when 0 is entered - Calculates and displays total sum of numbers and their average with 2 decimal places using
round()function - Variables
sumandcounttrack running total and number of inputs respectively - Output shows final sum and average of all non-zero numbers entered by user
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.
Example 47
Explanation
- Creates an empty list L to store numbers that meet specific criteria
- Loops through integers from 2000 to 3200 (inclusive) to find numbers divisible by 7 but not by 5
- Uses modulo operator (%) to check divisibility conditions and converts qualifying numbers to strings
- Appends matching numbers as strings to the list L for later formatting
- Prints all qualifying numbers separated by commas in a single line output
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.
Example 48
Explanation
- Creates an empty list L to store numbers with all even digits
- Iterates through numbers from 1000 to 3000 inclusive
- For each number, checks if all digits are even by:
- Extracting the last digit using modulo 10
- Checking if the digit is odd (remainder not 0 when divided by 2)
- If any odd digit found, sets flag to False and breaks
- Otherwise divides the number by 10 to check next digit
- Adds numbers with all even digits to list L as strings
- Prints all qualifying numbers separated by commas
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:
Example 49
Explanation
- Code tracks a robot's movement on a 2D grid starting at position [0,0] using user input commands
- Takes input in format "DIRECTION STEPS" like "UP 5" until user enters "!" to stop
- Updates robot's x,y coordinates based on direction commands (UP/DOWN change y-axis, LEFT/RIGHT change x-axis)
- Calculates and prints Euclidean distance from origin using Pythagorean theorem ((x² + y²)⁰·⁵)
- Uses basic Python functions like split(), int(), input(), and print() with while loop for continuous input processing
Output
###Problem 12:Write a program to print whether a given number is a prime number or not
Example 50
Explanation
- Checks if a number entered by user is prime or not using trial division method
- Uses
int(input())to read integer input from user and stores it in variablenum - Employs a for loop with
range(2, num)to test divisibility from 2 up to num-1 - Sets boolean flag to False when any divisor is found, breaking out of loop early
- Prints 'Prime' if no divisors found, otherwise 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.
Example 51
Explanation
- This code cell is currently empty and contains no executable code
- There are no functions, APIs, or operations defined to perform any specific task
- Since there's no code present, no output or side effects can occur when executed
- The cell would simply return without performing any actions in a Python environment
- This appears to be a placeholder or empty code cell waiting for implementation
###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.
Example 52
Explanation
- This code cell is currently empty and contains no executable code
- There are no functions, APIs, or operations defined to perform any specific task
- Since there's no code present, no output or side effects can occur when executed
- The cell would simply return without performing any actions in a Python environment
- This appears to be a placeholder or empty code cell waiting for implementation
###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.
Example 53
Explanation
- This code cell is currently empty and contains no executable code
- There are no functions, APIs, or operations defined to perform any specific task
- Since there's no code present, no output or side effects can occur when executed
- The cell would simply return without performing any actions in a Python environment
- This appears to be a placeholder or empty code cell waiting for implementation

