Conditional statement
By Aryan kumar
Python supports the usual logical conditions
from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Eample
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif
The elif keyword is Python's way of saying "if
the previous conditions were not true, then
try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which
isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If
If you have only one statement to execute,
you can put it on the same line as the if
statement.
One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute,
one for if, and one for else, you can put it all
on the same line:
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
And
The and keyword is a logical operator, and is
used to combine conditional statements:
Test if a is greater than b, AND if c is greater
than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is
used to combine conditional statements:
Test if a is greater than b, OR if a is greater
than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is
used to reverse the result of the conditional
statement:
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements
inside if statements, this is
called nested if statements
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Example Flowchart for an if-else Structure:
Start
Input x
Is x > 0?
Yes → Print "Positive"
No → Print "Negative"
End
Sort Three Numbers
a, b, c = 3, 1, 2
if a > b:
a, b = b, a # Swap a and b
if a > c:
a, c = c, a # Swap a and c
if b > c:
b, c = c, b # Swap b and c
print("Sorted order:", a, b, c)
Check Divisibility of a Number
number = 20
divisor = 5
if number % divisor == 0:
print(f"{number} is divisible by {divisor}")
else:
print(f"{number} is not divisible by
{divisor}")
For Loop
The for loop in Python is commonly used with
sequences like lists, strings, or ranges.
for i in range(5): # range(5) generates
numbers 0, 1, 2, 3, 4
print(i)
Using range() Function
The range() function generates a sequence of
numbers.
range(stop): Generates numbers from 0 to
stop - 1.
range(start, stop): Generates numbers from
start to stop - 1.
range(start, stop, step): Generates numbers
from start to stop - 1, with increments of step.
for i in range(1, 10, 2): # Generates 1, 3, 5, 7,
9
print(i)
While Loop
The while loop continues to execute as long
as a given condition is True.
i=0
while i < 5:
print(i)
i += 1 # Increment i
Break and Continue Statements
break: Exits the loop immediately.
continue: Skips the current iteration and moves to the
next one.
for i in range(10):
if i == 5:
break # Stop the loop when i is 5
print(i)
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
Nested Loops
You can nest a loop within another loop. This
is often used for multidimensional data or
patterns.
for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(f"i = {i}, j = {j}")
Generating a Pattern
n = 5
for i in range(1, n + 1):
print("*" * i)
output
*
**
***
****
*****
Finding Factorial of a Positive Number
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")
ERRORS
Errors in programming can be grouped into
three primary types: syntax errors, logical
errors, and run-time errors. Each type
impacts the code differently and requires
different approaches for debugging. Here’s a
breakdown of each:
Syntax Errors
Definition: Syntax errors occur when the code
violates the rules of the programming language.
These errors are typically related to incorrect
structure or grammar in the
[Link]:Missing punctuation (like
semicolons or commas in some languages).
Misspelled keywords or incorrect function names.
Unbalanced parentheses or brackets.
Detection: Syntax errors are usually caught by the
compiler or interpreter before the program runs. It
will indicate the line and type of syntax issue.
print("Hello World" # Missing closing parenthesis
Logical Errors
Definition: Logical errors occur when the program runs but doesn’t
behave as expected. This is because of mistakes in the logic that
determine how the program should [Link]:Using an
incorrect formula for calculations.
Setting a loop condition incorrectly.
Writing conditional statements that don’t cover all necessary cases.
Detection: Logical errors can be difficult to catch because they
don’t cause the program to crash. Instead, the program simply
produces incorrect or unintended results. Testing and debugging are
essential to find these errors.
# Suppose this code is supposed to calculate the area of a rectangle
length = 5
width = 10
area = length + width # Should be length * width, not length +
width
Run-time Errors
Definition: Run-time errors occur while the program is running.
These errors happen due to issues that only arise during execution,
often due to unforeseen conditions in the input or
[Link]:Dividing by zero.
Accessing elements out of the bounds of an array.
Trying to open a file that doesn’t exist.
Detection: Run-time errors cause the program to halt
unexpectedly and are typically accompanied by an error message
that identifies the line and type of issue
# Attempting to divide by zero
numerator = 10
denominator = 0
result = numerator / denominator # Will raise a ZeroDivisionError
.