Control structures are fundamental constructs in programming that manage the flow of execution in a program. They allow the program to make decisions, execute certain sections of code based on conditions, and repeat operations multiple times. Essentially, control structures are the decision-making brains of a program that guide which instructions are executed, how many times, and under what conditions. They are indispensable for creating dynamic and responsive programs.

There are two fundamental structures we will look at:

Conditional Statements

Conditional statements are the parts of a program that help it make decisions. They work like a series of "if this then that" statements that control whether certain sections of code are executed or skipped, based on whether their conditions are true or false. Essentially, they allow your program to react differently to different situations, much like how you might decide to wear a coat if it's cold or sunglasses if it's sunny.

IF Statement

temperature = 30  # Let's say temperature is 30 degrees
if temperature > 25:
    print("It's a hot day!")

This code checks if the temperature is greater than 25. If true, it prints "It's a hot day!"

IF-ELSE Statement

temperature = 18
if temperature > 25:
    print("It's a hot day!")
else:
    print("It's not so hot today.")

This code provides an alternative action if the condition is not true. If the temperature is not greater than 25, it prints "It's not so hot today."

IF-ELSE-IF-ELSE Statement

temperature = 10
if temperature > 25:
    print("It's a hot day!")
elif temperature < 15:
    print("It's a cold day!")
else:
    print("It's a mild day.")

This code checks multiple conditions. It first checks if it's hot; if not, it checks if it's cold, and if neither condition is true, it concludes that it's a mild day.

Loops