Topic 3 – Python Control Structures (If-else, For/while loops, break/continue/pass)

image 2

Play Store Application link – Java to Python in 17 Steps – App on Google Play

Github project link – https://github.com/kuldeep101990/Python_step3

Control structures are essential for directing the flow of a program. If you’re familiar with Java, you’ll find Python’s control structures to be simpler and more intuitive. Let’s dive in.


If-else in Python vs. Java

In Java, conditions use parentheses and braces, while Python relies on indentation and the absence of parentheses.

Java Example:

int age = 18;
if (age >= 18) {
    System.out.println("You are an adult.");
} else {
    System.out.println("You are not an adult.");
}

Python Equivalent:

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

  • Python eliminates the need for parentheses and braces, using colons (:) and indentation instead.

Real-world analogy: Think of Java as using a locked toolbox (explicit braces) and Python as having open shelves (indentation).


Loops in Python vs. Java

Loops help iterate over a range of values or elements. Python simplifies loops significantly compared to Java.

1. For Loop

In Java, a for loop typically iterates over a range of numbers or a collection using either traditional or enhanced syntax.

Java Example (Traditional):

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Java Example (Enhanced):

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}

Python Equivalent:

# Using range()
for i in range(5):
    print(i)
# Iterating over a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

  • The range() function generates numbers, similar to a for loop’s initialization and condition in Java.
  • Python’s for loop directly iterates over iterable objects (lists, strings, etc.), replacing the need for enhanced for in Java.

2. While Loop

Both Java and Python use while loops similarly, but Python’s syntax is less verbose.

Java Example:

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

Python Equivalent:

i = 0
while i < 5:
    print(i)
    i += 1

  • Note that Python uses += to increment, avoiding ++ which isn’t available in Python.

Break, Continue, Pass

Break:

Exits the loop prematurely.

Java Example:

for (int i = 0; i < 5; i++) {
    if (i == 3) break;
    System.out.println(i);
}

Python Equivalent:

for i in range(5):
    if i == 3:
        break
    print(i)

Continue:

Skips the current iteration and proceeds to the next.

Java Example:

for (int i = 0; i < 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}

Python Equivalent:

for i in range(5):
    if i == 3:
        continue
    print(i)

Pass:

A Python-specific keyword used as a placeholder. It does nothing and is often used for creating empty blocks of code.

Example:

for i in range(5):
    if i == 3:
        pass  # Placeholder for future logic
    print(i)

Real-world analogy: pass is like an empty shelf placeholder in a grocery store.


Complete Python Program

Here’s a program demonstrating these control structures:

# A Python program showcasing control structures
def main():
    # If-else example
    age = int(input("Enter your age: "))
    if age >= 18:
        print("You are an adult.")
    else:
        print("You are not an adult.")
    # For loop example with range()
    print("Counting from 0 to 4:")
    for i in range(5):
        print(i)
    # While loop example
    print("Counting from 5 to 1:")
    i = 5
    while i > 0:
        print(i)
        i -= 1
    # Using break and continue
    print("Numbers excluding 3:")
    for i in range(5):
        if i == 3:
            continue
        print(i)
    print("Loop stops at 3:")
    for i in range(5):
        if i == 3:
            break
        print(i)
if __name__ == "__main__":
    main()

How to Run:

  1. Save the code in a file named control_structures.py.
  2. Run it using the terminal: python control_structures.py

Sample Output:

Enter your age: 20
You are an adult.
Counting from 0 to 4:
0
1
2
3
4
Counting from 5 to 1:
5
4
3
2
1
Numbers excluding 3:
0
1
2
4
Loop stops at 3:
0
1
2

This program illustrates Python’s clean and concise control structures. With practice, you’ll appreciate how much easier Python makes common programming tasks. Stay tuned for the next tutorial on Python functions and modularity!

Leave a Reply

Your email address will not be published. Required fields are marked *