Indentation and If Statements
Indentation and If Statements
UNIT II
Syntax in Python
Python is case-sensitive
Keywords are reserved words in Python that have special meanings and cannot be
used as variable names, function names, or any other identifiers.
Indenting
Indentation in Python
In some programming languages use braces {} or keywords like end in other languages.
Consistent Indentation:
All lines within a block must have the same level of indentation.
Mixing spaces and tabs in the same file is not allowed.
Example with Consistent Indentation:
num = 10
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Output:
10 is even
V SURESH KUMAR, HEAD & AP, SVASC
Standard Indentation:
Mandatory Indentation:
Python requires indentation to mark blocks of code, such as in if, for, while, def, and class.
Example:
BRANCHING (IF)
STATEMENTS AND EXPRESSIONS
1. If Statement
If statements are used for decision-making.
They allow you to execute a block of code conditionally, based on whether a given
condition is True or False.
If the condition is True, the block of code that is present inside the if statement is executed
"if statement" is written by using the if keyword.
Diagram
V SURESH KUMAR, HEAD & AP, SVASC
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
Explanation:
In this example we use two variables, a and b,
If statement test whether b is greater than a.
2. if-else Statement
if…else statement is also used for decision-making based on specific conditions.
If the condition is true, True block will be executed otherwise false block will be executed
Diagram
Example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Explanation:
In this example we use one variables, x
If statement test whether x is greater than 5 or not.
V SURESH KUMAR, HEAD & AP, SVASC
3. if-elif-else Statement
if-elif-else statement is also used for decision-making based on specific conditions
The else statement executed when no matches found
Diagram
Example:
x=7
if x == 10:
print("x is greater than 10")
elif x == 7:
print("x is equal to 7")
else:
print("x is less than or equal to 10 but not equal to 7")
Explanation:
In this example we use one variables, x
If statement test whether x is equal to 7 or not.
The if condition false, then elif condition is true