CONTROL FLOW STATEMENT
CONTROL FLOW STATEMENTS
Control flow statements in Python are used to alter the sequential execution of code based on certain conditions. They allow you to control how the program flows and which blocks of code are executed. The common control flow statements in Python include:
1.if
statement: It is used to execute a block of code if a certain condition is true.SYNTAX:
if condition:
# code block to be executed if the condition is true
if-else
statement: It is used to execute one block of code if a condition is true, and another block if the condition is false.
SYNTAX:if condition:
# code block to be executed if the condition is true
else:
# code block to be executed if the condition is false
3.if-elif-else
statement: It is used to test multiple conditions and execute different blocks of code based on the first condition that evaluates to true. The elif
stands for "else if."if condition1:
# code block to be executed if condition1 is true
elif condition2:
# code block to be executed if condition2 is true and condition1 is false
else:
# code block to be executed if all conditions are false
4.for
loop: It is used to iterate over a sequence (such as a list, tuple, or string) or any iterable object. The loop body is executed for each item in the sequence.SYNTAX:
for item in sequence:
# code block to be executed for each item
5. while
loop: It repeatedly executes a block of code as long as a certain condition is true.SYNTAX:
while condition:
# code block to be executed as long as the condition is true
break
statement: It is used to exit a loop prematurely. When encountered, the program jumps out of the loop and continues with the next statement after the loop.
SYNTAX:
.while condition: if some_condition: break # rest of the loop code
.while condition: if some_condition: break # rest of the loop code
7.continue
statement: It is used to skip the remaining code in a loop iteration and move to the next iteration.for item in sequence SYNTAX:
for item in sequence:
if some_condition:
continue
# rest of the loop code
8. pass
statement: It is a placeholder statement that does nothing. It is used when a statement is syntactically required but you don't want to execute any condition SYNTAX:
if condition:
pass # no code to execute
else:
# code block to be executed
These control flow statements provide flexibility in managing the flow of your program and executing code based on different conditions and iterations.
Comments
Post a Comment