Loops & Conditional statements in Python.
What Are Python loops?
A loop is an instruction that repeats multiple times as long as some condition is met.
Flowchart:
Significance of indentation:
Indentation is significant in Python. It is used to define a block of code; without indentation, the program will show an error.
Type of Loops:
There are mainly two types of loops. Let’s discuss them one by one.
1. For Loop
A for loop in Python is used to iterate over a sequence (list, tuple, set, dictionary, and string).
Flowchart:
Syntax: for iterating_var in sequence:??
???statement(s)?
Example:
The preceding code executes as follows: The variable i is a placeholder for every item in your iterable object. The loop iterates as many times as the number of elements and prints the elements serially.
2. While Loop
The while loop is used to execute a set of statements as long as a condition is true.
Flowchart:
Syntax: while expression:??
????statements ?
Example:
The preceding code executes as follows: We assign the value to variable x as 1. Until the value of x is less than 3, the loop continues and prints the numbers.?The preceding code executes as follows: We assign the value to variable x as 1. Until the value of x is less than 3, the loop continues and prints the numbers.?
领英推荐
3. Nested Loop
If a loop exists inside the body of another loop, it is called a nested loop.
Example:
The preceding code executes as follows: The program first encounters the outer loop, performing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion. Then the program returns to the top of the outer loop, completing the second iteration and again triggers the nested loop. The nested loop runs to completion, and the program returns to the top of the outer loop until the sequence is complete.
Conditional Statements in Python:
Decision-making statements are used to execute the statements only when a particular condition is fulfilled.
Flowchart:
There are three main types of conditional statements. They are:
1. If statement: The if statement is used to test a specific condition. If the condition is true, a block of code is executed.
Syntax: if expression:
? statement(s)
Flowchart:
Example:
2. Else statement: The else statement is executed when the expression in the if condition is false.
Flowchart:
Example:
3. Elif statement: The elif statement in Python enables you to check multiple conditions and execute specific blocks of statements if the previous conditions were false.
Example: