
Python Basics: Functions and Loops
Python Basics: Functions and Loops
Functions are the building blocks of almost every Python program. They’re where the real action takes place!
In your Python Basics journey, you’ve probably encountered functions such as print(), len(), and round(). These are all built-in functions because they come built into the Python language itself. You can also create user-defined functions that perform specific tasks.
Functions break code into smaller chunks and are great for defining actions that a program will execute several times throughout your code. Instead of writing the same code each time the program needs to perform the same task, just call the function!
But sometimes you do need to repeat some code several times in a row. This is where loops come in.
In this Python Basics tutorial, you’ll learn how to create user-defined functions and how to write for and while loops.
User-Defined Functions
User-defined functions allow you to create custom functions specific to your needs. Here’s an example of a simple function that adds two numbers:
def add_numbers(x, y):
return x + y
result = add_numbers(3, 5)
print(result) # Output: 8In this example, the add_numbers function takes two parameters, x and y, and returns their sum.
for Loops
for loops are used to iterate over a sequence (e.g., list, tuple, string) or other iterable objects. Here's an example of using a for loop to iterate over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherrywhile Loops
while loops are used to execute a block of code repeatedly as long as a specified condition is true. Here's an example of using a while loop to print numbers from 1 to 5:
num = 1
while num <= 5:
print(num)
num += 1Output:
1 2 3 4 5
Now that you understand the basics of functions and loops, you can start using them to create more complex and efficient Python programs. Happy coding!
