Exp 4 and 5
Exp 4 and 5
Exercise:
if num % 2 == 0:
print("Even")
else:
print("Odd")
if num < 0:
num = -num
if a > b:
if a > c:
print("Largest number is:", a)
else:
print("Largest number is:", c)
else:
if b > c:
print("Largest number is:", b)
else:
print("Largest number is:", c)
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap Year")
else:
print("Not a Leap Year")
else:
print("Leap Year")
else:
print("Not a Leap Year")
5. Check if a Number is Positive, Negative, or Zero (if ... elif ... else)
num = float(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
6. Calculate Grade Based on Marks of 5 Subjects (if ... elif ... else)
marks = []
for i in range(5):
marks.append(float(input(f"Enter marks for subject {i+1}: ")))
average = sum(marks) / 5
print("Grade:", grade)
PRQ:
A. Comparison Operators
== Equal to a == b → False
B. Logical Operators
and Returns True if both conditions are True (x > 0 and y > 0) →
True
Definition Used when there are only two Used when an if statement is placed
possible outcomes (True or inside another if statement for more
False). complex conditions.
Readability Easier to read and understand. Can be harder to read if too many levels of
nesting are used.
Use Case Best for simple decision-making. Best for situations where one condition
depends on another condition.
Exp 5
Exercise:
*
**
***
****
Output:
*
**
***
****
***
**
*
Output:
1010101
10101
101
1
Output:
2 4 6 8 10 ... 100
Output:
Output:
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
5. Calculate Factorial of a Number (Using while Loop)
num = int(input("Enter a number: "))
factorial = 1
i=1
while i <= num:
factorial *= i
i += 1
print(f"Factorial of {num} is {factorial}")
Input: 5
Output: Factorial of 5 is 120
Input: 1234
Output: 4321
Input: 1234
Output: 10
8. Check if a Number is a Palindrome (Using while Loop)
num = int(input("Enter a number: "))
original = num
rev = 0
while num > 0:
rev = rev * 10 + num % 10
num //= 10
if original == rev:
print("Palindrome")
else:
print("Not a Palindrome")
Input: 121
Output: Palindrome
Input: 123
Output: Not a Palindrome
PRQ:
Code:
x = 10
while x > 5:
print(x, end=" ")
x -= 1
Expected Output:
10 9 8 7 6
Explanation:
Expected Output:
123456789
Explanation: