Introduction :
Python Programming's fundamental concepts include conditional statements and loops, which enable decision-making and repetitive operations. In this article, we look at the using of Python loops and the word of conditional statements.
You will have a solid understanding of Python loops and conditional statements by the end of this comprehensive guide. You will be able to make decisions, complete routine tasks, and create programs that are both effective and dynamic with the help of these fundamental ideas.
Conditional Statements and Loops in Python Programming.
Conditional statement
Conditional statements play a very important role in any programming language. Decisions are made through conditional statements.
We often make different decisions every moment. Doing a little math when you're short on money, getting busy during work days, getting tidy when you have an important meeting are all part of this decision making. And these decisions are conditional statements for the computer to make.
if
The most common conditional statement is the "if" statement. That is to add a condition with if. Let's see an example-
weather=30
if(weather>28):
print("The weather is hot")
Result-
The weather is hot
Here we put temperature 30 in a variable weather. In that if condition we have imposed a condition that if the temperature is more than 28 degrees then it will show us that The weather is hot.
Note here that there is a colon ( : ) after the if condition and the next statement with the condition is in a specific "indentation". "Indentation" is very important in Python. Newbies make two mistakes.
else
In the previous example we saw how to put a condition inside an if statement. But if the condition is not true then the result will be nothing.
For example –
weather=25
if(weather>28):
print("The weather is hot")
This code will not display any result, because the condition here is false. In such cases, "else" statement is used to display a final message for something unknown. The following example will give a clear idea-
weather=25
if (weather>28):
print ("The weather is hot")
else:
print ("The weather is unknown")
Result-
The weather is unknown
That is, only the "else" statement will work when the condition is false.
elif
In the example of if and else above, we noticed that only “yes” or “no” decisions are being made here, which is not realistic. It could also be that if the temperature is between 20 and 27 it is temperate, below 19 is cold and above 28 is hot.
It is exactly this type of condition that the elif statement is used to tie multiple conditions into the same thread.
See this example –
weather=25
if(weather<20):
print("The weather is cold.")
elif (weather>=20 and weather<=27):
print("The weather is temperate.")
elif(weather>27):
print("The weather is hot.")
Result-
The weather is temperate.
Note here: That all conditional operators are applicable for conditional statements and complex conditions can be made by connecting multiple conditions with and, or etc.
Nested if
One or more conditional statements can be used nested inside an if condition, it is called a nested condition.
Let's look at an example –
weather=25
if (weather<20):
print ("The weather is cold.")
else:
if (weather>=20 and weather<=27):
print ("The weather is temperate")
elif (weather>27):
print ("The weather is hot")
Result-
The weather is temperate.
Here it works like the previous example but first we check if it is cold weather, if not then we go inside else to check if it is temperate or hot.
Here the 'if' and 'elif' used after 'else' are nested conditions.
Loops in Python
Our life is like a loop. Get up in the morning, have breakfast, attend your workplace, eat lunch, eat and rest at night, have some entertainment if you have time, sleep at night. This is how our daily routine goes. That is, we do almost the same thing every day.
Repeating this same operation is called loop or looping in programming language. Loops are an essential element in any programming language.
There are two types of loops in Python –
•while loop
•for loop
But a loop has three main parts;
•Initialization
•Condition
•Increments/Decrements
"Initialization" is to initialize with some value before starting the condition of a loop.
The main condition of the "Condition" loop is; Impose the condition of the loop.
Help break condition by changing the value of a loop with "Increment/Decrements".
Read more: Data Types in Python: Variables and Operators
While loop
While literally means 'when'. That is, the "while loop" will continue until a certain condition is true. Let's see an example –
i=0
while(i<10):
print(i)
i+=1
Result –
0
1
2
3
4
5
6
7
8
9
Here the loop is initialized with i=0,
A condition is set with while(i<10) and the condition is broken with i+=1. Initially the value of i is set to 0, the value of i is incremented by 1 through i+=1 each time the loop is executed.
Once the value of i increases to 10 then the condition is false, whenever the condition is false then the loop is broken.
for loop
A for loop in Python is used to iterate a sequence. We have already seen about sequence data types i.e list, tuple, dictionary etc. Let's see an example below-
for i in range(10):
print (i)
Result-
0
1
2
3
4
5
6
7
8
9
The result is the same as the while loop. The difference is only in its type. A while loop loops over a condition, and a for loop loops over a sequence. Here range(10) means the number between 0 and 10.
Now we will look at adding numbers from 1 to 10 using loop two.
First of all we have seen the addition using the while loop-
sum = 0
i=0
while(i<11):
sum+=i
i+=1
print(sum)
Result -
55
Now we will look at adding using the for loop –
sum =0
for i in range (11):
sum+ =i
print (sum)
Result-
55
From the above two examples we are more clear about the difference between for and while and how it works.
Loop Control with pass:
In situations where you need a loop as a placeholder or a structure that doesn't require any action, you can use the pass statement.The pass statement acts as a null operation, essentially doing nothing.
When you are working on code but don't want to provide an implementation yet, it is frequently used as a placeholder.
For example:
vegetables = ["carrot", "potato", "pumpkin", "tomato"]
for vegetable in vegetables:
# Code to process each vegetable goes here
# TODO: Add your code to process each vegetable
pass
In this example, the pass statement serves as a placeholder for the code that will process each fruit. It allows you to define the structure of the loop without providing any action for now.
Read more:Python byte code comment,Documents
List Comprehension:
Python offers a concise way to create lists using a loop construct called list comprehension.By utilizing list comprehension, it becomes possible to generate a novel list by applying an expression to each individual element within an existing list or any other iterable.
Below is an illustrative instance employing list comprehension, where a fresh list is created consisting of the square values of numbers ranging from 1 to 5:
squares = [num ** 2 for num in range(1, 6)]
print (squares)
Result -
[1, 4, 9, 16, 25]
In this example, the expression num ' ** 2` is applied to each number in the range from 1 to 5 using list comprehension. The resulting squares are stored in the squares list.
List comprehension offers a concise and readable way to generate new lists based on existing ones, reducing the need for explicit loops.
These additional concepts enhance your understanding of Python loops and provide you with more tools to work with when designing and implementing your code.
Conclusion
In this article we have tried to provide a comprehensive guide to conditional statements and loops in Python programming. It emphasizes the importance of these basic concepts in decision-making and repetitive activities.
In this article we have tried to highlight the similarities and differences between their implementations, providing examples of adding numbers using both "while" and "for" loops. With these examples, you have gained a deeper understanding of the difference between the two loop types.
Overall, hopefully this article serves as a comprehensive and beginner-friendly guide to conditional statements and loops in Python programming. By mastering these concepts, you can make informed decisions, automate routine tasks, and efficiently develop dynamic programs.
FAQ
Q: What are loops in Python programming?
A: Loops in Python allow you to repeatedly execute a block of code.
They are used to perform repetitive tasks, iterate over sequences, or continue until a certain condition is met.
Q: How does a while loop work in Python?
A: A "while" loop continues to execute a block of code as long as a certain condition remains true. The code block is executed repeatedly until the condition becomes false.
Q: What is the purpose of the "pass" statement in loops?
A: The "pass" statement in Python is used as a placeholder when a loop or a code block requires a statement but you don't want to perform any action at that point.
It acts as a null operation, essentially doing nothing.
Q: What are conditional statements in python programming?
A: Conditional statements are fundamental concepts in Python programming that allow decision-making based on certain conditions. These statements enable programmers to execute specific blocks of code based on whether a condition is true or false.
0 Comments