Skip to content
Cover image for: Python Operators & Control Flow Guide
#pythonBeginner

Python Operators & Control Flow Guide

Apr 24, 2026
Updated May 14, 2026
30 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: python-operators-control-flow-guide

Learn all Python operators — arithmetic, comparison, logical, bitwise, membership, and identity — plus complete control flow mastery with if-elif-else chains, for loops, while loops, nested conditionals, and loop control statements (break, continue, pass). Includes practical programming examples like building a Fibonacci sequence generator, a four-function calculator, a prime number checker, and a countdown timer with step-by-step code explanations.

Quick Summary

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.

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
python

Output

text

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
python

Output

text

Understanding Python's logical operators AND, OR, and NOT with boolean operations

Explanation

  • The and operator 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 or operator 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 not operator 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 0 returns 0, 1 or 0 returns 1, and not 0 returns True
python

Output

text

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
python

Output

text

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 variable a and updates it, resulting in 4.
  • The *= operator multiplies the current value of a (2) by 2, updating it to 4.
  • The /= operator divides the current value of a (2) by 2, resulting in 1.0 (float).
  • The //= operator performs floor division on a (2) by 2, updating it to 1.
  • The %= operator calculates the modulus of a (2) by 2, resulting in 0.
python

Output

text

Demonstrating the usage of membership operators in Python for checking element presence

Explanation

  • The code uses the in and not in membership 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 True for 'D' and False for 'A'.
  • The third print statement checks if the integer 1 is in the list [1, 2, 3, 4], which returns True.
  • The fourth print statement verifies if the key 'name' exists in a dictionary, returning True since '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 False as 'Madhu' is not a key.
python

Output

text

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.
python

Output

text

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
python

Output

text

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.
python

Output

text

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.
python

Output

text

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
python

Output

text

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
python

Output

text

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
python

Output

text

Retrieve the list of reserved keywords in Python programming language

Explanation

  • The import keyword statement imports the keyword module, which provides functions related to Python's keywords.
  • The keyword.kwlist attribute 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.
python

Output

text

Generate a random integer between 1 and 100 using Python's random module

Explanation

  • The code imports the random module, which provides functions for generating random numbers.
  • It uses the randint function to generate a random integer within a specified range, inclusive of both endpoints.
  • The print function 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.
python

Output

text

Retrieve and display the current date and time using Python's datetime module

Explanation

  • The code imports the datetime module, which provides classes for manipulating dates and times.
  • It calls the now() method from the datetime class 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.
python

Output

text

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' to help(), 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.
python

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 i is initialized to 1, which will be used to iterate through the numbers 1 to 10.
  • A while loop runs as long as i is less than 11, printing the multiplication result of number and i in a formatted string.
  • After each iteration, i is incremented by 1 to progress through the multiplication table.
  • The output displays the multiplication results in the format "number * i = result".
python

Output

text

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 x with a value of 1.
  • The while loop continues to execute as long as x is less than 3, printing the current value of x and incrementing it by 1 in each iteration.
  • Once x reaches 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).
python

Output

text

A simple number guessing game that provides feedback on user guesses until the correct number is found.

Explanation

  • The code imports the random module 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 while loop 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.
python

Output

text

This code snippet demonstrates how to use a for loop to print numbers from 1 to 10.

Explanation

  • The for loop iterates over a sequence generated by range(1, 11), which produces numbers from 1 to 10.
  • The variable i takes on each value in the range during each iteration of the loop.
  • The print(i) statement outputs the current value of i to the console.
  • This loop will execute a total of 10 times, displaying each number on a new line.
python

Output

text

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 of i during each iteration.
  • As a result, the output will be the odd numbers: 1, 3, 5, 7, and 9.
python

Output

text

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 of i to the console during each iteration of the loop.
  • This approach is useful for generating sequences where a specific interval is required between numbers.
python

Output

text

This code snippet counts down from 10 to 1 and prints each number.

Explanation

  • The for loop 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.
python

Output

text

This code iterates through each character in the string 'Delhi' and prints them individually.

Explanation

  • The for loop iterates over each character in the string 'Delhi'.
  • The variable i takes 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.
python

Output

text

This code snippet iterates through a list of numbers and prints each one sequentially.

Explanation

  • The code uses a for loop 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.
python

Output

text

Iterating through a dictionary to print its keys in Python

Explanation

  • The code uses a for loop to iterate over a dictionary containing two key-value pairs: 'name' and 'age'.
  • During each iteration, the variable i takes 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.
python

Output

text

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_pop with 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.
python

Output

text

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, result and fact, are initialized to 0 and 1 respectively; result will hold the final sum, while fact will be used to compute factorial values.
  • A for loop iterates from 1 to n, calculating the factorial of each number and updating result by adding the fraction of the current index i over its factorial fact.
  • After the loop completes, the final computed value of result is printed, representing the sum of the series.
python

Output

text

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 i and j, 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.
python

Output

text

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.
python

Output

text

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 for loop 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.
python

Output

text

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.
python

Output

text

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 i equals 5, the break statement is triggered.
  • The break statement 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.
python

Output

text

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
python

Output

text

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
python

Output

text

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
python

Output

text

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
python

Output

text

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.
python

Output

text

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.
python

Output

text

Problem 4: Write a menu-driven program -

  1. cm to ft
  2. km to miles
  3. USD to INR
  4. 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 float ensures that the input values can be decimal numbers, allowing for more precise conversions.
python

Output

text

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, num1 and num2, to represent the first two numbers in the Fibonacci sequence (0 and 1).
  • Uses a for loop 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 num1 and num2, then updates num1 and num2 for the next iteration.
  • The loop effectively builds the sequence by shifting the values of num1 and num2 forward.
python

Output

text

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

bash

Output:

bash

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 fact is initialized to 1 to hold the result of the factorial calculation.
  • A for loop iterates from 1 to the entered number (inclusive), multiplying fact by each integer in this range.
  • Finally, the computed factorial is printed to the console.
python

Output

text

Problem 7 - Reverse a given integer number.

Example:

Input:

bash

Output:

bash

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.
python

Output

text

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:

bash

Output:

bash

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 N that are not multiples of five and do not cause the sum to exceed 300.
python

Output

text

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, sum and count, 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 sum and increments count for each valid input.
  • After exiting the loop, it prints the total sum and the average of the numbers, rounded to two decimal places.
python

Output

text

###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 L to 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 L as a comma-separated string.
python

Output

text

###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 L to store numbers with only even digits.
  • Iterates through each number i from 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 False and 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.
python

Output

text

###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:

text

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:

text

Output:

text

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²).
python

Output

text

###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 flag is initialized to True, 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, flag is set to False, and the loop breaks.
  • Finally, the program prints "Prime" if flag remains True, otherwise it prints "Not Prime".
python

Output

text

###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 pandas library 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.
python

###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 pandas library 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.
python

###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 pandas library 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.
python

Next in this series: Python Strings: Methods, Formatting & f-Strings Guide →

Frequently Asked Questions

The addition operator (+) adds two numbers together, producing a sum, such as 11 from 5 and 6.
The modulus operator (%) returns the remainder after division, yielding 1 when dividing 5 by 2.
The bitwise AND operator (&) for 2 and 3 results in 2.
The += operator adds a specified value to the variable and updates it, such as adding 2 to a variable 'a' resulting in 4.
The 'in' membership operator checks if specific elements exist within data structures, such as verifying if 'D' is present in the string 'Delhi', which returns True.

How was this tutorial?