Opens in a new tab
Lesson 3

Control Structures and Functions in Python

Control & Functions, Python Mastery Program, Stage 1 Python

Written by

Muhammad Atif

Last Updated

Conditional Statements

Conditional statements help you make decisions in your code based on whether certain conditions are met. Python uses if, elif, and else keywords for conditional statements.

Example:

Python
age = 17

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Loops

Loops allow you to repeatedly execute a block of code as long as a condition is met. Python has two types of loops: for and while.

Example:

Python
# for loop
for i in range(5):
    print(i)

# while loop
count = 0
while count < 5:
    print(count)
    count += 1

List Comprehensions

List comprehensions are a concise way to create lists using a single line of code. They are an alternative to using a for loop.

Example:

Python
squares = [x * x for x in range(1, 6)]
print(squares)  # Output: [1, 4, 9, 16, 25]

Defining Functions

Functions are reusable pieces of code that can be called with a name. They are defined using the def keyword followed by the function name and a pair of parentheses.

Example:

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

greet("Alice")

Function Arguments and Return Values

Functions can take arguments as input and return values as output. Arguments are specified in the function definition, and the return keyword is used to return a value from the function.

Example:

Python
def add(a, b):
    return a + b

result = add(2, 3)
print(result)  # Output: 5

Scope and Lifetime of Variables

Variables defined within a function have a local scope, which means they can only be accessed within the function. Variables defined outside a function have a global scope and can be accessed anywhere in the program.

Example:

Python
x = 10  # global variable

def print_x():
    x = 5  # local variable
    print(x)

print_x()  # Output: 5
print(x)   # Output: 10

Hands-on Exercises

  1. Write a Python function that takes a number as input and returns its factorial.
  2. Create a function that takes a list of numbers and returns the sum of all even numbers in the list.
  3. Write a program that prints the Fibonacci sequence up to a specified number using a function.

Real-World Example

Suppose you are working on a program that calculates the total cost of items in a shopping cart. You can create a function that takes the prices of individual items and applies a discount based on specific conditions using control structures.

Additional Resources

  1. Python documentation: Control Flow Statements
  2. W3Schools Python tutorial: Python Functions
  3. Real Python: Defining Your Own Python Function

Summary and Next Steps

In this lesson, you have learned about:

  1. Conditional statements (if, elif, else)
  2. Loops (for, while)
  3. List comprehensions
  4. Defining functions
  5. Function arguments and return values
  6. Scope and lifetime of variables

In the next lesson, you will learn about modules and libraries in Python, which will help you enhance your programs by leveraging existing code and functionalities.

Remember to review the material periodically and practice your skills to reinforce your learning. Good luck on your journey to becoming a Python developer!

Review Questions

  1. What is the difference between an if statement and a while loop in Python?
  2. Explain the concept of local and global variables in Python.
  3. How do you define a function with multiple arguments in Python?
  4. Write a Python function that checks whether a given number is prime or not.
  5. Create a Python function that takes a string as input and returns the number of vowels in the string.

Muhammad Atif

Data Analyst & Web Development Professional | Focused on Machine Learning, SQL and Python

Transitioned from a background in finance to IT, I now focus on data science and web development, with specialties in Machine Learning, SQL, and Python. My articles aim to clarify complex IT concepts, informed by a rich history in analytical thinking and strategy.

You Might Also Like

Browse more topics and insights handpicked just for you. Stay updated and informed with our latest articles and news.