Control statements are fundamental programming concepts that allow you to control the flow of execution in your programs. In Class 11, understanding these concepts is crucial as they form the basis for decision-making and iterative processes in coding. Here’s a breakdown of each:
The if-else
statement allows you to execute a block of code if a condition is true and another block of code if the condition is false.
Syntax:
if condition: # Code to execute if the condition is trueelse: # Code to execute if the condition is false
Example:
number = 10if number > 5: print("The number is greater than 5.")else: print("The number is 5 or less.")
2. if-elif-else Statement
The if-elif-else
statement is an extension of the if-else
statement. It allows you to check multiple conditions.
Syntax:
if condition1: # Code to execute if condition1 is trueelif condition2: # Code to execute if condition2 is trueelse: # Code to execute if all conditions are false
Example:
number = 10if number > 10: print("The number is greater than 10.")elif number == 10: print("The number is exactly 10.")else: print("The number is less than 10.")
3. while Loop
The while
loop is used to execute a block of code repeatedly as long as a given condition is true.
Syntax:
while condition: # Code to execute repeatedly
Example:
count = 0while count < 5: print("Count is:", count) count += 1
4. for Loop
The for
loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence.
Syntax:
for variable in sequence: # Code to execute for each item in the sequence
Example:
python
for i in range(5): print("Iteration:", i)
In this example, range(5)
generates numbers from 0 to 4, and the loop runs five times.
Summary
- if-else: Used for decision-making based on conditions.
- if-elif-else: Allows multiple conditions to be checked in sequence.
- while loop: Repeats code while a condition is true.
- for loop: Iterates over elements in a sequence.
Understanding these control statements will help you write programs that can make decisions and perform repeated tasks efficiently.
0 Comments
Please do note create link post in comment section