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:
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:
Learn Python 3 from Scratch
This course focuses exclusively on teaching Python to beginners and demystifies procedural programming, grounding every new concept in the hands-on project they gradually build with the course. You will begin by understanding built-in functions for input and output, and then move on to user-defined functions. Moreover, you will learn the basic data types and their application. Next, you will learn about the various structures of programs you can write: sequential, selective, and iterative; eventually, you will apply everything you’ve learned to complete an interesting project. More than anything else, this course aims to make you a lifelong learner, and intends to act as a great start to your wonderful career in the world of computing.

What will you cover in this Python tutorial?
You’re not just learning syntax here—you’re learning how to think like a programmer. This tutorial follows a structured, hands-on approach:
Start with the basics: Understand variables, data types, and operators with easy-to-follow examples.
Control your code: Learn conditional statements and loops to make your programs smart and dynamic.
Work with data: Explore lists, dictionaries, and files to handle real-world information.
Make it interactive: Master user input and functions to create programs that respond to real users.
Hands-on practice: Solve problems, complete exercises, and build small projects to reinforce what you learn!
Meet Alex and his backpack:
Alex is a student who carries a digital backpack to school. In this backpack, he keeps notebooks, pens, and snacks. Just like Alex organizes his belongings, Python uses variables to store and manage information.
A variable in Python is like a labeled pocket in Alex’s backpack. Each pocket holds specific items, such as:
A notebook labeled "math_notes" (stores math-related notes )
A water bottle labeled "water" (stores drinking water)
A lunchbox labeled "lunch" (stores food)
Similarly, in Python, variables hold different types of data:
Here, "math_notes" stores text (string), "water" stores a number (integer), and "lunch" also stores text (string).
Alex can replace his notebook with a new one when the old one is full. Similarly, in Python, you can reassign a variable to store a new value:
Python variables are flexible—just like Alex’s backpack contents can change!
When Alex buys a snack, he updates his backpack. He can ask his friend for a suggestion and then add it. In Python, we can take user input and store it in a variable:
This lets the user decide what Alex should put in his backpack!
Task: Let’s try adding some input, like chocolate, and press the “Run” button to see what is printed on the screen.
Let’s talk about local and global variables using Alex’s daily routine.
Local variables
Alex uses a notebook only in the classroom (it belongs to one specific subject).
In Python, a local variable exists only inside a function.
Line 2: subject_notes only exists inside the study() function, just like Alex’s school notebook is only used in class.
Global variables
Alex carries his water bottle everywhere to use anytime during the day.
A global variable is accessible throughout the program.
Line 1: The water_bottle variable can be accessed and updated inside and outside the function.
Alex can combine things in his backpack, like adding two snacks together. In Python, we can perform operations on variables:
Just like Alex counts how many snacks he has, Python can perform operations on numbers.
Task: Guess the total number of fruits before running the code. Click the “Run” button and check if you are right!
Alex organizes his backpack by checking if an item is a notebook, a snack, or a water bottle. Similarly, in Python, we can check a variable’s data type using type():
Task: Add a new variable with a 30.5 value, such as the price of a meal. Then, print its type using the type() function to verify it is a float.
Sometimes, Alex wants to measure his water in liters instead of milliliters. In Python, we can convert data types using type casting:
Like Alex changes units, Python allows us to convert numbers to strings, integers to floats, and more!
Alex’s identity number stays the same in school, like his school ID card number. In Python, we use constants (written in uppercase) for values that should not change:
Note: Python doesn’t enforce constants; using uppercase helps indicate that a variable should remain unchanged.
What have you learned?
Variables
Declaration and reassignment
Input and output variables
Local and global variables
Operations on variables
Type of a Python variable
Type casting variables
Constants
Hands-on exercise
Meet Emma and her digital organizer:
A social media manager, Emma organizes her daily tasks using a digital organizer. She handles posts, keeps track of followers, manages brand collaborations, and ensures everything runs smoothly.
Just like Emma uses different tools to store and manage data, Python has data types to store information efficiently.
Think of Emma’s digital organizer as Python’s data types:
Numbers track her total followers and engagement. 📊
Text stores captions and hashtags. 📝
Lists and tuples organize daily tasks. 📅
Dictionaries hold client details. 📂
Sets manage unique hashtags. 🔖
Let’s explore these data types with Emma’s real-world tasks.
Primitive data types store individual information like Emma’s dashboard shows basic statistics.
Type | Example | Emma’s Use Case |
Integer |
| Keeps track of total followers. |
Float |
| Measures engagement percentage. |
String |
| Stores captions for posts. |
Boolean |
| Checks if a post is scheduled. |
Example in Python
Here are the building blocks Emma uses daily:
Task: Add a new variable to store the number of likes on the post as an integer. Then, print the likes and existing details to see the complete post insights.
Emma doesn’t work with just one post or one client—she needs to organize multiple pieces of information. Python provides compound data types for structured storage.
Data Type | Example | Emma’s Use Case |
List |
| Stores daily tasks. |
Tuple |
| Holds fixed weekly schedule. |
Dictionary |
| Stores client details. |
Set |
| Stores unique hashtags. |
Emma’s to-do list changes daily. She can add, remove, or update tasks. Similarly, a list in Python is mutable and ordered.
Example in Python:
Task: Add another task to the list, such as "Check analytics", and then print the updated task list to see all planned activities for the day.
Just like Emma can update her to-do list, Python allows modifying lists.
Emma’s workweek follows a set pattern:
Monday: Content brainstorming
Tuesday: Video editing
Wednesday: Client meetings
We use a tuple (an immutable collection) as this schedule doesn’t change.
Example in Python:
Like Emma’s preset weekly tasks, tuples are fixed and cannot be modified.
Task: Add "Thursday" to the week_schedule tuple and print the updated weekly plan. As tuples are immutable, consider an alternative approach to modify the schedule.
Emma works with multiple brands. She stores details like client name, number of followers, and preferred hashtags using a dictionary, where each piece of information is stored as a key-value pair.
Let’s look at the following illustration of a client dictionary with key-value pairs:
Example in Python:
Sets automatically remove duplicates, helping Emma keep her posts clean and optimized.
What have you learned?
Python data types
Primitive data types
Compound data types
Lists, tuples, dictionaries, and sets
Hands-on exercise
Imagine you’re planning a grocery shopping trip. You must make a list of items, update it as needed, remove things you no longer want, and organize your list efficiently.
In Python, lists work similarly, helping you easily store and manage collections of items.
Before heading to the store, you jot down a list of essentials:
A list in Python is created using square brackets [], just like a real shopping list where you list multiple items.
Task: Add a new item to grocery_list and print the updated list.
You might want to check if you’ve added a specific item. In Python, you can access list items by their position:
You can access elements using index numbers like looking at the first and last items on your shopping list.
Oops! You forgot to add butter to your list. You can easily add it:
Just like you can write new items in your notebook, Python lets you add elements dynamically.
Maybe you prefer almond milk instead of regular milk. You can update the list accordingly:
Lists allow modifications, like crossing out an item and replacing it on your shopping list.
If you already have eggs at home, you can remove them from the list:
You may want to focus on only the first three items from the list:
List slicing helps you extract specific parts of your data, just like focusing on priority items.
If you want to highlight only fresh items and ignore packaged food, you can filter the list:
List comprehension helps filter and transform data efficiently, like refining your grocery list.
Task: Modify the grocery_list to include "Butter" and "Cheese", then run the code to check if they are filtered correctly.
Some useful list methods include:
Like organizing your shopping list alphabetically or by categories, list methods help in efficient data management.
Task: Add two more grocery items to the list before sorting and reversing. Then, run the code to check the updated count of items.
What have you learned?
Python lists
Creating lists
Accessing lists
Adding to lists
Modifying lists
Deleting from lists
List slicing
List comprehension
List methods
Hands-on exercise
Meet Jake, the game developer:
Jake is a game developer working on a new adventure game. His game has multiple features, such as player movement, enemy AI, and scoring systems. To make his code clear and organized, Jake uses comments in Python, just like game developers leave notes in design documents.
Let’s explore Python comments by stepping into Jake’s world!
Imagine Jake works on a game today but revisits the code after months—will he remember every detail?
Comments help Jake and his team:
Understand complex logic quickly
Collaborate with others effectively
Debug and update code efficiently
Python provides different types of comments to keep code readable and structured.
Single-line comments help Jake briefly explain what each part of the game does.
Example in Python:
Inline comments provide quick explanations next to the code without adding extra lines.
Example in Python:
Jake uses inline comments when he doesn’t need a full explanation but wants quick context.
Jake uses multi-line comments to document complex game logic properly when he writes complex game logic.
Example in Python:
Multi-line comments help explain entire sections, just like a game design document.
What have you learned?
Python comments
Single-line comments
Inline comments
Commenting code
Multi-line comments
Hands-on exercise
Meet Alex’s smart home:
Alex’s smart home system controls lights, temperature, and security. It makes decisions based on True/False conditions, like Python’s boolean values (True or False).
Let’s explore Python booleans by stepping into Alex’s world!
Booleans are like the ON/OFF switches in Alex’s smart home.
If the lights are ON, the system sees it as True.
If the lights are OFF, the system sees it as False.
Example in Python:
Booleans represent True or False values.
Just like in a smart home, booleans helps make decisions in Python.
The bool() method converts values into True or False. Alex’s smart home checks whether it’s night before turning on the lights.
Example in Python:
The bool() function helps check conditions like a home automation system!
Alex’s smart home must decide when to turn on heating or lock doors.
Booleans help by evaluating expressions using comparison operators (>, <, ==, !=).
Example in Python:
The system evaluates conditions to take action—just like Python booleans!
In Python, True is 1, and False is 0. Alex’s electricity bill calculator uses booleans in mathematical operations!
Example in Python:
This works because booleans behave like integers in calculations!
Task: Add another boolean variable for a powered device, such as ac_on, and update the total_devices calculation. Run the code to see the new total count.
What have you learned?
Python booleans
The bool() method
Evaluating expressions
Subtype of Int
Hands-on Exercise
Meet Mia’s coffee shop:
Mia owns a small coffee shop and manages orders, pricing, and customer discounts. Python operators help Mia calculate costs, compare prices, and check loyalty memberships.
Let’s explore Python operators using Mia’s coffee shop as an example.
Mia uses arithmetic operators (+, -, *, /, //, %, **) to calculate customer bills.
Example in Python:
Task: Add a new item, such as a sandwich, with its price, and update the total_bill calculation. Run the code to see the new total amount.
Mia also offers a combo discount using multiplication:
Mia needs to track coffee bean stock using assignment operators (=, +=, -=, *=, etc.).
Example in Python:
Assignment operators help update values efficiently!
Task: A new shipment of 20 coffee packs has arrived. Update the coffee_stock accordingly and print the new stock level.
Mia offers discounts for orders above $10 using comparison operators (>, <, >=, <=, ==, !=).
Example in Python:
Comparison operators help compare prices and apply discounts!
Task: A special discount applies only if the bill exceeds $15. Modify the code to check if the customer qualifies for this new discount and print the result.
Mia wants to offer a special deal if a customer buys a coffee and cake. Logical operators (and, or, not) help!
Example in Python:
Task: The café now offers a discount on coffee or cake purchases. Modify the code to check if the customer qualifies for this new offer and print the result.
Mia’s shop accepts different payment methods. She needs to verify if a customer used cash or a card using identity operators (is, is not).
Example in Python:
Identity operators help compare specific values or objects!
Mia has a VIP customer list and needs to check if a customer is a member using membership operators (in, not in).
Example in Python:
Mia uses bitwise operators (&, |, ^, <<, >>) to track stock using binary operations.
Example in Python:
Bitwise operations are useful for efficient inventory tracking!
Mia must ensure the order of operations follows PEMDAS (parentheses, exponents, multiplication/division, addition/subtraction).
Example in Python:
Proper precedence helps avoid miscalculations in pricing!
What have you learned?
Python operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Operator precedence and associativity
Hands-on exercise
Imagine Emma has a morning checklist:
Wake up ☀️
Make coffee ☕
Read emails 📧
Go for a jog 🏃♀️
She follows these steps every day—just like a loop in Python! Python loops automate repetitive tasks, making them efficient and error-free.
A for loop repeats actions a fixed number of times—like checking off each task on Emma’s checklist.
Example:
How it works:
The loop goes through each item in tasks.
It prints every task until the list is complete.
A while loop keeps running until a condition is met—like sipping coffee until the cup is empty.
Example:
How it works:
The loop runs until coffee_sips reaches 0.
Each sip reduces the count, and when it’s gone, the loop stops.
You can control loops using:
break: Stops the loop early.
continue: Skips a step but keeps looping.
pass: A placeholder to do nothing.
Example:
Task: The email filter should skip spam instead of stopping completely. Modify the code to continue checking other emails even after detecting spam.
What have you learned?
Python for loops
Python while loops
Loop control statements (break, continue, pass)
Now 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.)
Before we start writing this formula as Python code, let’s set up our program so that it takes 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.
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.
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:
int: A whole number with no decimal point. Example: 5float: A number with a decimal point. Example: 3.14bool: A data type with only two possible values: True or False. Used in logical operations and control statements.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.
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.
When we write this out as code, the formula looks like this:
Let’s cover these mathematical operators in Python.
* operator: multiply\ operator: divide** operator: raise to the power ofNow, we can check our work against the website that we looked at in the beginning.
Let’s run this program using the same parameters we ran on the website.
Our value of 1,216.65 is the same as what we got on the website. So that’s good progress!
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.
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.
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.
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.
Start learning Python in your browser today
This course uses an active learning approach to teach Python programming to beginners. You’ll interact with the code from the start, using everyday logic and fun challenges to build confidence. You will learn essential programming concepts through interactive examples and mini projects like input/output, decision-making, error handling, and simple logic. Whether new to coding or just starting with Python, this course provides the perfect foundation to develop your problem-solving skills and easily write your programs. More than anything else, this course aims to make you a lifelong learner and serve as a strong starting point for a successful career in computing. You don’t need any programming experience to begin.
Below is the completed code for our entire program in the Python programming language.
Now, we can test our program against the CalculatorSoup.com web app – using the same parameters for both:
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:
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.
Before you dive into writing your first program, make sure you’re using the latest version of Python — Python 3.10 or newer. Python 2 is no longer supported, and almost every modern library relies on Python 3 features.
A few best practices to start with:
Always run your scripts with python3 instead of python.
Use f-strings for clean, readable output:
print(f"Your total interest is: {interest:.2f}")
Follow PEP 8, Python’s official style guide. It helps you write readable, professional-quality code.
Modern Python uses type annotations to make code easier to understand and catch errors early. Type hints don’t change how your program runs — they’re just a guide for humans and tools.
Here’s how your interest calculation function might look with type hints:
def calc_interest(principal: float, rate: float, time: float, freq: int) -> float:return principal * (1 + rate / freq) ** (freq * time)
This tells anyone reading your code — and tools like linters or IDEs — exactly what type of input the function expects and what it returns.
In the original example, the program assumes users will enter valid numbers. In real programs, that’s not always the case. It’s good practice to validate and handle errors gracefully:
try:principal = float(input("Enter the principal amount: "))rate = float(input("Enter the annual interest rate (as a decimal): "))time = float(input("Enter the time in years: "))freq = int(input("Enter the number of times interest is compounded per year: "))except ValueError:print("Oops! Please enter valid numeric values.")exit(1)
This approach prevents your program from crashing and gives the user helpful feedback.
When dealing with financial calculations, small floating-point errors can accumulate. For higher precision, you can use the decimal module:
from decimal import Decimalprincipal = Decimal("1000.00")rate = Decimal("0.05")time = Decimal("5")freq = Decimal("4")interest = principal * (1 + rate / freq) ** (freq * time)
It’s a simple change that makes your calculations more reliable — especially when working with money.
As your programs grow, structuring them properly becomes essential. One best practice is to include a main guard so your script can be imported without running automatically:
if __name__ == "__main__":total = calc_interest(principal, rate, time, freq)print(f"The total amount after {time} years is: {total:.2f}")
This makes your code more modular and easier to reuse in other projects.
Manual testing with print statements is fine for learning, but in real projects, automated tests are the norm. Python’s built-in unittest module is a great place to start:
import unittestclass TestCalcInterest(unittest.TestCase):def test_interest(self):self.assertAlmostEqual(calc_interest(1000, 0.05, 5, 4), 1283.36, places=2)if __name__ == "__main__":unittest.main()
Running tests ensures your program works even after you make changes — and it’s a key part of professional development workflows.
When you start working on more Python projects, you’ll likely install external libraries. To avoid conflicts between them, always use a virtual environment:
python3 -m venv envsource env/bin/activate # Mac/Linuxenv\Scripts\activate # Windows
This keeps each project isolated and easier to manage.
Interactive input() is great for beginners, but professional scripts often use command-line arguments so they can run automatically. Python’s argparse module makes this easy:
import argparseparser = argparse.ArgumentParser()parser.add_argument("principal", type=float)parser.add_argument("rate", type=float)parser.add_argument("time", type=float)parser.add_argument("freq", type=int)args = parser.parse_args()total = calc_interest(args.principal, args.rate, args.time, args.freq)print(f"The total amount is: {total:.2f}")
This makes your program more flexible and easier to integrate into automated systems.
Even small projects benefit from tools that keep your code clean and consistent. Try these:
Black – automatically formats your code.
Flake8 – checks for style violations.
Pylint – analyzes your code for potential errors.
These tools make your code easier to read, debug, and maintain — and they’re widely used in real-world projects.
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 Learn Python. 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. You can even start by building a simple number guessing game in Python Tkinter.
We offer beginner coding courses in a bunch of other languages (Java, JavaScript, C++, C#, Ruby, etc.). So, if you want to learn something a little different, you can activate a seven-day free trial!
Happy learning!