If Statements

Conditional execution with if, elif, else

Interview Relevant: Basic control flow

If Statements

Control program flow based on conditions.

Code Examples

Conditional statements in Python.

python
1# Basic if
2if x > 0:
3    print("Positive")
4
5# if-else
6if x > 0:
7    print("Positive")
8else:
9    print("Non-positive")
10
11# if-elif-else
12if x > 0:
13    print("Positive")
14elif x < 0:
15    print("Negative")
16else:
17    print("Zero")
18
19# Ternary operator
20result = "Yes" if condition else "No"
21
22# Nested if
23if x > 0:
24    if x < 10:
25        print("Single digit positive")
26
27# Multiple conditions
28if x > 0 and x < 10:
29    print("Between 0 and 10")

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In