You can learn the basics of Python in 7 days, but mastering it takes time. You can cover basic concepts like variables, loops, functions, and simple programs in a week. However, real proficiency comes with practice and hands-on projects.
Have you ever wanted to build your app, automate boring tasks, or explore artificial intelligence? Python makes it all possibleâeven if youâve never written a single line of code! Known for its simple syntax and powerful capabilities.
Python is the go-to language for web development, data science, and machine learning. Whether youâre a software engineer or just curious about coding, learning Python can unlock endless career opportunities.
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!
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.
Python is one of the worldâs most beginner-friendly and versatile programming languages. Hereâs why:
Easy to learn: Pythonâs simple, readable syntax makes it perfect for beginners. If you can write basic English sentences, you can learn Python!
High demand in tech: Companies like Google, Netflix, and Instagram use Python for AI, automation, and web development. Learning Python boosts your job prospects!
Used everywhere: Python powers websites, apps, data science, cybersecurity, automation, and even robots! No matter your interests, Python has a place for you.
Suppose youâre at a coffee shop, ordering your favorite drink. You tell the barista your order (input), and after a few moments, they hand you the drink (output). This is exactly how Python handles input and outputâitâs a two-way communication where you provide data, and Python responds with results.
When you order coffee, you provide details like the type of coffee, size, and any customizations. In Python, we use the input()
function to collect information from the user:
name = input("Enter your name: ")drink = input("What coffee would you like? ")print("Order received for", name, "-", drink)
Enter the input below
As a barista waits for your response before preparing your drink, Python waits for the userâs input before proceeding.
Task: Letâs try to add some input like mocca and press the âRunâ button to see what is printed on the screen.
Once your coffee is ready, the barista calls out your name and hands you the drink. In Python, we use the print()
function to display messages, results, or calculations:
print("Your coffee is ready! Enjoy!")
What have you learned?
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:
math_notes = "Algebra formulas"water = 500lunch = "Sandwich"
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:
math_notes = "Geometry formulas" # Reassigning a new valuewater = 750 # Updating the water quantity
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:
snack = input("What snack should I pack today? ")print("You packed:", snack)
Enter the input below
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.
def study():subject_notes = "Physics notes" # Local variableprint("Studying:", subject_notes)study()print(subject_notes) # This will cause an error!
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.
water_bottle = 1000 # Global variabledef drink_water():global water_bottlewater_bottle -= 250 # Drinking 250ml of waterprint("Remaining water:", water_bottle, "ml")drink_water()print("Water left for the day:", water_bottle, "ml")
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:
apple = 1banana = 2total_fruits = apple + banana # Addition operationprint("Total fruits packed:", total_fruits)
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()
:
math_notes = "Algebra formulas"water = 500lunch = "Sandwich"print(type(math_notes)) # <class 'str'>print(type(water)) # <class 'int'>print(type(lunch)) # <class 'str'>
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:
x = "100"y = int(x) # Converts string to integerprint(y, type(y)) # Output: 100 <class 'int'>
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:
SCHOOL_ID = "F2025001"
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:
followers = 5000 # Integerengagement_rate = 3.5 # Floatpost_caption = "New blog is live!" # Stringis_scheduled = True # Booleanprint("Followers:", followers)print("Engagement Rate:", engagement_rate, "%")print("Post Caption:", post_caption)print("Is Post Scheduled?", is_scheduled)
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:
tasks = ["Write post", "Edit video", "Reply to comments"]tasks.append("Schedule story") # Adding a new taskprint("Today's Tasks:", tasks)
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:
week_schedule = ("Monday", "Tuesday", "Wednesday")print("Emmaâs Weekly Plan:", week_schedule)
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:
client = {"name": "BrandX","followers": 20000,"hashtags": ["#marketing", "#business"]}print("Client Name:", client["name"])print("Followers:", client["followers"])print("Hashtags:", client["hashtags"])
hashtags = {"#socialmedia", "#growth", "#branding", "#growth"}
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:
grocery_list = ["Milk", "Eggs", "Bread", "Bananas"]print(grocery_list)
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:
print(grocery_list[0]) # Output: Milkprint(grocery_list[-1]) # Output: Bananas
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:
grocery_list.append("Butter") # Adds to the endgrocery_list.insert(2, "Cheese") # Adds at a specific position
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:
grocery_list[0] = "Almond Milk"
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:
grocery_list.remove("Eggs") # Removes by valuedel grocery_list[1] # Removes by index
You may want to focus on only the first three items from the list:
essentials = grocery_list[:3] # Get first three items
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:
grocery_list = ["Milk", "Eggs", "Bread", "Bananas"]fresh_items = [item for item in grocery_list if item not in ["Butter", "Cheese"]]print(fresh_items)
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:
grocery_list = ["Milk", "Eggs", "Bread", "Bananas"]grocery_list.sort() # Sorts items alphabeticallygrocery_list.reverse() # Reverses the orderprint(len(grocery_list)) # Finds the number of items
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:
# Initialize playerâs healthplayer_health = 100# Set enemy speedenemy_speed = 5
Inline comments provide quick explanations next to the code without adding extra lines.
Example in Python:
player_score = 0 # Score starts at zeroenemy_count = 3 # Three enemies spawn initially
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:
"""This function controls player movement.- Left arrow: Move left- Right arrow: Move right- Spacebar: Jump"""def move_player():pass # Movement logic will go here
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.
lights_on = Truedoor_locked = False
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:
is_night = bool("dark outside") # Any non-empty string is Trueprint(is_night) # Output: True
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:
temperature = 15heater_on = temperature < 18 # Turn on the heater if the temp is belowprint(heater_on) # Output: True
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:
lights_on = True # Internally, True is 1fans_on = False # Internally, False is 0# Total powered devicestotal_devices = lights_on + fans_onprint(total_devices) # Output: 1
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:
coffee_price = 5cake_price = 3total_bill = coffee_price + cake_price # Adding pricesprint("Total Bill:", total_bill) # Output: 8
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:
discount = 2discounted_price = total_bill - discount # Applying discountprint("Discounted Price:", discounted_price) # Output: 6
Mia needs to track coffee bean stock using assignment operators (=
, +=
, -=
, *=
, etc.).
Example in Python:
coffee_stock = 100coffee_stock -= 10 # Sold 10 cupsprint("Remaining Coffee Stock:", coffee_stock) # Output: 90
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:
customer_bill = 12discount_eligible = customer_bill > 10print("Eligible for Discount:", discount_eligible) # Output: True
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:
bought_coffee = Truebought_cake = Truespecial_deal = bought_coffee and bought_cakeprint("Gets Special Deal:", special_deal) # Output: True
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:
payment_method = "cash"print(payment_method is "cash") # Output: Trueprint(payment_method is not "card") # Output: True
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:
vip_customers = ["Alice", "Bob", "Charlie"]customer = "Alice"print(customer in vip_customers) # Output: Trueprint("David" not in vip_customers) # Output: True
Mia uses bitwise operators (&
, |
, ^
, <<
, >>
) to track stock using binary operations.
Example in Python:
coffee_stock = 0b110 # Binary representation (6 in decimal)cake_stock = 0b101 # Binary representation (5 in decimal)total_stock = coffee_stock | cake_stock # Bitwise ORprint(bin(total_stock)) # Output: 0b111 (7 in decimal)
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:
total_cost = 5 + 3 * 2 # Multiplication happens firstprint(total_cost) # Output: 11total_cost = (5 + 3) * 2 # Parentheses firstprint(total_cost) # Output: 16
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:
tasks = ["Wake up", "Make coffee", "Read emails", "Go for a jog"]for task in tasks:print("Task Completed:", task)
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:
coffee_sips = 5while coffee_sips > 0:print("Sipping coffee... â")coffee_sips -= 1 # Reduce sips each timeprint("Coffee finished!")
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:
emails = ["Work Update", "Meeting Invite", "Spam", "Newsletter"]for email in emails:if email == "Spam":print("Spam detected! Stopping check.")break # Stops the loopprint("Checking:", email)
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)
You've taken your first steps on the road to mastering Python! If youâre ready to choose your career path after learning the basics of Python, here are some Python courses designed to guide you step by step:
Can I learn Python in 7 days?
What is the best tutorial for Python?
Is 2 hours a day enough to learn Python?
Is Python easy to learn?
How should a beginner learn Python?
Can I learn Python in 30 days?
Is Python easier than C++?
Can I learn Python at 45 and get a job?
Free Resources