CPROG 1 Control - Structures
CPROG 1 Control - Structures
CPROG 1 Control - Structures
Example:
print("Hello, World!")
x = 10
y=5
print("Sum:", x + y)
Syntax:
if condition:
# block of code
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
IF-ELSE STATEMENT
Provides an alternative block of code if the condition is false.
Syntax:
if condition:
# block of code if true
else:
# block of code if false
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
IF-ELIF-ELSE LADDER
Used when multiple conditions need to be checked.
Syntax:
if condition1:
# block of code
elif condition2:
# block of code
else:
# block of code
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
NESTED IF STATEMENTS
An if statement inside another if statement.
Syntax:
if condition1:
if condition2:
# block of code
Example:
num = 10
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
REPETITION CONTROL STRUCTURE
(LOOPS)
Repeats a block of code multiple times until a condition is met.
Types of Loops:
for loop
while loop
FOR LOOP
Iterates over a sequence (like a list, tuple, dictionary, set, or string).
Syntax:
for variable in sequence:
# block of code
Example:
for i in range(5):
print(i)
WHILE LOOP
Repeats a block of code as long as a condition is true.
Syntax:
while condition:
# block of code
Example:
count = 0
while count < 5:
print(count)
count += 1
NESTED LOOPS
A loop inside another loop.
Syntax:
for i in range(3):
for j in range(2):
# block of code
Example:
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
BREAK AND CONTINUE STATEMENTS
Break:
Exits the loop prematurely.
Example:
for i in range(5):
if i == 3:
break
print(i)
Continue:
Skips the rest of the loop's current iteration and moves to the next iteration.
Example:
for i in range(5):
if i == 3:
continue
print(i)
COMMON PITFALLS
Infinite Loops:
Ensure loop conditions eventually become false.
Off-by-One Errors:
Be cautious with loop boundaries.
Nested Loops Performance:
Avoid deep nesting to reduce complexity.
SUMMARY
Key Takeaways:
Online Resources:
Python
Documentation(https://docs.python.org/3/tutorial/controlflow.html)