Tutorials
Home Python Tutorial
Python is a popular, high-level programming language known for its readable syntax and wide range of applications. It is used in web development, automation, data analysis, artificial intelligence, machine learning, and many other technical fields.
These Python Tutorials explain programming concepts step by step, from writing your first line of code to building practical applications. Each topic includes explanations and Python coding examples to help you practise what you learn.
.py extension.Before following Python Programming Tutorials, install Python and choose a code editor. You can use Visual Studio Code, PyCharm, or Python's built-in IDLE editor.
Download Python from the official website and follow the installation instructions for your operating system.
Download Python from Python.org
python --version
On some systems, use python3 --version instead.
The command should display the installed Python version.
Create a folder named python-practice. Inside it,
create a file called hello.py.
print("Hello, Python!")
print("I am learning Python programming.")
Run the program from your terminal:
python hello.py
Expected output:
Hello, Python!
I am learning Python programming.
Practice task: Change the messages and run the program again. This is the first step in learning Python programming.
This Python Basics Tutorial introduces the essential rules used when writing Python code. Start with simple instructions before moving to conditions, loops, and functions.
The print() function displays text, numbers, and
calculated results in the output.
print("Welcome to Python")
print(25)
print(10 + 5)
Comments explain code to people reading it. Python ignores
single-line comments that begin with #.
# Display a welcome message
print("Welcome!")
Indentation defines blocks of code in Python. Use consistent indentation, commonly four spaces, inside conditions, loops, functions, and classes.
if 10 > 5:
print("10 is greater than 5")
Variables store values that a program can use later. Python determines a variable's type from the value assigned to it.
student_name = "Arun"
age = 20
percentage = 85.5
is_enrolled = True
print(student_name)
print(age)
print(percentage)
print(is_enrolled)
| Data type | Purpose | Example |
|---|---|---|
| int | Whole numbers | age = 20 |
| float | Decimal numbers | price = 99.50 |
| str | Text values | name = "Arun" |
| bool | True or false values | is_active = True |
| list | Ordered, changeable collection | marks = [80, 90, 75] |
| tuple | Ordered, unchangeable collection | point = (10, 20) |
| dict | Key-value data | student = {"name": "Arun"} |
age = 20
print(type(age))
name = "Arun"
print(type(name))
Practice task: Create variables for your name, age, course, and whether you are a student. Print each value.
Operators perform calculations, compare values, and combine conditions. Understanding operators helps you write useful Python coding examples and solve everyday programming problems.
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a // b) # Floor division
print(a % b) # Remainder
print(a ** b) # Exponentiation
Comparison operators compare two values and return
True or False.
first_mark = 85
second_mark = 70
print(first_mark > second_mark)
print(first_mark == second_mark)
print(first_mark != second_mark)
age = 22
has_id = True
print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)
score = 10
score += 5
print(score)
score -= 2
print(score)
Practice task: Create a simple calculator that accepts two numbers and displays their sum, difference, product, and quotient.
Conditional statements allow a program to make decisions. The code runs different instructions depending on whether a condition is true or false.
mark = 78
if mark >= 90:
print("Grade A")
elif mark >= 75:
print("Grade B")
elif mark >= 50:
print("Grade C")
else:
print("Needs improvement")
The program checks the conditions from top to bottom. When a condition is true, its block runs and the remaining branches are skipped.
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are under 18.")
The input() function returns text, so
int() converts the entered value to an integer.
This example assumes the user enters a valid whole number.
Practice task: Write a program that checks whether a number is positive, negative, or zero.
Loops repeat instructions. Use a for loop to
iterate through a sequence or a while loop to
repeat while a condition remains true.
for number in range(1, 6):
print(number)
range(1, 6) produces the numbers 1 through 5.
The ending value is excluded.
count = 1
while count <= 5:
print(count)
count += 1
for number in range(1, 6):
if number == 3:
continue
print(number)
continue skips the current iteration.
break stops the loop entirely.
Practice task: Print the multiplication table for a number entered by the user.
Collections allow you to store and manage multiple values. Choose the collection type based on whether you need ordered items, unique values, or key-value pairs.
A list is ordered and can be changed after creation.
courses = ["Python", "Java", "PHP"]
courses.append("JavaScript")
print(courses)
print(courses[0])
A tuple is ordered but cannot be changed after creation.
coordinates = (10, 20)
print(coordinates[0])
A set stores unique values and does not guarantee a fixed display order.
numbers = {1, 2, 2, 3, 4}
print(numbers)
A dictionary stores values using keys.
student = {
"name": "Arun",
"course": "Python",
"mark": 85
}
print(student["name"])
print(student["course"])
Practice task: Store five student names in a list and display them one by one. Then create a dictionary for one student's name, course, and mark.
A string represents text. Python provides methods to search, format, split, and transform string values.
message = "Learn Python Programming"
print(message.lower())
print(message.upper())
print(message.title())
print(message.replace("Python", "Web"))
print(message.split())
name = "Arun"
course = "Python"
print(f"{name} is learning {course}.")
F-strings make it easy to insert variables and expressions into text. They are useful when generating messages, reports, and formatted output.
Practice task: Ask the user for their name and display a welcome message using an f-string.
A function is a reusable block of code that performs a particular task. Functions help organise a program and reduce repeated instructions.
def greet():
print("Welcome to Python!")
greet()
def add_numbers(a, b):
return a + b
result = add_numbers(10, 5)
print(result)
Parameters provide input to a function, while
return sends a result back to the code that
called it.
def welcome(name="Student"):
print(f"Hello, {name}!")
welcome()
welcome("Arun")
Practice task: Create a function that accepts a student's marks and returns whether the student has passed.
A module is a Python file containing reusable code. Packages organise related modules into a directory structure. Python also includes a standard library with useful tools.
import math
print(math.sqrt(25))
print(math.pi)
from random import randint
number = randint(1, 10)
print(number)
python -m pip install requests
Use a virtual environment for project-specific dependencies. It helps keep one project's packages separate from another's.
python -m venv .venv
Practice task: Use the math module to calculate
the square root of a number.
File handling allows a program to read information from files
and save results for later use. Python's with
statement helps close files safely after use.
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("I am learning Python.")
file.write("\\nThis is my first file.")
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Common file modes include r for reading,
w for writing, and a for appending.
Writing with w replaces existing file contents.
Practice task: Create a program that saves a list of tasks to a text file and displays them when the program runs again.
Exceptions are errors that occur while a program is running. Handling expected errors helps prevent a program from stopping unexpectedly and makes error messages more useful.
try:
number = int(input("Enter a number: "))
print(100 / number)
except ValueError:
print("Please enter a valid whole number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
try:
print("Processing started.")
finally:
print("Processing finished.")
The finally block runs whether or not an exception
occurs. Use specific exception types whenever possible so
genuine programming errors are not hidden.
Practice task: Write a calculator that handles invalid input and division by zero.
Object-oriented programming (OOP) organises related data and behaviour into classes and objects. It is useful when building applications with multiple related entities.
class Student:
def __init__(self, name, course):
self.name = name
self.course = course
def introduce(self):
print(f"My name is {self.name}.")
print(f"I am learning {self.course}.")
student = Student("Arun", "Python")
student.introduce()
A class defines the structure and behaviour of objects.
The __init__() method initialises an object,
and self refers to the current instance.
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def display(self):
print(f"Student name: {self.name}")
student = Student("Arun")
student.display()
Important OOP concepts include classes, objects, constructors, inheritance, encapsulation, and polymorphism.
Practice task: Create a BankAccount class with
methods to deposit money, withdraw money, and display the balance.
Python libraries provide reusable tools for common tasks. Choose a library based on what you want your application to do.
| Library | Common use |
|---|---|
| Requests | Sending HTTP requests to web services |
| NumPy | Numerical operations and arrays |
| Pandas | Working with structured data |
| Matplotlib | Creating charts and graphs |
| Flask | Building web applications and APIs |
| Django | Developing database-driven web applications |
import random
number = random.randint(1, 100)
print(f"Your number is {number}")
Learn the Python language fundamentals before trying many third-party libraries. Strong basics make library documentation easier to understand.
These Python Coding Examples help beginners apply basic programming concepts to small problems. Try to write each program yourself before checking the solution.
first = 10
second = 20
total = first + second
print("Total:", total)
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
a = 15
b = 28
c = 12
largest = max(a, b, c)
print("Largest number:", largest)
number = 5
factorial = 1
for value in range(1, number + 1):
factorial *= value
print("Factorial:", factorial)
word = "programming"
vowels = "aeiou"
count = 0
for character in word.lower():
if character in vowels:
count += 1
print("Number of vowels:", count)
Once these examples become easy, practise with lists, dictionaries, functions, and files. Gradually combine several concepts into one program.
Building small applications helps you apply what you learn through Python Tutorials. Start with a simple project and add features as your programming skills improve.
Concepts: Input, operators, conditions, functions.
Concepts: Loops, conditions, and the random module.
Concepts: Lists, dictionaries, functions, and conditions.
Concepts: Lists, loops, functions, and file handling.
Concepts: Dictionaries, functions, and file handling.
Follow this learning path to move from beginner concepts to practical Python development. Practise each stage before moving to more advanced topics.
Python Tutorials explain Python programming concepts through examples and exercises. They can help learners progress from basic syntax to functions, data structures, and projects.
Yes. Python Tutorials for Beginners can help students learn programming step by step. Start with variables and simple output, then practise conditions, loops, functions, and projects.
Begin with Python syntax, print statements, variables, data types, and operators. Then learn conditions, loops, collections, and functions.
Installing Python on your computer lets you run programs locally. You can also start with an online Python editor if you want to try basic examples before installing it.
You can practise Python Coding Examples in the examples section of this tutorial. Start with arithmetic, conditions, loops, and strings before attempting larger programs.
A calculator, number guessing game, student marks manager, to-do list, and contact book are useful beginner projects. They provide practice with variables, conditions, loops, collections, and functions.
After learning the fundamentals, practise building projects and explore a path such as web development, automation, data analysis, or artificial intelligence.
Write code regularly, solve small programming problems, understand error messages, review your solutions, and build projects that use several concepts together.
Explore Python Programming Tutorials, practise coding examples, and build projects to strengthen your programming fundamentals. Learn one concept at a time and apply it through regular practice.
Get internship updates, IT training news, placement opportunities, and career tips directly to your inbox.
Join our WhatsApp community for internship updates, IT courses, placement support, and latest job opportunities.
Join Now