DEV Community

Cover image for Python 101 tutorial: Write your first real program
Hunter Johnson for Educative

Posted on • Originally published at educative.io

Python 101 tutorial: Write your first real program

Python is a great general purpose programming language and one of the most popular languages in the world right now. It's widely used in many different fields and industries. Some of the most common uses are for data science and data visualization, web development, scientific computing, and automation for email and web scraping, as well as AI and machine learning.

Today, we're going to write our first Python program that does more than just Hello world. We'll get hands-on with software engineering fundamentals like:

  • Collecting user input
  • Converting data types
  • Performing advanced calculations
  • Defining a reusable function

Getting your development environment can be a little tricky when you're starting out. So, stick around to the end of the post where we tell you how to start in a few seconds without having to set anything up. Plus, we'll give you access to some amazing free intro computer science content.

We have this entire tutorial recorded and posted to YouTube! If you prefer to watch rather than read for your own comprehension, check out the video here:

Get hands on with the finished code

Below is the completed project, try it yourself! Enter the four starting parameters in the box below, each separated by a new line: principal, interest rate as a decimal, time period, and compounding frequency. Be sure to write them in this order. Once you have all the values set, click run in a code editor and the program will do the rest for you!

def calcInterest(principal, interest_rate, time_period, frequency):
    amount = principal * (1 + (interest_rate / compounding_frequency)) ** (compounding_frequency * time_period)
    interestAmt = amount - principal
    return interestAmt


# get user input

## Enter the principal amount
principal = float(input())

## Enter the interest rate as a decimal
interest_rate = float(input())

## Enter the time period
time_period = float(input())

## Enter the compounding frequency in years
compounding_frequency = float(input())

# print out
totalInterest = calcInterest(principal, interest_rate, time_period, compounding_frequency)

print('Total interest accrued',round(totalInterest, 2))
Enter fullscreen mode Exit fullscreen mode

We'll cover:

Python 101: Learn Python with compound interest

In this tutorial, we're going to learn the basics of Python to create a program to calculate compound interest.

This program will be a great way of calculating retirement savings or what an investment may look like several years down the road.

First, go to this website: Compound Interest Calculator where they calculate this for us. Let's run through this web app as an example, and then we'll recreate our own using Python.

Start with a principal amount of $1,000, an annual interest rate of 4%, and have it compounded on an annual basis.

If we run the program given a time period of five years, it tells us that the principal plus interest is going to be equal to $1,216.

They also provide this formula for us, and it's surprisingly complex. (We'll reference this formula a little later when we're writing our code.)

A = P(1 + r/n)^{nt}

  • A = Accrued amount (principal + interest)
  • P = Principal amount
  • r = Annual interest rate as a decimal
  • n = number of compounding periods
  • t = time in decimal years

Before we start writing this formula as Python code, let's set up our program so that it takes user input.

Basic Syntax: Getting user inputs

By collecting user inputs within the program, we can make it so that our code can be reused without having to edit it.

The syntax for getting any user input first involves declaring a variable and then assigning it to the built-in function input().

Below is a code block that shows the proper syntax for retrieving all the user inputs we'll need to calculate the compound interest.

Generally, it is a best practice to add a comment (using a # symbol) to describe what the program is trying to accomplish in each section.

# get user inputs

## Enter the principal amount
principal = input()

## Enter the interest rate as a decimal
interest_rate = input()

## Enter the time period
time_period = input()

## Enter the compounding frequency in years
compounding_frequency = input()

print(principal)
print(interest_rate)
print(time_period)
print(compounding_frequency)
Enter fullscreen mode Exit fullscreen mode

But what does this do? input() is a built-in function that comes with every version of the Python language. It collects user input from our terminal.

So, let's quickly test this out. If you run the code above, you'll see that after filling in the necessary parameters, the variables now spit out the value that you typed in.

The code widget in our blog accepts user input slightly different than a normal IDE or terminal would. Below is a non-executable widget that shows how you would call the input() function outside of this blog.

# Get user inputs

principal = input("Enter the principal amount: ")
interest_rate = input("Enter the interest rate as a decimal: ")
time_period = input("Enter the time period: ")
compounding_frequency = input("Enter the compounding frequency in years: ")
Enter fullscreen mode Exit fullscreen mode

Converting data types

Before we go any further, we need to do some data conversion on these variables. Python has several different data types. The four most basic data types are:

  • Integer int: A whole number with no decimal point. Example: 5
  • Float float: A number with a decimal point. Example: 3.14
  • Boolean bool: A data type with only two possible values: True or False. Used in logical operations and control statements.
  • String str: A sequence of characters enclosed in quotation marks. Example: "Hello, World!"

One key element of Python is that everything that's collected from a user prompt with the input() function is formatted as a string.

But we want all of these values to be numbers, specifically floats, meaning that they have decimal values (versus whole numbers, or integers).

To do a data conversion here, we need to specify that each of these inputs should be treated as floating point values. The syntax for converting data types in this scenario is to use the built-in float() function.

The corrected code with converted data types can be found below.

# get user inputs

## Enter the principal amount
principal = float(input())

## Enter the interest rate as a decimal
interest_rate = float(input())

## Enter the time period
time_period = float(input())

## Enter the compounding frequency in years
compounding_frequency = float(input())
Enter fullscreen mode Exit fullscreen mode

Calculating the result

Now that we have all of our necessary parameters, and they are the correct data type, we can start performing calculations on them.

To do this, we're going to create a new variable called amount. And we're going to recreate that formula that we mentioned earlier.

A = P(1 + r/n)^{nt}

When we write this out as code, the formula looks like this:

# calculate interest
amount = principal * (1 + (interest_rate / compounding_frequency)) ** (compounding_frequency * time_period)
Enter fullscreen mode Exit fullscreen mode

Let's cover these mathematical operators in Python.

  • * operator: multiply
  • \ operator: divide
  • ** operator: raise to the power of

Now, we can check our work against the website that we looked at in the beginning.

# get user inputs

## Enter the principal amount
principal = float(input())

## Enter the interest rate as a decimal
interest_rate = float(input())

## Enter the time period
time_period = float(input())

## Enter the compounding frequency in years
compounding_frequency = float(input())

# calculate interest
amount = principal * (1 + (interest_rate / compounding_frequency)) ** (compounding_frequency * time_period)

print(amount)
Enter fullscreen mode Exit fullscreen mode

Let's run this program using the same parameters we ran on the website.

  • Principal = 1000
  • Interest rate = .04 (4%)
  • Time period = 5 years
  • Compounding frequency/year = 1

Our value of 1,216.65 is the same as what we got on the website. So that's good progress!

Defining a function

We now know that the bare bones of our code work– we're able to run the calculation, but there are a couple changes to make our program more usable.

First, we want to round the printed total amount off so that it only displays two places to the right of the decimal. This gives us the desired monetary result in dollars and cents.

And then we also want to have a friendly message to say "this is what your amount is:".

To follow the best practices of actual programmers, we'll create a function. Functions open the door to more advanced programming concepts and allow us to create larger, highly functional programs.

At their simplest, functions are a way of defining logic. They are useful if you need to reference this logic more than once, and if different chunks of code are going to be calling it.

To create a reusable function, you always start off with the keyword, def.

Let's take a look at the function we'll use for this program.

def calcInterest(principal, interest_rate, time_period, frequency):
    amount = principal * (1 + (interest_rate / compounding_frequency)) ** (compounding_frequency * time_period)
    interestAmt = amount - principal
    return interestAmt
Enter fullscreen mode Exit fullscreen mode

Our function is called calcInterest, and the line ends with a colon. In the parentheses are all of the input parameters for this function. These are the variables that the function will accept as arguments. So, we're going to pass the: principal, interest rate, time period, and compounding frequency.

Notice that every single line of code within that function is indented a couple of spaces. This formatting is unique to Python. Other programming languages might have curly braces to notate code nested in a function, but in Python, it's done by indentation.

The second line of the function is just the same exact formula that we used previously.

Since we've titled the function calcInterest, we want to return only the amount of interest accrued (not the total principal + interest). So, we create a new variable called interestAmt, and set it equal to the total amount minus the principal.

Printing the output

Now that we have our function defined, we can work on the part of the program that the user will ultimately see after it runs.

# print output
totalInterest = calcInterest(principal, interest_rate, time_period, compounding_frequency)

print("Total interest accrued: $", round(totalInterest, 2))
Enter fullscreen mode Exit fullscreen mode

Here we created another variable called totalInterest. It is set equal to the output of our function, calcInterest when the necessary parameters have been passed through. Each of these parameters (principal, interest rate, time period, and compounding frequency) will be collected at the very beginning of the program when they are assigned from the user's input.

Finally, the program will print the total interest. But we've made it into a more human message.

The final output of the program reads:

Total interest accrued $[totalInterest]

Another point worth noting is our inclusion of the built-in function round(). This function allows us to choose what nearest number to round to. By specifying round(totalInterest, 2) we ensure that the number that gets printed out is rounded to the nearest hundredth, and that it accurately represents a dollar amount.

Testing the finished code

Below is the completed code for our entire program in the Python programming language.

def calcInterest(principal, interest_rate, time_period, frequency):
    amount = principal * (1 + (interest_rate / compounding_frequency)) ** (compounding_frequency * time_period)
    interestAmt = amount - principal
    return interestAmt


# get user input

## Enter the principal amount
principal = float(input())

## Enter the interest rate as a decimal
interest_rate = float(input())

## Enter the time period
time_period = float(input())

## Enter the compounding frequency in years
compounding_frequency = float(input())

# print out
totalInterest = calcInterest(principal, interest_rate, time_period, compounding_frequency)

print('Total interest accrued',round(totalInterest, 2))
Enter fullscreen mode Exit fullscreen mode

Now, we can test our program against the CalculatorSoup.com web app – using the same parameters for both:

  • Principal = 1000
  • Interest rate = .04
  • Time period = 5
  • Compounding frequency = 1

Our program returns that the total interest accrued is $216.65, which is the same value given by the website.

The way that we built this program is that we can reuse this multiple times, we don't have to change the numbers specifically within the program to rerun it.

So, we can rerun this over and over with different values. Try some bigger numbers this time:

  • Principal = $10,000
  • Interest rate = .05
  • Time period = 20
  • compounding frequency = 1

We see that our total interest accrued is over $16,000. If we match that against the web application, we see that we again get the same value.

Python 101 wrap up: What's next?

Congratulations, you just wrote your first Python program — and you got a little smarter about personal finance too!

If you want to start learning even more about Python: check out our brand-new course Python for Absolute Beginners. It goes more in depth with the basics that we discussed today, but you'll eventually be able to build your own complex programs from scratch!

Here at Educative.io we have over hundreds completely interactive courses spanning programming languages, web development, data science, system design and interview prep. Each course features a pre-built development environment that lets you code directly in the browser, as you saw demonstrated in this post, so you don't have to configure anything.

We offer beginner coding courses in a bunch of other languages (Java, JavaScript, C++, Go, etc.). So, if you want to learn something a little different, you can activate a seven-day free trial!

Happy learning!

Start a discussion

What Python skill would you like to learn next? Was this article helpful? Let us know in the comments below!

Top comments (0)