Tutorials

Home Python Tutorial

Python Tutorials

Introduction

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.

What you will learn: Python syntax, variables, data types, operators, conditions, loops, collections, functions, modules, file handling, exception handling, object-oriented programming, and beginner-friendly projects.

Why learn Python?

  • Its syntax is relatively easy for beginners to read.
  • It supports procedural and object-oriented programming.
  • It can automate repetitive tasks.
  • It has libraries for data analysis, AI, and web development.
  • It helps beginners develop logical thinking and problem-solving skills.

How does a Python program work?

  1. Write Python instructions in a code editor.
  2. Save the program with a .py extension.
  3. Run the program using the Python interpreter.
  4. Python executes the instructions and displays the output.
  5. Review the result, correct errors, and practise again.

Python Installation and Development Setup

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.

Tools you need

  • Python interpreter to run Python programs.
  • Visual Studio Code or another code editor.
  • Terminal or command prompt to execute commands.
  • A browser to access documentation and learning resources.

Step 1: Install Python

Download Python from the official website and follow the installation instructions for your operating system.

Download Python from Python.org

Step 2: Verify the installation

Terminal / Command Prompt
python --version

On some systems, use python3 --version instead. The command should display the installed Python version.

Step 3: Create your first Python file

Create a folder named python-practice. Inside it, create a file called hello.py.

hello.py
print("Hello, Python!")

print("I am learning Python programming.")

Run the program from your terminal:

Terminal
python hello.py

Expected output:

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.

Python Basics Tutorial

This Python Basics Tutorial introduces the essential rules used when writing Python code. Start with simple instructions before moving to conditions, loops, and functions.

1. The print() function

The print() function displays text, numbers, and calculated results in the output.

Python
print("Welcome to Python")
print(25)
print(10 + 5)

2. Python comments

Comments explain code to people reading it. Python ignores single-line comments that begin with #.

Python
# Display a welcome message
print("Welcome!")

3. Python indentation

Indentation defines blocks of code in Python. Use consistent indentation, commonly four spaces, inside conditions, loops, functions, and classes.

Python
if 10 > 5:
    print("10 is greater than 5")
Beginner tip: Practise small programs first. Understand what each line does before combining several concepts into one application.

Python Variables and Data Types

Variables store values that a program can use later. Python determines a variable's type from the value assigned to it.

Creating variables

Python
student_name = "Arun"
age = 20
percentage = 85.5
is_enrolled = True

print(student_name)
print(age)
print(percentage)
print(is_enrolled)

Common Python data types

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"}

Check a variable's type

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

Python Operators

Operators perform calculations, compare values, and combine conditions. Understanding operators helps you write useful Python coding examples and solve everyday programming problems.

1. Arithmetic operators

Python
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

2. Comparison operators

Comparison operators compare two values and return True or False.

Python
first_mark = 85
second_mark = 70

print(first_mark > second_mark)
print(first_mark == second_mark)
print(first_mark != second_mark)

3. Logical operators

Python
age = 22
has_id = True

print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)

4. Assignment operators

Python
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 in Python

Conditional statements allow a program to make decisions. The code runs different instructions depending on whether a condition is true or false.

Using if, elif, and else

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

Using conditions with user input

Python
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 in Python

Loops repeat instructions. Use a for loop to iterate through a sequence or a while loop to repeat while a condition remains true.

1. For loop

Python
for number in range(1, 6):
    print(number)

range(1, 6) produces the numbers 1 through 5. The ending value is excluded.

2. While loop

Python
count = 1

while count <= 5:
    print(count)
    count += 1

3. Break and continue

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

Python Lists, Tuples, Sets, and Dictionaries

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.

1. Lists

A list is ordered and can be changed after creation.

Python
courses = ["Python", "Java", "PHP"]

courses.append("JavaScript")
print(courses)
print(courses[0])

2. Tuples

A tuple is ordered but cannot be changed after creation.

Python
coordinates = (10, 20)
print(coordinates[0])

3. Sets

A set stores unique values and does not guarantee a fixed display order.

Python
numbers = {1, 2, 2, 3, 4}
print(numbers)

4. Dictionaries

A dictionary stores values using keys.

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

Python Strings

A string represents text. Python provides methods to search, format, split, and transform string values.

Common string operations

Python
message = "Learn Python Programming"

print(message.lower())
print(message.upper())
print(message.title())
print(message.replace("Python", "Web"))
print(message.split())

String formatting with f-strings

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

Python Functions

A function is a reusable block of code that performs a particular task. Functions help organise a program and reduce repeated instructions.

Create and call a function

Python
def greet():
    print("Welcome to Python!")

greet()

Functions with parameters and return values

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

Default parameters

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

Python Modules and Packages

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 a built-in module

Python
import math

print(math.sqrt(25))
print(math.pi)

Import a specific function

Python
from random import randint

number = randint(1, 10)
print(number)

Install a package

Terminal
python -m pip install requests

Use a virtual environment for project-specific dependencies. It helps keep one project's packages separate from another's.

Terminal
python -m venv .venv

Practice task: Use the math module to calculate the square root of a number.

File Handling in Python

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.

Write to a text file

Python
with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("I am learning Python.")
    file.write("\\nThis is my first file.")

Read from a text file

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

Exception Handling in Python

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.

Using try and except

Python
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.")

Using finally

Python
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 in Python

Object-oriented programming (OOP) organises related data and behaviour into classes and objects. It is useful when building applications with multiple related entities.

Classes and objects

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

Inheritance

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

Popular Python Libraries

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

Example: Generate a random number

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

Python Coding Examples for Practice

These Python Coding Examples help beginners apply basic programming concepts to small problems. Try to write each program yourself before checking the solution.

Example 1: Add two numbers

Python
first = 10
second = 20

total = first + second
print("Total:", total)

Example 2: Check even or odd

Python
number = int(input("Enter a number: "))

if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

Example 3: Find the largest of three numbers

Python
a = 15
b = 28
c = 12

largest = max(a, b, c)
print("Largest number:", largest)

Example 4: Calculate a factorial

Python
number = 5
factorial = 1

for value in range(1, number + 1):
    factorial *= value

print("Factorial:", factorial)

Example 5: Count vowels in a word

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

Python Projects for Beginners

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.

1. Simple Calculator

Concepts: Input, operators, conditions, functions.

  • Accept two numbers from the user.
  • Allow addition, subtraction, multiplication, and division.
  • Display the result clearly.
  • Handle invalid choices and division by zero.

2. Number Guessing Game

Concepts: Loops, conditions, and the random module.

  • Generate a random number.
  • Ask the user to guess the number.
  • Provide higher or lower hints.
  • Count the number of attempts.

3. Student Marks Manager

Concepts: Lists, dictionaries, functions, and conditions.

  • Store student names and marks.
  • Calculate total and average marks.
  • Display a student's result.
  • Find the highest mark.

4. To-Do List Application

Concepts: Lists, loops, functions, and file handling.

  • Add new tasks.
  • Display existing tasks.
  • Mark tasks as completed or remove them.
  • Save tasks to a file so they remain available later.

5. Contact Book

Concepts: Dictionaries, functions, and file handling.

  • Save names and contact details.
  • Search for a contact.
  • Update or remove a contact.
  • Store the data in a file.

How to build your first Python project

  1. Choose one small problem to solve.
  2. Write down the features you need.
  3. Break the problem into smaller functions.
  4. Build one feature at a time.
  5. Test normal inputs and incorrect inputs.
  6. Improve the code and document how to run it.

Python Learning Roadmap

Follow this learning path to move from beginner concepts to practical Python development. Practise each stage before moving to more advanced topics.

Stage 1: Python Fundamentals Learn installation, syntax, print statements, comments, variables, data types, and operators.
Stage 2: Program Logic Practise conditions, loops, strings, lists, tuples, sets, and dictionaries.
Stage 3: Reusable Code Learn functions, modules, packages, file handling, and exception handling.
Stage 4: Object-Oriented Programming Understand classes, objects, constructors, inheritance, and other core OOP concepts.
Stage 5: Practical Projects Build a calculator, guessing game, student marks manager, to-do list, and contact book.
Stage 6: Choose a Specialisation Explore web development, automation, data analysis, or artificial intelligence after building a strong foundation.

Frequently Asked Questions About Python Tutorials

1. What are Python Tutorials?

Python Tutorials explain Python programming concepts through examples and exercises. They can help learners progress from basic syntax to functions, data structures, and projects.

2. Are Python Tutorials for Beginners suitable for students?

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.

3. What should I learn first in Python?

Begin with Python syntax, print statements, variables, data types, and operators. Then learn conditions, loops, collections, and functions.

4. Do I need to install Python to practise?

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.

5. Where can I find Python Coding Examples?

You can practise Python Coding Examples in the examples section of this tutorial. Start with arithmetic, conditions, loops, and strings before attempting larger programs.

6. What are some Python Projects for Beginners?

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.

7. What can I do after learning Python basics?

After learning the fundamentals, practise building projects and explore a path such as web development, automation, data analysis, or artificial intelligence.

8. How can I improve my Python programming skills?

Write code regularly, solve small programming problems, understand error messages, review your solutions, and build projects that use several concepts together.

Start Learning Python Programming

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.

Join Our WhatsApp Channel 💬

Join our WhatsApp community for internship updates, IT courses, placement support, and latest job opportunities.

Join Now