Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Python Basics Exercises: Functions and Loops (Summary)

In this video course, you practiced what you learned in Python Basics: Functions and Loops. You created custom functions, which consist of two parts:

  1. The function signature, initiated with the def keyword, which includes the function’s name and parameters.
  2. The function body, where the code executes every time the function is called.

Functions provide reusable components in your code, preventing repetition and enhancing readability and maintenance.

Along the way, you practiced using for loops, taking input from the user, and formatting numbers in f-strings.

If you haven’t already tackled the Python Basics: Functions and Loops Quiz, now is a great time to give it a whirl.

For further insights into the concepts covered in this video course, you can refer to the following tutorials:

Or you can explore the following video courses:

To continue your Python learning journey, check out the other Python Basics courses. You might also consider getting yourself a copy of Python Basics: A Practical Introduction to Python 3.

Download

Sample Code (.zip)

3.9 KB
Download

Course Slides (.pdf)

7.7 MB

00:00 Congratulations, you’ve made it to the last lesson of this Python Basics Exercises video course, and in this course, you practiced using functions, user input, basic arithmetic, and for loops to solve the exercises and the challenges.

00:17 You used code comments to help you get organized. You broke up the exercises into smaller tasks. You used descriptive variable names, which is always a good idea, and you repeatedly tested to see whether the code does what you expect it to do.

00:33 If you want to deepen your knowledge about functions and loops even more, I have some additional resources for you.

00:40 In Defining Your Own Python Functions, you learn how to define and call your own Python function. You also learn about passing data to your function and returning data from your function back to its calling environment.

00:53 And to learn more about the return statement, we have Usage and Best Practices. This is a step-by-step tutorial where you learn how to use the Python return statement when writing functions.

01:04 Additionally, you’ll cover some good programming practices related to the use of return. With this knowledge, you’ll be able to write readable, robust, and maintainable functions in Python.

01:14 Same goes for the tutorial Python for Loops: Definite Iteration. In this introductory tutorial, you’ll learn about how to perform definite iteration with Python’s for loops.

01:26 You’ll see how other programming languages implement definite iteration and learn about iterables and iterators, and then tie it all together to learn about Python’s for loop.

01:37 That’s the perfect addition to this course. If there were some parts where you were unsure how to solve it, then it’s a good idea to revisit these resources.

01:49 I don’t know about you, but I think this course was a good investment. Thanks again for joining me, and until next time, at realpython.com.

Avatar image for Anonymous

Anonymous on Feb. 13, 2024

Spent a little bit too much on this, but learned a lot. Also gave myself some extra challenge by calculating the monthly interest and some small error handling. There are probably minor errors here and there:

import sys

#--------------------------- functions ----------------------------------------
def compound_interest_core(principal_amount, rate_per_period, period):
    return principal_amount * (1 + rate_per_period) ** period


def annual_interest(amount, rate, periods):
    for year in range(1, periods+1):
        year_amount = compound_interest_core(amount, rate, year)
        print(f'Year {year}: ${year_amount:,.2f}')

    # output interest earned
    print((f'Total interest earned after {periods} years with annual compounding: '
           f'${year_amount - amount:,.2f}'))


def monthly_interest(amount, rate, periods):
    principal_amount = amount
    months = periods * 12
    monthly_rate = rate / 12

    for month in range(1, months+1):
        amount = compound_interest_core(amount, monthly_rate, 1)
        if month % 12 == 0:
            year = month // 12
            print(f'End of Year {year}: ${amount:,.2f}')

    # Output interest earned
    print((f'Total interest earned after {periods} years with monthly compounding: '
           f'${amount - principal_amount:,.2f}'))
#------------------------- end of functions -----------------------------------

while True:
    compounds = ('monthly', 'annually')

    compound_period = input('Enter the compound period? monthly or annually: ').lower()
    if not compound_period in compounds:
        print('Aceptable inputs: monthly or annually. try again!\n')
        continue

    principal_amount = float(input('Principal Amount: '))
    interest_rate = float(input('Interest Rate: '))
    periods = int(input('Time: '))

    if compound_period == 'monthly':
        monthly_interest(principal_amount, interest_rate, periods)
    elif compound_period == 'annually':
        annual_interest(principal_amount, interest_rate, periods)

    print()

    while True:
        choices_for_exit_prompt = ('y', 'n')
        restart_calc = input('Restart? y/n: ')
        if not restart_calc in choices_for_exit_prompt:
            print('Acceptable input: y/n. try again!\n')
            continue

        if restart_calc == 'n': sys.exit('Exiting...')

        print('Restarting...\n')
        break
Avatar image for rwelk

rwelk on March 8, 2024

I to spent a lot of time on the investment challange. It forced me to review functions in the suggested resources courses. I added this line so I could use the integer 5 instead which seems to work would this be considered Pythonic?

rate = float(input(“Enter rate of interest: “))/100

Avatar image for John Akpan

John Akpan on July 7, 2024

This is good. To make things simpler, I will use the try and except ValueError in the code. It helps manages the exception codes and troubleshooting.

Become a Member to join the conversation.