Python Programs (Loops, Conditional
Statements and Strings)
Loops
1.For Loop
# Program to print squares of numbers from 1 to 10
# and also identify even or odd numbers
# and calculate total sum of squares
total_sum = 0 # to store the sum of all squares
for num in range(1, 11):
square = num ** 2
print(f"Square of {num} is {square}")
if num % 2 == 0:
print(f"{num} is an Even number.")
else:
print(f"{num} is an Odd number.")
total_sum += square # add square to total sum
print("-" * 30) # separator for readability
print(f"Total sum of squares from 1 to 10 is {total_sum}")
Output – Run the code on online gdb compiler and write the output on
your notebooks
Code Explanation
• This program loops from 1 to 10 using a for loop.
• It calculates the square of each number.
• It checks if the number is even or odd using an if-else statement.
• It prints appropriate messages.
• It adds the square to a running total.
• Finally, it prints the total sum of all squares
2. While Loop
# Program to count and print multiples of 5 from 1 to 50 using while loop
num = 1
count = 0
print("Multiples of 5 between 1 and 50:")
while num <= 50:
if num % 5 == 0:
print(num)
count += 1
num += 1
print("-" * 30)
print("Total multiples of 5 found:", count)
Output – Run the code on online gdb compiler and write the output on
your notebooks
Explanation
• The program uses a while loop to iterate from 1 to 50.
• It checks if a number is a multiple of 5.
• If it is, it prints the number and keeps a count of how many such
numbers are found.
• Finally, it displays the total count of multiples of 5.
3. Do-While Loop.
# Simulating do-while loop: Password checker
correct_password = "admin123"
while True:
user_input = input("Enter your password: ")
if user_input == correct_password:
print(" Access Granted!")
break
else:
print(" Incorrect password. Try again.")
print("Waiting for correct password...")
print("-" * 40)
Output – Run the code on online gdb compiler and write the output on
your notebooks
Explanation
• This program simulates a do-while loop where the user is asked to
enter a password.
• It keeps asking until the correct password is entered (ensures at least
one execution).
• The loop breaks only when the correct password ("admin123") is
given.
• Simulates a real-world application like login systems.
Conditional Statements
1. Python Program using 'if' Statement
Explanation:
This program checks whether a given number is positive. We use an 'if'
condition to verify if the number is greater than 0. If it is, we display a
message indicating it's positive.
Code
# Check if a number is positive
num = int(input("Enter a number: "))
if num > 0:
print("You entered a positive number.")
print("This number is greater than zero.")
print("Positive numbers are used in many applications.")
print("For example, distance, money, etc.")
print("This is a simple 'if' condition demonstration.")
print("Program completed.")
Output – Run the code on online gdb compiler and write the output on
your notebooks
2. Python Program using 'if-else' Statement
Explanation:
This program checks whether a number is even or odd using 'if-else'. It
divides the number by 2 and uses the modulus operator to check the
remainder. If the remainder is zero, it’s even; otherwise, it’s odd.
Code:
# Check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is Even.")
print("Even numbers are divisible by 2.")
print("Examples: 2, 4, 6, etc.")
else:
print("The number is Odd.")
print("Odd numbers are not divisible by 2.")
print("Examples: 1, 3, 5, etc.")
print("This is an 'if-else' demonstration.")
Output – Run the code on online gdb compiler and write the output on
your notebooks
3. Python Program using 'if-elif-else' Ladder
Explanation:
This program assigns grades to students based on their marks using an if-
elif-else ladder. Each condition checks if the marks fall into a certain range.
This allows for multiple conditions to be checked sequentially.
Code:
# Assign grade based on marks
marks = int(input("Enter your marks (0-100): "))
if marks >= 90:
print("Grade: A (Excellent)")
elif marks >= 75:
print("Grade: B (Very Good)")
elif marks >= 60:
print("Grade: C (Good)")
elif marks >= 40:
print("Grade: D (Needs Improvement)")
else:
print("Grade: F (Fail)")
print("Grading done using if-elif-else ladder.")
Output – Run the code on online gdb compiler and write the output on
your notebooks
4. Python Program using Nested 'if' Statement
Explanation:
This program checks if a user is eligible to vote and further categorizes
them. A nested 'if' is used inside the main 'if' block to add more conditions,
like whether the person is a senior citizen or an adult.
Code:
# Voting eligibility check with age category
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
if age >= 60:
print("You are also a senior citizen voter.")
else:
print("You are an adult voter.")
print("Make sure to carry your ID while voting.")
else:
print("You are not eligible to vote yet.")
print("Program demonstrates nested if.")
Output – Run the code on online gdb compiler and write the output on
your notebooks
5. Python Equivalent of Switch Statement using match-
case
Explanation:
This program uses the 'match-case' structure to mimic a switch statement.
The user enters a number and the program returns the corresponding day
of the week. It uses Python's pattern matching (introduced in Python 3.10).
Code:
# Day of the week using match-case
day = int(input("Enter day number (1-7): "))
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Invalid day number!")
print("Switch-case simulated using match-case.")
Output – Run the code on online gdb compiler and write the output on
your notebooks
Strings in Python
Explanation
This program takes a sentence as input and performs various string
operations:
• Changes to uppercase, lowercase, and title case
• Counts a specific character
• Replaces a word with another
• Shows the length of the string
• Displays the first and last words using slicing
• Checks whether a keyword exists in the sentence using in
Code
# Python program to demonstrate string operations
# Input from user
sentence = input("Enter a sentence: ")
# Convert to uppercase, lowercase, and title case
print("Uppercase:", sentence.upper())
print("Lowercase:", sentence.lower())
print("Title Case:", sentence.title())
# Count how many times 'a' appears
print("Count of 'a':", sentence.count('a'))
# Replace a word
new_sentence = sentence.replace("Python", "Java")
print("After replacement:", new_sentence)
# Length of string
print("Length of sentence:", len(sentence))
# Print first and last word using split
words = sentence.split()
if len(words) >= 2:
print("First word:", words[0])
print("Last word:", words[-1])
else:
print("Not enough words to show first and last.")
# Check for a keyword
if "exam" in sentence.lower():
print("The sentence talks about an exam.")
else:
print("No mention of an exam.")
Output – Run the code on online gdb compiler and write the output on
your notebooks
Concepts Covered:
input() for user input
.upper(), .lower(), .title() – string case conversion
.count() – count occurrences
.replace() – replace substrings
len() – length of string
.split() – breaking sentence into words
in – membership test