Python 101 tutorial: Write your first real program in 10-minutes
Learn how gather user input, convert data types, and declare a function in Python. By the end you'll have your very own compound interest calculator!
This tutorial is originally from the Educative Blog
Learning to code is no small task.
I have found that many learners either don't know how to start learning to code, or immediately get discouraged upon starting. There are so many approaches to learning programming that I often find the lessons don't end up sticking, even if you come in highly motivated and ready to learn. I also see computer science students in four-year degree settings emerge unprepared for what real, professional software development is like.
Initially, you don't have to stress about setting up your development environment or diving into the deep end with while loops. To help learners find balance, I wanted to illuminate that you can build useful programs as a complete novice.
That's why I'm using this week's newsletter to teach all of the beginners out there meaningful coding skills in just a few minutes.
I'll walk you through writing your first Python program that does more than just print Hello world. You'll learn real software engineering fundamentals like:
Collecting user input
Converting data types
Performing advanced calculations
Defining a reusable function
Since this is on SubStack, you won't be able to execute the code. Visit this Python 101 blog post if you want to follow along yourself.
Our blog contains interactive code widgets, so you can execute the program right in your browser without having to set up any development environment. Or, check out the video below for a step-by-step breakdown.
Let's get started!
Why Python?
I often recommend Python to beginners because it helps teach the fundamentals without throwing you into the deep end.
As a programming language, it is readable and simple to debug. It has an incredibly large offering of pre-built libraries that greatly expand its functionality. Think of Python like a high-powered multi-tool: it is intuitive to use and easy to modify.
Python is also the fastest growing programming language in the world. This is because it's perfectly suited for beginners, and also because it is used across so many different fields. Python is particularly popular in data science, data visualization, automation, scientific computing, web development, as well as AI and machine learning.
Get hands-on with Python today
Start writing real, practical programs that do more than just print "Hello world!" With Educative, you can get started immediately right in your browser window — without setting up a development environment.
Compound interest calculator
For this project, we'll build a compound interest calculator. This calculator will take four values from user input and return the total interest accrued over the course of a given time period.
Below is the entirety of the completed project.
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 inputs
principal = float(input("Enter the principal amount: "))
interest_rate = float(input("Enter the interest rate as a decimal: "))
time_period = float(input("Enter the time period: "))
compounding_frequency = float(input("Enter the compounding frequency in years: "))
# print out
totalInterest = calcInterest(principal, interest_rate, time_period, compounding_frequency)
print('Total interest accrued: $',round(totalInterest, 2))
As mentioned above, you can experiment with this code yourself on our blog, but I'll break it down and explain each block in this post as well.
1) Compound interest formula
Don't jump straight into writing code, do some research to determine how to solve the problem first.
Before I start dissecting the code itself, let's walk through the real-world compound interest formula that we started with for this program.
This formula is one that you can just find on Google, but it is surprisingly complex.
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 translate this formula into code, we'll need to collect the values from the user.
2) Collecting user input
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
principal = float(input("Enter the principal amount: "))
interest_rate = float(input("Enter the interest rate as a decimal: "))
time_period = float(input("Enter the time period: "))
compounding_frequency = float(input("Enter the compounding frequency in years: "))
You'll notice that each input()
function is prepended by another function, float()
. The built-in float()
function serves to convert the data type of the input from a string into a float– a number with a decimal point.
Some examples of other data types are as follows:
Integer
int
: A whole number with no decimal point. Example: 5Float
float
: A number with a decimal point. Example: 3.14Boolean
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!”
3) Defining a function to calculate the result
Defining a function is a best practice for most complex programs.
def calcInterest(principal, interest_rate, time_period, frequency):
amount = principal * (1 + (interest_rate / compounding_frequency)) ** (compounding_frequency * time_period)
interestAmt = amount - principal
return interestAmt
To create a reusable function, always begin with the keyword, def
. The above function is named calcInterest
. Note that the line ends with a colon, and the parentheses contain all of the input parameters for this function. These are the variables that the function will accept as arguments.
The core math of the function is a recreation of the compound interest formula at the beginning of this newsletter. Each value will be filled in from the variables assigned to the user's input. (It is crucial to group values using parentheses, just like you would on a calculator!)
The Python operators used to write this equation are as follows:
* operator
: multiply\ operator
: divide** operator
: raise to the power of
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
.
The keyword return ends the function and selects the value that is communicated to the function's caller.
4) The final step: printing the output
To make the program user-friendly, we'll print a clean output and a readable, human message to contextualize it.
# print output
totalInterest = calcInterest(principal, interest_rate, time_period, compounding_frequency)
print("Total interest accrued: $", round(totalInterest, 2))
Here we created another variable called totalInterest
, and set it equal to the output of our function, calcInterest
when the necessary parameters have been passed through.
Finally, we have the program print out the total interest with a friendly message. It is important to note however, that in this print statement, we use a new built-in function called round()
. The syntax, round(totalInterest, 2)
, specifies that the program will round the final value off to the second decimal place.
Don't stop here — there is much more to learn!
I hope you enjoyed this quick look under the first layer of the Python onion. There is so much that this language is capable of that it is impossible to cover it all just in writing.
This step-by-step tutorial is emblematic of the basic workflow of professional developers around the world. First, determine the strategic/mathematical approach that will solve the problem. Then, define the variables and functions that the program will need to function. Finally, write the code that optimally drives the process.
If you're interested in more beginner-focused content, subscribe to our YouTube channel. We'll be posting a lot more frequently, and you won't want to miss out. Educative is the best place to learn to code — no setup required! Our brand new Learn to Code courses are available in the following programming languages:
Python
JavaScript
Java
C++
C#
Ruby
Let me know what you think of this tutorial newsletter format. Are there any other topics I should cover next?
As always, happy learning!