Home/Blog/Python tutorial for beginners
Home/Blog/Python tutorial for beginners

Python tutorial for beginners

14 min read
Apr 26, 2025
content
What is Python?
Python input
Python output
What are Python variables?
Declaration and reassignment
Input and output variables
Python local and global variables
Operations on variables
Type of a Python variable
Type casting variables
Constants
What are Python data types?
Primitive data types
Compound data types
Python lists
Python tuples
Python dictionaries
Python sets
Example in Python:
Python lists
Creating lists
Accessing lists
Adding to lists
Modifying lists
Delete items from lists
List slicing
List comprehension
List methods
Python comments
Why are Python comments important?
Types of Python comments
Single-line comments
Inline comments
Multi-line comments
Python booleans
The bool() method
Evaluating expressions
Booleans as a sub-type of integers
Python operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Operator precedence
Python loops
Python for loops
Python while loops
Loop control: break, continue, pass
Final Word

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:

  1. Start with the basics: Understand variables, data types, and operators with easy-to-follow examples.

  2. Control your code: Learn conditional statements and loops to make your programs smart and dynamic.

  3. Work with data: Explore lists, dictionaries, and files to handle real-world information.

  4. Make it interactive: Master user input and functions to create programs that respond to real users.

  5. Hands-on practice: Solve problems, complete exercises, and build small projects to reinforce what you learn!

Learn Python 3 from Scratch

Cover
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.

6hrs
Beginner
62 Playgrounds
5 Quizzes

What is Python?#

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.

Python input#

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.

Python output#

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?

Python input
Python output
Hands-on exercise

What are Python variables?#

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 = 500
lunch = "Sandwich"

Here, "math_notes" stores text (string), "water" stores a number (integer), and "lunch" also stores text (string).

Declaration and reassignment#

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 value
water = 750 # Updating the water quantity

Python variables are flexible—just like Alex’s backpack contents can change!

Input and output variables#

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.

Python local and global variables#

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 variable
print("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 variable
def drink_water():
global water_bottle
water_bottle -= 250 # Drinking 250ml of water
print("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.

Operations on variables#

Alex can combine things in his backpack, like adding two snacks together. In Python, we can perform operations on variables:

apple = 1
banana = 2
total_fruits = apple + banana # Addition operation
print("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!

Type of a Python variable#

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 = 500
lunch = "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.

Type casting variables#

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 integer
print(y, type(y)) # Output: 100 <class 'int'>

Like Alex changes units, Python allows us to convert numbers to strings, integers to floats, and more!

Constants#

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

What are Python data types?#

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#

Primitive data types store individual information like Emma’s dashboard shows basic statistics.

Type

Example

Emma’s Use Case

Integer

followers = 5000

Keeps track of total followers.

Float

engagement_rate = 3.5

Measures engagement percentage.

String

post_caption = "New blog is live!"

Stores captions for posts.

Boolean

is_scheduled = True

Checks if a post is scheduled.

Example in Python

Here are the building blocks Emma uses daily:

followers = 5000 # Integer
engagement_rate = 3.5 # Float
post_caption = "New blog is live!" # String
is_scheduled = True # Boolean
print("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.

Compound data types#

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

tasks = ["Write post", "Edit video", "Reply to comments"]

Stores daily tasks.

Tuple

week_schedule = ("Monday", "Tuesday", "Wednesday")

Holds fixed weekly schedule.

Dictionary

client = {"name": "BrandX", "followers": 20000}

Stores client details.

Set

hashtags = {"#socialmedia", "#growth", "#branding"}

Stores unique hashtags.


Python lists #

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 task
print("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.

Python tuples #

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.

Python dictionaries#

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:

Visualization of client dictionary
Visualization of client dictionary

Example in Python:

client = {
"name": "BrandX",
"followers": 20000,
"hashtags": ["#marketing", "#business"]
}
print("Client Name:", client["name"])
print("Followers:", client["followers"])
print("Hashtags:", client["hashtags"])

Task: Add a new hashtag to the hashtags list inside the client dictionary and print the updated list of hashtags.

Python sets#

Emma avoids duplicate hashtags in her posts. A set ensures unique hashtags are stored.

Example in Python:#
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

Python lists#

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.

Creating lists#

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.

Accessing lists#

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: Milk
print(grocery_list[-1]) # Output: Bananas

You can access elements using index numbers like looking at the first and last items on your shopping list.

Adding to lists#

Oops! You forgot to add butter to your list. You can easily add it:

grocery_list.append("Butter") # Adds to the end
grocery_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.

Modifying lists#

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.

Delete items from lists#

If you already have eggs at home, you can remove them from the list:

grocery_list.remove("Eggs") # Removes by value
del grocery_list[1] # Removes by index

List slicing#

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.

List comprehension#

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.

List methods#

Some useful list methods include:

grocery_list = ["Milk", "Eggs", "Bread", "Bananas"]
grocery_list.sort() # Sorts items alphabetically
grocery_list.reverse() # Reverses the order
print(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

Python comments#

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!

Why are Python comments important?#

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

Types of Python comments#

Python provides different types of comments to keep code readable and structured.

Single-line comments#

Single-line comments help Jake briefly explain what each part of the game does.

Example in Python:

# Initialize player’s health
player_health = 100
# Set enemy speed
enemy_speed = 5

Inline comments#

Inline comments provide quick explanations next to the code without adding extra lines.

Example in Python:

player_score = 0 # Score starts at zero
enemy_count = 3 # Three enemies spawn initially

Jake uses inline comments when he doesn’t need a full explanation but wants quick context.

Multi-line comments#

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

Python booleans#

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 = True
door_locked = False

Just like in a smart home, booleans helps make decisions in Python.

The bool() method#

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 True
print(is_night) # Output: True

The bool() function helps check conditions like a home automation system!

Evaluating expressions#

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 = 15
heater_on = temperature < 18 # Turn on the heater if the temp is below
print(heater_on) # Output: True

The system evaluates conditions to take action—just like Python booleans!

Booleans as a sub-type of integers #

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 1
fans_on = False # Internally, False is 0
# Total powered devices
total_devices = lights_on + fans_on
print(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

Python operators#

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.

Arithmetic operators#

Mia uses arithmetic operators (+, -, *, /, //, %, **) to calculate customer bills.

Example in Python:

coffee_price = 5
cake_price = 3
total_bill = coffee_price + cake_price # Adding prices
print("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 = 2
discounted_price = total_bill - discount # Applying discount
print("Discounted Price:", discounted_price) # Output: 6

Assignment operators#

Mia needs to track coffee bean stock using assignment operators (=, +=, -=, *=, etc.).

Example in Python:

coffee_stock = 100
coffee_stock -= 10 # Sold 10 cups
print("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.

Comparison operators#

Mia offers discounts for orders above $10 using comparison operators (>, <, >=, <=, ==, !=).

Example in Python:

customer_bill = 12
discount_eligible = customer_bill > 10
print("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.

Logical operators#

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 = True
bought_cake = True
special_deal = bought_coffee and bought_cake
print("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.

Identity operators#

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: True
print(payment_method is not "card") # Output: True

Identity operators help compare specific values or objects!

Membership operators#

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: True
print("David" not in vip_customers) # Output: True

Bitwise operators#

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 OR
print(bin(total_stock)) # Output: 0b111 (7 in decimal)

Bitwise operations are useful for efficient inventory tracking!

Operator precedence#

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 first
print(total_cost) # Output: 11
total_cost = (5 + 3) * 2 # Parentheses first
print(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

Python loops#

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.

Python for loops#

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.

Python while loops#

A while loop keeps running until a condition is met—like sipping coffee until the cup is empty.

Example:

coffee_sips = 5
while coffee_sips > 0:
print("Sipping coffee... ☕")
coffee_sips -= 1 # Reduce sips each time
print("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.

Loop control: break, continue, pass#

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 loop
print("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)

Final Word#

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:

Frequently Asked Questions

Can I learn Python in 7 days?

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.

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?


Written By:
Muhammad Usama

Free Resources