Beginner Python Tutorial: Learn Python Step by Step from Scratch
19 min read
Introduction
Python is one of the most popular programming languages in the world — and for good reason. It is simple to read, easy to learn, and powerful enough to build everything from small automation scripts to complex artificial intelligence systems.
This Beginner Python Tutorial was created for absolute beginners who want to learn Python step by step, without feeling overwhelmed. No prior programming experience is required.
By the end of this guide, you will understand the core fundamentals of Python, including variables, data types, loops, conditional statements, functions, modules, and popular Python libraries used in real-world projects.
📌 This guide is part of our Programming Hub and serves as a foundational resource for new developers.
Why Learn Python?
Python is often recommended as the best first programming language. Here’s why:
- Simple and readable syntax
- Massive community and learning resources
- Used in web development, data science, AI, automation, and more
- Cross-platform (Windows, macOS, Linux)
- High demand in the job market
Python is used by companies like Google, Netflix, Spotify, NASA, and Instagram.
Setting Up Python
Before writing your first Python code, you need to install Python.
How to Install Python
- Go to the official Python website
- Download the latest stable version (Official Page)
- Install Python and enable “Add Python to PATH”
- Verify installation by typing in your terminal:
python --version
Recommended Code Editors
- Visual Studio Code (VS Code)
- PyCharm Community Edition
- Sublime Text
💡 VS Code is highly recommended for beginners due to its simplicity and extensions.

Python Basics: Variables and Data Types
Variables store data in memory. Python does not require you to declare a variable type explicitly.
Creating Variables
name = "John"
age = 25
price = 19.99
is_student = True
Python automatically determines the data type.
Common Data Types in Python
| Data Type | Example |
|---|---|
| Integer | 10 |
| Float | 3.14 |
| String | "Hello" |
| Boolean | True, False |
| List | [1, 2, 3] |
| Tuple | (1, 2, 3) |
| Dictionary | {"name": "John"} |
Explanation of Variables and Data Types
In Python, variables are used to store information that can be reused and manipulated throughout the program. You create a variable by assigning a value to a name using the = symbol.
One of Python’s biggest advantages is that it is dynamically typed, which means you do not need to explicitly define the data type of a variable. Python automatically detects the type based on the value assigned.
For example:
"John"is recognized as a string25is recognized as an integer19.99is recognized as a floatTrueis recognized as a boolean
Understanding data types is essential because they determine what kind of operations you can perform on a variable. For instance, numbers can be used in calculations, while strings are commonly used to store text.
Python also provides powerful built-in data structures:
- Lists store multiple items in a single variable and are mutable (can be changed)
- Tuples are similar to lists but are immutable (cannot be changed)
- Dictionaries store data in key-value pairs, making them ideal for structured information
Mastering variables and data types is a fundamental step in learning Python, as they form the basis for more advanced concepts like loops, functions, and data analysis.
Type Checking
type(age)
This helps you understand what kind of data you are working with.
Explanation of Type Checking in Python
In Python, the type() function is used to check the data type of a variable. This is especially useful when you are learning the language or debugging your code.
When you run:
type(age)
Python returns the type of data stored in the variable age, such as:
<class 'int'>for integers<class 'float'>for decimal numbers<class 'str'>for text (strings)<class 'bool'>for boolean values
Type checking helps you avoid errors and better understand how your program works. For example, you cannot perform mathematical operations on strings unless you convert them to numbers first.
Using type() is a great habit for beginners because it makes your code more predictable and easier to debug as your programs grow in complexity.

Conditional Statements (If, Else, Elif)
Conditional statements allow your program to make decisions.
Basic If Statement
age = 18
if age >= 18:
print("You are an adult")
Explanation of the Code
In this example, we are using a basic if statement to check a condition and make a decision based on it.
First, the variable age is created and assigned the value 18. A variable is used to store information that we can reuse later in the program.
Next, the if statement checks whether the value of age is greater than or equal to 18. The comparison operator >= means “greater than or equal to”.
If this condition is true, Python executes the code inside the if block. In this case, it prints the message “You are an adult” on the screen.
The colon (:) at the end of the if line tells Python that the next indented lines belong to the condition. Indentation is very important in Python because it defines which code runs when the condition is met.
Since the value of age is 18, the condition is true, and the message is displayed. If the value were less than 18, the message would not be printed.
This simple example shows how Python uses if statements to make decisions based on conditions.
If-Else Statement
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")
Explanation of the Code
In this example, we are using an if-else statement to handle two possible outcomes based on a condition.
First, the variable age is created and given the value 16. This value represents a person’s age and will be used to make a decision in the program.
The if statement checks whether the value of age is greater than or equal to 18. If this condition is true, the program prints the word “Adult”.
However, because the value of age is 16, the condition is false. When the condition in the if statement is not met, Python automatically executes the code inside the else block.
As a result, the program prints “Minor”, indicating that the person is under 18 years old.
The else statement is useful when you want the program to do something when the condition is not true. Together, if and else allow Python to choose between two different paths based on the data provided.
This structure is commonly used in real-world programs, such as age verification, login systems, and decision-making logic.
If-Elif-Else
score = 85
if score >= 90:
print("Excellent")
elif score >= 70:
print("Good")
else:
print("Needs improvement")
Explanation of the Code
In this example, we are using an if-elif-else statement to check multiple conditions and choose the correct result.
First, the variable score is created and assigned the value 85. This value represents a score or grade that will be evaluated by the program.
The program starts by checking the first condition: if score is greater than or equal to 90. If this condition is true, Python prints “Excellent” and stops checking the remaining conditions.
If the first condition is false, Python moves to the elif statement. The keyword elif means “else if”. Here, the program checks whether the score is greater than or equal to 70. Since 85 is greater than 70, this condition is true, and the program prints “Good”.
The else block is only executed if none of the previous conditions are true. In this case, the else block would print “Needs improvement”, but it is not executed because one of the earlier conditions was already satisfied.
This structure is useful when you need to handle more than two possible outcomes, such as grading systems, performance levels, or decision-based logic.
The program stops as soon as it finds the first true condition, which makes if-elif-else both efficient and easy to understand.
Loops in Python
Loops allow you to repeat tasks efficiently.
For Loop
for i in range(5):
print(i)
This prints numbers from 0 to 4.
Explanation of the Code
In this example, we are using a for loop to repeat an action multiple times.
The line for i in range(5): tells Python to loop through a sequence of numbers generated by the range(5) function. The range(5) function creates a sequence starting from 0 up to, but not including, 5.
This means the loop will run with the values 0, 1, 2, 3, and 4.
The variable i is used as a counter. Each time the loop runs, i takes the next value from the sequence.
Inside the loop, the print(i) statement prints the current value of i to the screen. Because this line is indented, it runs once for each iteration of the loop.
As a result, the program prints the numbers from 0 to 4, each on a new line.
for loops are commonly used when you know in advance how many times you want to repeat an action, such as iterating through numbers, lists, or other collections of data.
While Loop
count = 0
while count < 5:
print(count)
count += 1
Explanation of the Code
In this example, we are using a while loop to repeat an action as long as a condition remains true.
First, the variable count is created and initialized with the value 0. This variable will be used to control how many times the loop runs.
The while count < 5: line tells Python to keep running the loop while the value of count is less than 5.
Inside the loop, the print(count) statement displays the current value of count on the screen. Because this line is indented, it runs every time the loop repeats.
The line count += 1 increases the value of count by 1 after each loop iteration. This step is very important because it ensures that the condition will eventually become false.
As count increases from 0 to 4, the loop continues running. When count reaches 5, the condition count < 5 becomes false, and the loop stops.
This example prints the numbers 0 to 4, just like the for loop example, but using a different approach.
while loops are useful when you don’t know in advance how many times the loop should run and want it to depend on a condition instead.
Loop Control Keywords
break→ exits the loopcontinue→ skips to the next iteration
for number in range(10):
if number == 5:
break
print(number)
Explanation of the Code
In this example, we are learning about loop control keywords, specifically break and continue, which are used to control how loops behave.
The for loop starts with the line for number in range(10):. This means the loop will go through the numbers from 0 to 9.
Inside the loop, there is an if statement that checks whether the value of number is equal to 5.
When the condition number == 5 becomes true, the break keyword is executed. The break statement immediately stops the loop, even if there are more values left to process.
Because of this, the loop prints the numbers 0, 1, 2, 3, and 4, and then exits when it reaches 5.
The print(number) line runs only while the loop is active and before the break condition is met.
The break keyword is useful when you want to exit a loop early, such as when a specific condition is found or when continuing the loop is no longer necessary.
Although the continue keyword is mentioned in the comments, it is not used in this example. continue works differently—it skips the current iteration and moves to the next one instead of stopping the loop completely.
Understanding break and continue helps you write more efficient and controlled loops in Python.
Functions in Python
Functions allow you to reuse code and keep your programs organized.
Creating a Function
def greet(name):
print("Hello", name)
Explanation of the Code
In this example, we are learning how to create a function in Python.
The keyword def is used to define a function. Here, the function is named greet. A function name should describe what the function does, and in this case, greet is used to greet someone.
Inside the parentheses (name), we define a parameter. A parameter is a variable that receives a value when the function is called. In this example, name will store the name of the person we want to greet.
The colon (:) at the end of the function definition tells Python that the next indented lines belong to the function.
Inside the function, the print("Hello", name) statement prints a greeting message followed by the value of the name parameter.
Functions are useful because they allow you to reuse code, keep programs organized, and make your code easier to read and maintain.
Calling a Function
greet("Alice")
Explanation of the Code
In this example, we are calling a function that was previously defined.
The line greet("Alice") calls the function named greet and passes the value "Alice" as an argument. An argument is the actual value that is sent to a function when it is called.
When the function is called, the value "Alice" is assigned to the parameter name inside the function definition.
As a result, the function executes its code and prints the message:
Hello Alice
Calling a function allows you to reuse the same code with different values. For example, you could call the function again with a different name:
greet("John")
Functions help make programs more flexible, organized, and easier to maintain, especially as they grow in size.
Functions with Return Values
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Explanation of the Code
In this example, we are creating a function that returns a value instead of only printing something to the screen.
The function add is defined using the def keyword and has two parameters: a and b. These parameters represent the two numbers that will be added together.
Inside the function, the line return a + b calculates the sum of a and b and sends the result back to the place where the function was called. The return keyword ends the function and provides a value that can be stored or used later.
Next, the function is called with the arguments 5 and 3 using add(5, 3). The returned value, which is 8, is stored in the variable result.
Finally, print(result) displays the value stored in result on the screen.
Using return is very powerful because it allows functions to produce results that can be reused in calculations, conditions, or other parts of the program, instead of just printing output.
Modules in Python
Modules are files containing Python code that you can reuse.
Using Built-in Modules
import math
print(math.sqrt(16))
Explanation of the Code
In this example, we are learning how to use a built-in module in Python.
The line import math imports the math module, which is a built-in Python module that provides mathematical functions such as square roots, trigonometry, and more.
By importing the module, we gain access to all the functions inside it using the dot (.) notation.
The line math.sqrt(16) calls the sqrt function from the math module. The sqrt function calculates the square root of a number.
In this case, the square root of 16 is 4. The result is then printed to the screen using the print() function.
Modules help keep Python programs organized and powerful by allowing you to reuse pre-written code instead of writing everything from scratch.
Python includes many built-in modules, such as math, random, and datetime, which make programming easier and more efficient.
Creating Your Own Module
Create a file called utils.py:
def multiply(a, b):
return a * b
Then import it:
import utils
print(utils.multiply(4, 5))
Explanation of the Code
In this example, we are learning how to create and use our own module in Python.
First, a new Python file named utils.py is created. This file acts as a custom module, which means it contains code that can be reused in other Python programs.
Inside the utils.py file, a function called multiply is defined. This function takes two parameters, a and b, and returns their multiplication using the return keyword.
Next, in another Python file, the line import utils is used to import the custom module. Python looks for a file named utils.py in the same folder as the main program or in its module search path.
After importing the module, the function inside it can be accessed using dot notation. The line utils.multiply(4, 5) calls the multiply function from the utils module.
The result of the multiplication, which is 20, is then printed to the screen using the print() function.
Creating your own modules helps you organize your code, avoid repetition, and keep large projects clean and easy to maintain.
Popular Python Libraries for Beginners
Python’s power comes from its libraries.
NumPy – Numerical Computing
Used for mathematical operations and arrays.
import numpy as np
numbers = np.array([1, 2, 3])
print(numbers * 2)
Explanation of the Code
In this example, we are using NumPy, a popular Python library designed for numerical computing and working with arrays.
The line import numpy as np imports the NumPy library and assigns it the shorter name np. This is a common convention that makes the code easier to read and write.
Next, np.array([1, 2, 3]) creates a NumPy array containing the numbers 1, 2, and 3. Unlike regular Python lists, NumPy arrays are optimized for mathematical operations and performance.
The expression numbers * 2 multiplies every element in the array by 2. NumPy automatically applies the operation to all elements at once, without the need for a loop.
As a result, the output will be:
[2 4 6]
This feature is called vectorization, and it allows NumPy to perform calculations faster and more efficiently.
NumPy is widely used in data science, machine learning, scientific computing, and engineering applications because it simplifies complex numerical operations.
Pandas – Data Analysis
Perfect for working with tables and datasets.
import pandas as pd
data = {
"Name": ["Alice", "Bob"],
"Age": [25, 30]
}
df = pd.DataFrame(data)
print(df)
Explanation of the Code
In this example, we are using Pandas, a powerful Python library designed for data analysis and working with tabular data, similar to spreadsheets or database tables.
The line import pandas as pd imports the Pandas library and assigns it the short name pd, which is the standard convention used by Python developers.
Next, we create a Python dictionary called data.
Each key in the dictionary represents a column name ("Name" and "Age"), and the lists associated with each key represent the column values.
The line pd.DataFrame(data) converts this dictionary into a DataFrame, which is Pandas’ main data structure. A DataFrame looks like a table with rows and columns, making data easier to read, analyze, and manipulate.
Finally, print(df) displays the DataFrame in a table format, producing an output similar to:
Name Age
0 Alice 25
1 Bob 30
Each row has an index (0 and 1), which Pandas automatically assigns.
Pandas is widely used in data analysis, data science, machine learning, and business analytics because it makes it easy to:
- Filter and sort data
- Perform calculations on columns
- Load data from CSV, Excel, or databases
This makes Pandas an essential tool for anyone working with real-world datasets in Python.
Requests – Working with APIs
Used to fetch data from the web.
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Explanation of the Code
In this example, we are using Requests, one of the most popular Python libraries for working with APIs and making HTTP requests.
The line import requests imports the Requests library, which allows Python to communicate with websites and web services.
Next, requests.get("https://api.github.com") sends an HTTP GET request to the GitHub public API. A GET request is used to retrieve data from a server.
The result of this request is stored in the variable response. This object contains important information about the request, such as:
- The response status
- The returned data
- Headers and metadata
The line print(response.status_code) prints the HTTP status code returned by the server.
Common status codes include:
- 200 → Request was successful
- 404 → Resource not found
- 500 → Server error
If the output is 200, it means the API request was successful and the server responded correctly.
The Requests library is widely used for:
- Accessing REST APIs
- Fetching data from websites
- Sending data to servers (POST requests)
- Automating web-based tasks
This makes Requests an essential tool for developers who work with web applications, APIs, and data integration in Python.
Common Beginner Mistakes in Python
- Forgetting indentation
- Mixing tabs and spaces
- Not reading error messages
- Trying to learn everything at once
🔎 Python errors are your best teachers — always read them carefully.
Best Practices for Python Beginners
- Write clean and readable code
- Use meaningful variable names
- Practice every day
- Build small projects
- Comment your code
What to Learn After This Tutorial
Once you master the basics, move on to:
- Object-Oriented Programming (OOP)
- File handling
- Virtual environments
- Web development with Flask or Django
- Automation scripts
- Data science and AI
Frequently Asked Questions
Is Python good for beginners?
Yes, Python is one of the easiest and most beginner-friendly languages.
How long does it take to learn Python?
Basic proficiency usually takes 1–3 months with consistent practice.
Can I get a job with Python?
Yes. Python is widely used in web development, data science, automation, and AI.
Conclusion
This Beginner Python Tutorial provides a solid foundation for learning Python programming from scratch. By understanding variables, loops, functions, modules, and libraries, you are now ready to build real projects and advance your programming journey.
Python is a powerful skill that opens doors to countless opportunities. Keep practicing, stay curious, and continue learning.
🔗 Recommended Resources to Continue Learning Python
If you want to deepen your Python knowledge and explore official and trusted resources, the links below are essential for every beginner and future professional.
The official Python website offers complete documentation, tutorials, and the latest updates about the language. It’s the best starting point to understand Python’s philosophy, syntax, and real-world applications:
👉 https://www.python.org
For more detailed and technical explanations, the official Python documentation provides in-depth guides on core concepts, standard libraries, and advanced features. This resource is ideal when you want to master Python step by step:
👉 https://docs.python.org/3
When working with data, mathematics, or scientific computing, NumPy is one of the most important Python libraries. It allows efficient numerical operations and is widely used in data science, machine learning, and engineering projects:
👉 https://numpy.org
Another essential library is Pandas, which is widely used for data analysis and manipulation. It helps beginners work with tables, datasets, and real-world data in a simple and intuitive way:
👉 https://pandas.pydata.org
Exploring these resources will strengthen your foundation in Python and help you move from beginner concepts to more advanced programming projects with confidence.
“If you have questions or suggestions, feel free to leave a comment below — I’d be happy to help!”