Conditional Statements in Python
Conditional Statements in Python
Conditional statements in Python allow for the execution of specific code blocks based on whether a given condition evaluates to True or False. This mechanism enables programs to make decisions and exhibit dynamic behavior.
The primary conditional statements in Python are:
1. if statement:
The if statement executes a block of code only if its associated condition is True.
Python
age = 25
if (age >= 18):
print("You are an adult.")
2. if-else statement:
The if-else statement provides an alternative block of code to execute when the if condition evaluates to False.
Python
temperature = 30
if (temperature > 25):
print("It's hot outside.")
else:
print("It's not too hot.")
3. if-elif-else ladder:
This structure allows for checking multiple conditions sequentially. The elif (else if) statement checks a new condition if the preceding if or elif conditions were False. The else block is executed if none of the preceding conditions are True.
Python
score = 85
if (score >= 90):
print("Grade A")
elif (score >= 80):
print("Grade B")
elif (score >= 70):
print("Grade C")
else:
print("Grade D or F")
Prog 1.
age = 20
if (age >= 18):
print("Eligible to vote.")
Output
Eligible to vote.
Prog 2.
age = 10
if (age <= 12):
print("Travel for free.")
else:
print("Pay for ticket.")
Output
Travel for free.
Prog 3.
age = 25
if (age <= 12):
print("Child.")
elif (age <= 19):
print("Teenager.")
elif (age <= 35):
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
Prog 4.
Largest of Three Numbers
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
c = int(input("Enter Third Number: "))
if (a >= b) and (a >= c):
print("First number is largest:", a)
elif (b >= c):
print("Second number is largest:", b)
else:
print("Third number is largest:", c)
Prog 5.
Check if Number is Multiple of 7
n = int(input("Enter Number: "))
if n % 7 == 0:
print("Multiple of 7")
else:
print("Not a multiple of 7")
Prog 6.
Check Fail and Pass Condition
Marks=int(input("Enter the marks"))
if(marks>=33):
print("Pass")
else:
print("Fail")
Prog 7.
Check Percent Marks Condition
marks=int(input("Enter the Marks")
if(marks>=65):
print("First")
elif(marks>=45):
print("Second")
elif(marks>=33):
print("third")
else:
print(Fail")
Prog 8.
Check Grade Condition
marks=int(input("Enter The marks:"))
if(marks>=85):
print("S Grade")
elif(marks>=75):
print("A+ Grade")
elif(marks>=65):
print("A Grade")
if(marks>=45):
print("B Grade")
if(marks>=33):
print("C Grade")
else:
print("Fail")

No comments: