Python Conditional Statements(if, elif, else)
Python Conditional Statements(if, elif, else)
.png)
Introduction
In real life, we take decision every day like if rain then take an umbrella, if phone battery is low then charge it, etc. Similarly, in python, conditional statement are used for decision making.
In this blog, you'll learn:
Conditional statements allow a program to perform different action based on whether a certain condition is true or false. Suppose if we have to find the given number is divisible from 2 or not.
Python mainly uses :
- if
- elif
- else
Let's take above example:
Code:
#find numbers divisible by two and which are not.
b=13
if b%2==0:
print("b is divisible by 2")
else:
print("b is not divisible by 2")
Output:
b is not divisible by 2
The if Statement
The if statement runs code only when the condition is true. if statement can not be written without condition.
Example:
#using age find eligible to vote.
age=18
if age>=18:
print("You are eligible to vote")
Output:
You are eligible to vote
Try, what if age is 15?
The else Statement
The else statement runs code when all statement turn out to be false. else statement do not contain any condition statement. You can write if statement alone but else alone is not allowed in programming.
Example:
#using age find eligible to vote or not.
age=12
if age>=18
print("You are eligible to vote")
else:
print("You are not eligible to vote")
Output:
You are not eligible to vote
The elif Statement
Used when their are multiple conditions.
Example:
#using age to find eligible to vote or not.
age=-20
if age>=18
print("You are eligible to vote")
elif age<18:
print("You are not eligible to vote")
else:
print("value is invalid")
Output:
value is invalid
Real Life Example: Login System
Code:
username="admin"
password= "1234"
if username == "admin" and password =="1234":
print("Login successful")
else:
print("Invalid username or Password")
Practice Questions
- Check whether a number is positive or negative.
- Check if a number is even or odd.
- Find the greatest of two numbers.
- Check whether a student passed(marks>=35)
- Create a simple login syatem
Conclusion
- Conditional statements help programs make decisions
- if checks condition
- elif checks another condition
- else runs when all conditions fails
Comments
Post a Comment