Conditionals and Loops in Python Programming language (Part 4/6)

Experience the Beauty of Python: The Easiest Language to Learn and Use

Siddhartha Purwar
6 min readJul 14, 2023
source: https://in.pinterest.com/pin/326581410496262002/

Lets start with a joke:

How do loops break up? They say, “It’s not you, it’s the condition!”” 😄

Table of Contents

  1. Introduction to Conditional Statements
  2. if Statement
  3. if-else Statement
  4. if-elif-else Statement
  5. Nested if Statements
  6. Comparison Operators
  7. Logical Operators
  8. Introduction to Loops
  9. while Loop
  10. for Loop
  11. Nested Loops
  12. Loop Control Statements
  13. Best Practices
  14. Additional Resources

1. Introduction to Conditional Statements

Conditional statements are used to make decisions based on certain conditions. They execute different blocks of code depending on whether a condition is true or false. In Python, conditional statements are created using keywords such as if, else, and elif (short for "else if").

2. if Statement

The if statement is the most basic type of conditional statement. It allows us to execute a block of code only if a given condition is true. Here is the syntax:

if condition:
# Code to execute if the condition is true

Let’s consider an example where we check if a number is positive:

num = 10

if num > 0:
print("The number is positive.")

Output:

The number is positive.

3. if-else Statement

The if-else statement extends the if statement by providing an alternative block of code to execute when the condition is false. The syntax is as follows:

if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false

Let’s modify the previous example to include the else statement:

num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is not positive.")

Output:

The number is not positive.

4. if-elif-else Statement

The if-elif-else statement allows us to check multiple conditions and execute different blocks of code accordingly. The elif keyword is short for "else if" and can be used multiple times. Here is the syntax:

if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if all conditions are false

Let’s consider an example where we determine the grade based on the percentage obtained:

percentage = 75

if percentage >= 90:
print("Grade: A")
elif percentage >= 80:
print("Grade: B")
elif percentage >= 70:
print("Grade: C")
elif percentage >= 60:
print("Grade: D")
else:
print("Grade: F")

Output:

Grade: C

5. Nested if Statements

Python allows nesting conditional statements within each other. This means that we can have an if statement inside another if statement. Here is an example:

num = 15

if num > 0:
if num % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive and odd.")
else:
print("The number is not positive.")

Output:

The number is positive and odd.

6. Comparison Operators

Conditional statements rely on comparison operators to evaluate conditions. Here are the commonly used comparison operators in Python:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

7. Logical Operators

Logical operators are used to combine multiple conditions in conditional statements. The three logical operators in Python are:

  • and (returns True if both conditions are true)
  • or (returns True if at least one condition is true)
  • not (returns the opposite of the condition)

8. Introduction to Loops

Loops enable us to execute a block of code repeatedly until a specific condition is met. They eliminate the need for writing repetitive code and allow us to process data efficiently. Python offers two main types of loops: while loops and for loops.

9. while Loop

A while loop repeatedly executes a block of code as long as a given condition is true. The syntax of a while loop is as follows:

while condition:
# Code to execute while the condition is true

Let’s consider an example where we use a while loop to count from 1 to 5:

count = 1

while count <= 5:
print(count)
count += 1

Output:

1
2
3
4
5

10. for Loop

A for loop is used to iterate over a sequence, such as a string, list, or tuple. It executes a block of code for each element in the sequence. The syntax of a for loop is as follows:

for element in sequence:
# Code to execute for each element

Let’s consider an example where we use a for loop to iterate over a list of fruits:

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

11. Nested Loops

Python allows us to nest loops within each other. This means that we can have a loop inside another loop. Nested loops are useful when dealing with multidimensional data or when we need to iterate over multiple sequences simultaneously. Here is an example:

for i in range(1, 4):
for j in range(1, 4):
print(i, j)

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

12. Loop Control Statements

Python provides loop control statements to modify the behavior of loops. These statements include break, continue, and pass:

  • break: Terminates the loop prematurely and transfers control to the next statement after the loop.
  • continue: Skips the current iteration of the loop and moves to the next iteration.
  • pass: Acts as a placeholder and does nothing. It is commonly used when a statement is required syntactically but no action is needed.

Let’s consider an example where we use loop control statements:

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
if fruit == 'banana':
continue
elif fruit == 'cherry':
break
else:
pass

print(fruit)

Output:

apple

13. Best Practices

When working with conditional statements in Python, it is important to follow some best practices:

  • Use meaningful variable names to enhance code readability.
  • Indent code blocks consistently (usually using four spaces) to improve code structure.
  • Add comments to explain complex conditions or code logic.
  • Avoid excessive nesting of if statements to keep code clean and readable.

When working with loops in Python, it is important to follow some best practices:

  • Use meaningful variable names to enhance code readability.
  • Avoid infinite loops by ensuring the loop condition will eventually become false.
  • Minimize the use of nested loops to maintain code clarity and performance.
  • Use loop control statements judiciously and ensure they improve the code’s logic.

14. Additional Resources

Here are some resources to further deepen your understanding of conditional statements in Python:

Here are some resources to further deepen your understanding of loops in Python:

This article covers two important topics in Python: conditional statements and loops.

For conditional statements, we discussed various types such as if, if-else, if-elif-else, and nested if statements. We provided syntax, code examples, and outputs to illustrate their usage. Following best practices is emphasized to ensure clean and readable code. Additional resources were suggested to further enhance understanding and proficiency in working with conditionals.

Regarding loops, we explored while loops and for loops. We provided syntax, code examples, and outputs to demonstrate their functionality. Nested loops and loop control statements, including break, continue, and pass, were also discussed. The article stressed the importance of best practices for clean and efficient code. Similar to the conditional statements section, additional resources were suggested for further learning.

By practicing and exploring these topics, readers can become proficient in utilizing conditionals and loops effectively in Python.

Thank you for reading!

This is part 4, and there will be 2 more part. This part was about conditionals and loops in Python Programming Language. In part 4we will learn about Python functions.

Link for Part 1: https://medium.com/@siddp6/python-programming-language-part-1-6-8b937f7297bf

Link for Part 2: https://siddp6.medium.com/python-programming-language-part-2-6-403dabaa7c6a

Link for Part 3: https://medium.com/@siddp6/python-programming-language-part-3-6-ab0af8000e27

Link for Part 4: https://medium.com/@siddp6/conditionals-and-loops-python-programming-language-part-4-6-b5b1a8c9521e

Link for Part 5: https://siddp6.medium.com/functions-in-python-programming-language-part-5-6-5c2c5b1df5fe

Link for Part 6: https://siddp6.medium.com/classes-and-object-oriented-programming-oop-in-python-programming-language-part-6-6-4e2fca5e1eb9

Copyright © 2023 Siddhartha Purwar. All rights reserved. Portions of this content were enhanced grammatically and refined with the assistance of ChatGPT, an AI language model by OpenAI.

--

--

Siddhartha Purwar
Siddhartha Purwar

Written by Siddhartha Purwar

"Data data data, I can't make bricks without clay"

Responses (1)