Branching Statements in Python
Complete Tutorial with Examples and Output
1. Introduction to Branching
Branching is a programming technique used to make decisions in a program. It allows a program to execute different blocks of code depending on whether a condition is True or False.
In Python, branching is mainly performed using:
ifstatementif-elsestatementif-elif-elsestatement- Nested
ifstatements
Condition → False → Execute another block
2. if Statement
The if statement executes a block of code only when its condition
is True.
Syntax
if condition:
statement
Example
age = 20
if age >= 18:
print("You are an adult.")
Output
You are an adult.
3. When the if Condition is False
If the condition is False, Python skips the indented block.
age = 15
if age >= 18:
print("You are an adult.")
print("Program completed.")
Output
Program completed.
4. if-else Statement
The if-else statement provides two possible execution paths.
If the condition is True, the if block executes. Otherwise,
the else block executes.
Syntax
if condition:
statement1
else:
statement2
Example
number = 10
if number > 0:
print("Positive number")
else:
print("Not a positive number")
Output
Positive number
5. Practical Example – Even or Odd
The modulus operator % can be used to determine whether a number
is even or odd.
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
Sample Output
Enter a number: 24
Even number
6. Positive, Negative or Zero
When more than two possibilities exist, an if-elif-else structure
can be used.
number = int(input("Enter a number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
Sample Output
Enter a number: -8
Negative
7. if-elif-else Statement
The elif keyword means "else if". It is used when a program
needs to test multiple conditions.
Syntax
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
statement4
Example
marks = 75
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Output
Grade B
8. Practical Example – Student Grade
marks = int(input("Enter marks: "))
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
Sample Output
Enter marks: 85
Grade: A
9. Nested if Statement
A nested if statement means placing one if statement
inside another if statement.
Example
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Entry not allowed")
Output
Entry allowed
10. Branching Using Comparison Operators
Conditions commonly use comparison operators.
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater than or equal | a >= b |
<= |
Less than or equal | a <= b |
11. Branching Using Logical Operators
Logical operators allow multiple conditions to be combined.
and– both conditions must be Trueor– at least one condition must be Truenot– reverses the Boolean result
Example using and
age = 20
marks = 80
if age >= 18 and marks >= 50:
print("Eligible")
else:
print("Not eligible")
Output
Eligible
12. Using the or Operator
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Holiday")
else:
print("Working day")
Output
Holiday
13. Using the not Operator
logged_in = False
if not logged_in:
print("Please login first")
Output
Please login first
14. Practical Example – Find Largest of Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
print("Largest =", a)
elif b > a:
print("Largest =", b)
else:
print("Both numbers are equal")
Sample Output
Enter first number: 25
Enter second number: 40
Largest = 40
15. Practical Example – Largest of Three Numbers
a, b, c = map(int, input("Enter three numbers: ").split())
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Largest =", largest)
Sample Output
Enter three numbers: 25 60 40
Largest = 60
16. Practical Example – Leap Year
A year is a leap year when it is divisible by 400, or when it is divisible by 4 but not divisible by 100.
year = int(input("Enter year: "))
if year % 400 == 0:
print("Leap year")
elif year % 100 == 0:
print("Not a leap year")
elif year % 4 == 0:
print("Leap year")
else:
print("Not a leap year")
Sample Output
Enter year: 2024
Leap year
17. Practical Example – Voting Eligibility
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Sample Output
Enter your age: 20
You are eligible to vote.
18. Practical Example – Simple Login Check
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "1234":
print("Login successful")
else:
print("Invalid username or password")
Sample Output
Enter username: admin
Enter password: 1234
Login successful
19. Practical Example – Simple Calculator
Branching can be used to create a simple calculator by selecting an operation.
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
operator = input("Enter operator (+, -, *, /): ")
if operator == "+":
print("Result =", a + b)
elif operator == "-":
print("Result =", a - b)
elif operator == "*":
print("Result =", a * b)
elif operator == "/":
if b != 0:
print("Result =", a / b)
else:
print("Cannot divide by zero")
else:
print("Invalid operator")
Sample Output
Enter first number: 20
Enter second number: 5
Enter operator (+, -, *, /): *
Result = 100.0
20. Importance of Indentation
Python uses indentation to identify blocks of code. Statements belonging
to an if, elif, or else block must be
indented consistently.
Correct Example
age = 20
if age >= 18:
print("Adult")
Important
The statement print("Adult") is indented because it belongs to
the if block.
21. Conditional Expression
Python also provides a compact form of branching called a conditional expression.
Syntax
value_if_true if condition else value_if_false
Example
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
Output
Adult
22. Flow of Branching
Start
↓
Evaluate Condition
↓
True → Execute True Block
or
False → Execute False / Next Condition
↓
Continue Program
23. Common Errors in Branching
-
Forgetting the colon:
if age >= 18: - Incorrect indentation: Statements inside the branch must be properly indented.
-
Using = instead of ==:
=is assignment, while==checks equality. -
Incorrect condition order: In an
if-elifstructure, conditions should be arranged carefully.
24. Branching Statements Quick Reference
| Statement | Purpose |
|---|---|
if |
Execute code when a condition is True |
if-else |
Choose between two alternatives |
if-elif-else |
Choose among multiple alternatives |
Nested if |
Place one decision inside another |
| Conditional expression | Compact one-line decision |
25. Summary
Branching is an important part of Python programming because it allows a program to make decisions based on conditions.
The main branching structures are if, if-else,
if-elif-else, and nested if statements.
Comparison operators and logical operators are commonly used to construct
branching conditions.
Branching is used in many practical applications including student grading, login systems, voting eligibility, calculators, billing systems, validation, menu-driven programs and decision-making systems.
Created by Bijan Krishna Paul
Computer Science • Python Programming • Data Science
No comments:
Post a Comment