Conditional statements
1. if
2. if..else
3. Nested if
4. if-elif statements.
1) If Statement
Syntax:-
if condition:
# Statements to execute if condition is true
Example
# if statement example
if 10 > 5:
print("10 greater than 5")
print("Program ended")
2) if else Statement
Syntax:-
if (condition):
# Executes this block if condition is true
else:
# Executes this block if condition is false
Example
# if..else statement example
x=3
if x == 4:
print("Yes")
else:
print("No")
3) Nested if..else
Syntax:-
if outer_condition:
# Code executed if outer_condition is True
if inner_condition:
# Code executed if both outer_condition and inner_condition are
True
print("Both conditions are true.")
else:
# Code executed if outer_condition is True but inner_condition is
False
print("Outer condition is true, inner is false.")
else:
# Code executed if outer_condition is False
print("Outer condition is false.")
Example
age = 25
is_student = True
if age >= 18:
print("Eligible to vote.")
if is_student:
print("You are also eligible for a student discount.")
else:
print("No student discount applies.")
else:
print("Not eligible to vote.")
4) if-elif
Syntax:-
if-elif Statement Syntax
if (condition):
statement
elif (condition):
statement
else:
statement
Examples:-
# Ask the user to enter a number
number = int(input("Enter a number: "))
# Check if the number is positive, negative, or zero
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Que1) a Write a program to check if a number is positive, negative, or zero.
# Get input from the user
num = float(input("Enter a number: "))
# Check the number
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
b Write a program to find the largest of three numbers.
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("The largest number is:", largest)
c Write a program to check if a number is even or odd.
num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, "is even.")
else:
print(num, "is odd.")
For Loop
Syntax:-
for variable in iterable:
# Code block to be executed for each item
Examples
for i in range(1, 6):
print(i)
Output:-
1
2
3
4
5
for i in range(6):
print(i)
Output:-
0
1
2
3
4
5
for i in range(0, 10, 2):
print(i)
Output:-
02468
string = "Hello World"
for x in string:
print(x)
Output
H
e
l
l
o
W
o
r
l
d
iterable: This is the sequence or collection that you want to iterate over.
Examples include:
Lists: [1, 2, 3]
Tuples: ('a', 'b', 'c')
Strings: "hello"
range() function: range(5) (generates numbers from 0 to 4)
The range() function is commonly used with for loops to generate a sequence
of numbers. It can take one, two, or three arguments:
range(stop): Generates numbers from 0 to stop-1.
range(start, stop): Generates numbers from start to stop-1.
range(start, stop, step): Generates numbers from start to stop-1,
incrementing by step.
For Loop for the Tuple
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output
apple
banana
cherry
For Loop for the List
or x in [11,12,13,14]:
print(x)
Output
11
12
13
14
While Loop
Syntax:-
while condition:
# Code block to execute repeatedly
# as long as the condition is True
Explanation:
The condition is evaluated before each iteration.
If the condition is True, the code inside the loop runs.
After running the code, it checks the condition again.
When the condition becomes False, the loop stops.
Example:
count = 1
while count <= 5:
print(count)
count += 1 # Increment to eventually end the loop
2 a Write a program to find the factorial of a number using a while loop.
num = int(input("Enter a non-negative integer: "))
if num < 0:
print("Factorial is not defined for negative
numbers.")
else:
factorial = 1
for i in range(1, num + 1):
factorial *= i # factorial = factorial * i
print(f"The factorial of {num} is {factorial}.")
b Write a program to print the first 10 natural numbers using a while
loop
num = 1
while num <= 10:
print(num)
num=num+1
C Write a program to print all even numbers between 1 and 50.
num = 2 # Start from the first even number greater than 1
while num <= 50:
print(num)
num += 2 # Increment by 2 to get the next even number
3 a Write a program to find the sum of all numbers in a given range
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
total_sum = 0
# Loop from start to end (inclusive)
for num in range(start, end + 1):
total_sum += num # total_sum = total_sum + num
print(f"The sum of all numbers from {start} to {end} is
{total_sum}")
b Write a program to check if a given year is a leap year.
# Input the year
year = int(input("Enter a year: "))
# Check leap year using a single condition
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
C Write a program to print the multiplication table of a given number.
# Input the number
num = int(input("Enter a number to print its multiplication
table: "))
# Loop from 1 to 10
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
4 A. Write a program to count the number of digits in a number.
# Input number from user
num = int(input("Enter a number: "))
# Initialize count variable
count = 0
# Make sure to handle zero separately because while loop
won't run for zero
if num == 0:
count = 1
else:
# Use absolute value to handle negative numbers
num = abs(num)
# Count digits by dividing the number by 10 until it becomes
0
while num > 0:
num = num // 10 # Integer division by 10 removes last
digit
count += 1
print("Number of digits:", count)
b Write a program to reverse a given number.
# Input number from user
num = int(input("Enter a number: "))
# Initialize variable to store reversed number
reversed_num = 0
# Use absolute value to handle negative numbers
temp = abs(num)
# Reverse the number
while temp > 0:
digit = temp % 10 # Get last digit
reversed_num = reversed_num * 10 + digit # Add digit to reversed
number
temp = temp // 10 # Remove last digit
# If original number was negative, make reversed number negative
if num < 0:
reversed_num = -reversed_num
print("Reversed number:", reversed_num)
c. Write a program to check if a given number is a palindrome.
# Input number from user
num = int(input("Enter a number: "))
# Store the original number to compare later
original_num = num
# Initialize variable to store reversed number
reversed_num = 0
# Use absolute value to handle negative numbers
temp = abs(num)
# Reverse the number
while temp > 0:
digit = temp % 10
reversed_num = reversed_num * 10 + digit
temp = temp // 10
# If original number was negative, reversed number should also
be negative
if num < 0:
reversed_num = -reversed_num
# Check if original number and reversed number are the same
if num == reversed_num:
print(num, "is a palindrome.")
else:
print(num, "is not a palindrome.")
5 A Write a program to find the sum of the digits of a number.
# Input number from user
num = int(input("Enter a number: "))
# Use absolute value to handle negative numbers
temp = abs(num)
# Initialize sum variable
digit_sum = 0
# Calculate sum of digits
while temp > 0:
digit = temp % 10
digit_sum += digit
temp = temp // 10
print("Sum of the digits:", digit_sum)
b Write a program to print all prime numbers between 1 and 100.
# Python program to display all the prime numbers within an
interval
lower = 900
upper = 1000
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
#################
for num in range(2, 101):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)
C Write a program to find the greatest common divisor (GCD) of two
a = 60 # first number
b = 110 # second number
while a != b:
if a > b:
a -= b # subtract b from a if a is greater
else:
b -= a # subtract a from b if b is greater
print(b)
6 A Write a program to check if a given string is a palindrome.
text = input("Enter a string: ")
# Remove spaces and convert to lowercase
text = [Link](" ", "").lower()
is_palindrome = True
length = len(text)
for i in range(length // 2):
if text[i] != text[length - 1 - i]:
is_palindrome = False
break
if is_palindrome:
print("It's a palindrome!")
else:
print("It's not a palindrome.")
B)Write a program to print the Fibonacci series up to a given number of
terms.
# Get number of terms from the user
n = int(input("Enter the number of terms: "))
# First two terms
a, b = 0, 1
count = 0
print("Fibonacci series:")
while count < n:
print(a)
a, b = b, a + b
count += 1
c) Write a program to count the number of vowels in a given string.
# Get input from the user
text = input("Enter a string: ")
# Define vowels
vowels = "aeiouAEIOU"
# Initialize count
count = 0
# Loop through each character in the string
for char in text:
if char in vowels:
count += 1
# Print the result
print("Number of vowels:", count)
7 A) Write a program to find the sum of all even numbers in a given list.
# Example list (you can change or get input from user)
numbers = [10, 15, 20, 25, 30]
# Initialize sum
even_sum = 0
# Loop through the list
for num in numbers:
if num % 2 == 0:
even_sum += num
# Print the result
print("Sum of even numbers:", even_sum)
B) Write a program to check if a given number is a perfect number
num = int(input("Enter a number: "))
total = 0
for i in range(1, num):
if num % i == 0:
total += i
if total == num:
print("It is a perfect number.")
else:
print("It is not a perfect number.")
8 A) Write a python program to accept any no. and find the count of
even, odd & zero digits within that number.
# Get input from the user
number = input("Enter a number: ")
# Initialize counters
even_count = 0
odd_count = 0
zero_count = 0
# Loop through each character in the input
for i in number:
if [Link]():
i = int(i)
if i == 0:
zero_count += 1
elif i % 2 == 0:
even_count += 1
else:
odd_count += 1
# Print the results
print("Even digits:", even_count)
print("Odd digits:", odd_count)
print("Zero digits:", zero_count)
b) Write a python program to accept a number and find the sum of
1st and last digit of that number.
# Get input from the user as a string
number = input("Enter a number: ")
# Extract first and last digit
first_digit = int(number[0])
last_digit = int(number[-1])
# Calculate the sum
sum_digits = first_digit + last_digit
# Print the result
print("Sum of first and last digit:", sum_digits)
9 a) Write a python program to calculate the length of string without
using inbuilt function.
string = input("Enter a string: ")
count = 0
for char in string:
count += 1
print("Length of the string is:", count)
b) Write a python program to copy one string into another string.
original = input("Enter a string: ")
# Copying character by character
copy = ""
for char in original:
copy += char
# Output
print("Original string:", original)
print("Copied string: ", copy)
10) Write a Python program to add 'ing' at the end of a given string (length
should be at least 3). If the given string already ends with 'ing' then add 'ly'
instead. If the string length of the given string is less than 3, leave it
unchanged.
Sample Input: 'run'
Expected Output: 'runing'
Sample Input: : 'string'
Expected Output: : 'stringly'
word = input("Enter a word: ")
# Check length
if len(word) < 3:
result = word
elif [Link]("ing"):
result = word + "ly"
else:
result = word + "ing"
# Print result
print("Result:", result)