Day 2: Control Structures and Functions

Welcome back to our Python learning journey! Yesterday, we covered the basics of Python programming, including data types, variables, and input/output. Today, we’ll dive into control structures and functions.

Control Structures

Control structures are constructs that allow us to control the flow of our program based on certain conditions. The most common control structures are if statements and loops.

If Statements

if statements allow us to execute code only if a certain condition is true. Here’s the basic syntax:

if condition:
    # code to execute if condition is true

The condition is an expression that evaluates to either True or False. If it’s True, the code inside the if statement will be executed. If it’s False, the code will be skipped.

Let’s look at an example:

age = 18

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

In this example, we’re checking if age is greater than or equal to 18. If it is, we print out a message saying that the user is an adult. If age is less than 18, the message will not be printed.

We can also add an else clause to execute code if the condition is False:

age = 16

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

In this example, if age is greater than or equal to 18, we print out a message saying that the user is an adult. Otherwise, we print out a message saying that the user is not yet an adult.

Let’s improve the program by taking input from the user:

age = int(input("Hi there, please enter your age: "))

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

When you run it, you can enter any number and you will get the result:

Control structure in python example

As you can see, there is no limit on the value you can enter. In reality, age couldn’t be < 0 or greater than 200 (for now). Can you add more checks to make sure invalid values are not allowed?

Loops

Loops allow us to execute a block of code repeatedly. The two most common types of loops are for loops and while loops.

For Loops

for loops allow us to iterate over a sequence of values. Here’s the basic syntax:

for variable in sequence:
    # code to execute for each value in sequence

The variable is a temporary variable that takes on each value in the sequence one at a time. The code inside the loop is executed once for each value in the sequence.

Let’s look at an example:

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

for fruit in fruits:
    print(fruit)

In this example, we’re iterating over a list of fruits and printing out each one.

looping through a list

While Loops

while loops allow us to execute a block of code as long as a certain condition is true. Here’s the basic syntax:

while condition:
    # code to execute while condition is true

The condition is an expression that evaluates to either True or False. The code inside the loop is executed repeatedly as long as the condition is True.

Let’s look at an example:

count = 0

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

In this example, we’re using a while loop to print out the numbers from 0 to 4.

While loop in python

Functions

Functions are blocks of code that can be called from other parts of the program. They allow us to organize our code into reusable chunks and make our code more modular.

Defining Functions

To define a function, we use the def keyword followed by the name of the function and its parameters (if any):

def greet(name):
  print(f"Hello, {name}!")
    
def greet_general():
  print("Hello, hi")

In this example, we’ve defined a function called greet that takes one parameter name. The function prints out a greeting message using the value of the name parameter.

Calling Functions

To call a function, we simply use its name followed by its arguments (if any):

greet("Dat")
greet_general()

This will call the greet and greet_general functions. Here is the output:

Define and call functions in python

Returning Values

Functions can also return values using the return keyword. Here’s an example:

def square(x):
    return x * x

In this example, we’ve defined a function called square that takes one parameter x. The function returns the square of x.

We can call this function and use its return value like this:

result = square(5)
print(result) # prints 25

Extra tasks

Now that we’ve covered the basics of control structures and functions, it’s time to put them to the test with some programming challenges.

Write a function that takes a number as an argument and returns "odd" or "even" depending on whether the number is odd or even.

This is quite a simple assignment. The only thing you may not know beforehand is how to check if a number is odd or even. The trick is to use the modulus operator.

Here is the code:

number = int(input("Please input a number: "))

if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")

Running the program would produce the following output:

Write a function that takes a list of numbers as an argument and returns the sum of all the numbers in the list.

This practice helps you reinforce your knowledge of list. Here is the code for this program:

def sum_list(numbers):
    # initialize a variable to store the sum
    total = 0

    # loop through the list and add each number to the total
    for number in numbers:
        total += number

    # return the final total
    return total

Let’s break down what the code does:

  1. We define a function called sum_list that takes one parameter numbers. This function returns the sum of all the numbers in the numbers list.
  2. Inside the sum_list function, we initialize a variable called total to 0. This variable will store the sum of all the numbers in the list.
  3. We use a for loop to iterate through each number in the numbers list. Inside the loop, we add each number to the total variable.
  4. After looping through all the numbers in the list, we return the final total value.

Let’s try the function with some list:

print("Sum of list from 1 to 5: " + str(sum_list([1, 2, 3, 4, 5])))
print("Sum of list from 5 to 10: " + str(sum_list([5, 6, 7, 8, 9, 10])))

The output is exactly as you might expect:

Sumlist output

Conclusion

In this post, you’ve learned about control structures (if and while) and how to define and user functions. These building blocks are vital for any program you write in the future. In the next lesson, you will learn about String and List.

In the meantime, keep practicing! If you need the code, it’s available on GitHub.

Leave a Comment