Control Structures and Functions

In this lesson, we’ll explore how Python handles control structures and functions, comparing them with their Java counterparts. This knowledge will help you write more Pythonic code and understand the key differences between these two languages.

Control Structures

If/Elif/Else Statements

Python’s if statements are similar to Java’s, but with some syntactic differences:

# Python
if condition:
    # code block
elif another_condition:
    # code block
else:
    # code block

Compare this to Java:

// Java
if (condition) {
    // code block
} else if (anotherCondition) {
    // code block
} else {
    // code block
}

Key differences:

  1. Python uses elif instead of else if
  2. Python doesn’t use parentheses around conditions
  3. Python uses colons and indentation instead of curly braces

For and While Loops

Python’s for loops are more similar to Java’s enhanced for loops:

# Python
for item in iterable:
    # code block
// Java
for (Item item : iterable) {
    // code block
}

Python’s while loops are syntactically similar to if statements:

# Python
while condition:
    # code block
// Java
while (condition) {
    // code block
}

Python also provides break and continue statements, which work similarly to Java.

Loop Behavior Differences

  1. Python’s for loops always iterate over sequences (lists, tuples, etc.) or other iterables.
  2. There’s no C-style for loop in Python (e.g., for(int i=0; i<10; i++)). Instead, you can use range():
# Python
for i in range(10):
    print(i)
  1. Python provides an else clause for both for and while loops, which executes when the loop completes normally (not through a break):
# Python
for item in iterable:
    if condition:
        break
else:
    print("Loop completed normally")

Functions

Defining and Calling Functions

Python functions are defined using the def keyword:

# Python
def greet(name):
    return f"Hello, {name}!"

# Calling the function
print(greet("Alice"))

Compare this to Java:

// Java
public static String greet(String name) {
    return "Hello, " + name + "!";
}

// Calling the method
System.out.println(greet("Alice"));

Key differences:

  1. Python doesn’t require specifying return types or parameter types
  2. Python uses indentation to define the function body, not curly braces

Default Arguments

Python supports default arguments, which Java doesn’t have natively:

# Python
def greet(name="World"):
    return f"Hello, {name}!"

print(greet())  # Output: Hello, World!
print(greet("Alice"))  # Output: Hello, Alice!

Keyword Arguments

Python allows calling functions with named arguments in any order:

# Python
def create_person(name, age, city):
    return f"{name} is {age} years old and lives in {city}"

print(create_person(age=30, city="New York", name="Alice"))

This feature doesn’t exist in Java.

Lambda Functions

Python’s lambda functions are similar to Java’s anonymous functions, but more concise:

# Python
square = lambda x: x ** 2
print(square(5))  # Output: 25
// Java
Function<Integer, Integer> square = x -> x * x;
System.out.println(square.apply(5));  // Output: 25

Python’s lambda functions are often used with built-in functions like map(), filter(), and reduce() as we will see later in the course.

Conclusion

In this lesson, we’ve explored how Python handles control structures and functions, highlighting the key differences from Java. Python’s syntax is generally more concise and relies heavily on indentation for structure. Its function definitions are more flexible, allowing for default and keyword arguments.

In the next lesson, we’ll dive into Python’s data structures, including lists, tuples, and dictionaries, and compare them to Java’s collections.