Ultimate Python Tutorial for Beginners | Full Notes + Practical Programs

Python programming workspace
Beginner to Practical Level With Exercises Interactive MCQs

Complete Python Full Course Notes

This professional course is designed for students who want to learn Python from installation to practical programming. Every section includes explanations, examples, practical tasks, and question answers.

How to use: Read one module, type the code yourself, complete the practical task, then answer the quiz. Do not only copy and paste.

1. Python Installation and Setup

Coding setup

What is Python?

Python is a high-level, beginner-friendly programming language. It is used for web development, automation, data science, artificial intelligence, software development, scripting, and education.

Install Python on Windows

  1. Go to the official Python website.
  2. Download the latest Python version.
  3. Run the installer.
  4. Very important: tick Add Python to PATH.
  5. Click Install Now.
  6. Open Command Prompt and type:
python --version
pip --version

Install Code Editor

Recommended editor: Visual Studio Code. Install Python extension inside VS Code.

First Python Program

print("Hello, Python!")

Output:

Hello, Python!

Practical Task

  1. Install Python.
  2. Install VS Code.
  3. Create a file named first.py.
  4. Print your name, age, and country.
print("Name: Kumar")
print("Age: 20")
print("Country: Sri Lanka")

Quiz 1

Which command checks Python version?

2. Introduction to Python

Why Learn Python?

Easy syntax
Python code is readable and close to English.
Popular
Used in AI, web, automation, and data science.
Large library
Many ready-made packages are available.
Cross-platform
Works on Windows, Linux, and macOS.

Python Program Structure

# This is a simple program
name = "Anu"
print("Welcome", name)

Interactive Mode vs Script Mode

ModeExplanation
Interactive ModeType commands directly in Python shell.
Script ModeWrite code in a .py file and run it.

Question and Answer

Q: Is Python compiled or interpreted?

A: Python is commonly called an interpreted language because code is executed line by line by the Python interpreter.

Q: What is a Python file extension?

A: .py

Quiz 2

Python file extension is:

3. Syntax, Comments, Variables

Python Syntax

Python uses indentation to define code blocks. Other languages often use braces { }, but Python uses spaces.

if 10 > 5:
    print("10 is greater than 5")
Important: Wrong indentation causes an IndentationError.

Comments

# Single line comment

"""
Multi-line comment style
commonly used as documentation
"""

Variables

A variable is a name used to store data.

student_name = "Ravi"
age = 21
marks = 78.5
is_passed = True

Variable Naming Rules

  • Can contain letters, numbers, and underscores.
  • Cannot start with a number.
  • Cannot use spaces.
  • Names are case-sensitive.

Practical Task

Create variables for a student and print a student report.

name = "Meena"
subject = "Python"
marks = 85

print("Student:", name)
print("Subject:", subject)
print("Marks:", marks)

Quiz 3

Which variable name is valid?

4. Data Types

Programming code

Data type means the kind of value stored in a variable.

TypeExampleMeaning
int10Whole number
float10.5Decimal number
str"Hello"Text
boolTrueTrue or False
list[1, 2, 3]Ordered, changeable collection
tuple(1, 2, 3)Ordered, unchangeable collection
set{1, 2, 3}Unordered unique collection
dict{"name":"Ravi"}Key-value collection

Check Type

x = 25
print(type(x))

Type Conversion

a = "10"
b = int(a)
print(b + 5)

Practical Task

Take two numbers as input and print total.

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
total = num1 + num2
print("Total:", total)

Quiz 4

Which data type stores text?

5. Operators

Arithmetic Operators

OperatorMeaningExample
+Addition5 + 2 = 7
-Subtraction5 - 2 = 3
*Multiplication5 * 2 = 10
/Division5 / 2 = 2.5
//Floor division5 // 2 = 2
%Modulus5 % 2 = 1
**Power5 ** 2 = 25

Comparison Operators

x = 10
print(x == 10)
print(x != 5)
print(x > 3)

Logical Operators

age = 20
has_id = True

if age >= 18 and has_id:
    print("Allowed")

Practical Task

Create a simple calculator for two numbers.

a = float(input("Enter number 1: "))
b = float(input("Enter number 2: "))

print("Add:", a + b)
print("Subtract:", a - b)
print("Multiply:", a * b)
print("Divide:", a / b)

Quiz 5

Which operator gives remainder?

6. Conditions and Loops

if, elif, else

marks = 75

if marks >= 75:
    print("A Grade")
elif marks >= 65:
    print("B Grade")
elif marks >= 50:
    print("C Grade")
else:
    print("Fail")

for Loop

for i in range(1, 6):
    print(i)

while Loop

count = 1

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

break and continue

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Practical Task

Print multiplication table.

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

for i in range(1, 13):
    print(number, "x", i, "=", number * i)

Quiz 6

Which loop is best when you know the number of repetitions?

7. Strings

A string is a sequence of characters.

message = "Welcome to Python"
print(message)

String Indexing

text = "Python"
print(text[0])   # P
print(text[-1])  # n

String Slicing

text = "Python Programming"
print(text[0:6])
print(text[7:])

Useful String Methods

name = "  python course  "
print(name.upper())
print(name.lower())
print(name.strip())
print(name.replace("python", "Java"))

f-string Formatting

name = "Arun"
age = 22
print(f"My name is {name} and I am {age} years old.")

Practical Task

Ask user name and print a greeting message.

name = input("Enter your name: ")
print(f"Hello {name}, welcome to Python class!")

Quiz 7

What is the index of the first character in Python?

8. Lists, Tuples, Sets, Dictionaries

Laptop coding

List

A list is ordered and changeable.

fruits = ["apple", "banana", "mango"]
fruits.append("orange")
print(fruits)

Tuple

A tuple is ordered but unchangeable.

days = ("Monday", "Tuesday", "Wednesday")
print(days[0])

Set

A set stores unique values.

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

Dictionary

A dictionary stores data in key-value pairs.

student = {
    "name": "Kavi",
    "age": 20,
    "course": "Python"
}

print(student["name"])

Practical Task

Create a student marks dictionary and calculate total.

marks = {
    "maths": 75,
    "science": 80,
    "english": 70
}

total = marks["maths"] + marks["science"] + marks["english"]
average = total / 3

print("Total:", total)
print("Average:", average)

Quiz 8

Which collection stores key-value pairs?

9. Functions

A function is a reusable block of code.

Creating a Function

def greet():
    print("Hello!")

greet()

Function with Parameter

def greet(name):
    print("Hello", name)

greet("Nimal")

Function with Return Value

def add(a, b):
    return a + b

result = add(10, 20)
print(result)

Default Parameter

def welcome(name="Student"):
    print("Welcome", name)

welcome()
welcome("Rani")

Practical Task

Create a function to calculate area of a rectangle.

def rectangle_area(length, width):
    return length * width

l = float(input("Enter length: "))
w = float(input("Enter width: "))

print("Area:", rectangle_area(l, w))

Quiz 9

Which keyword creates a function?

10. File Handling

File handling is used to read and write files.

Write File

file = open("notes.txt", "w")
file.write("This is my Python note.")
file.close()

Read File

file = open("notes.txt", "r")
content = file.read()
print(content)
file.close()

Recommended Method: with

with open("notes.txt", "r") as file:
    content = file.read()
    print(content)
ModeMeaning
rRead
wWrite, replaces existing content
aAppend
xCreate new file

Practical Task

Create a file and save five student names.

with open("students.txt", "w") as file:
    for i in range(5):
        name = input("Enter student name: ")
        file.write(name + "\n")

print("Names saved successfully.")

Quiz 10

Which mode appends data to a file?

11. Error Handling

Error handling prevents a program from stopping suddenly.

try and except

try:
    number = int(input("Enter number: "))
    print(10 / number)
except:
    print("Something went wrong.")

Specific Exception

try:
    number = int(input("Enter number: "))
    print(10 / number)
except ValueError:
    print("Please enter only numbers.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

finally

try:
    file = open("data.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("File not found.")
finally:
    print("Program completed.")

Practical Task

Create a safe division program.

try:
    a = float(input("Enter first number: "))
    b = float(input("Enter second number: "))
    print("Answer:", a / b)
except ZeroDivisionError:
    print("You cannot divide by zero.")
except ValueError:
    print("Invalid input. Please enter numbers only.")

Quiz 11

Which block catches errors?

12. Object-Oriented Programming

Online learning

OOP is a programming style based on classes and objects.

Class and Object

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

student1 = Student("Ravi", 21)
print(student1.name)
print(student1.age)

Method

class Student:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print("Hello, I am", self.name)

s1 = Student("Meena")
s1.say_hello()

Inheritance

class Animal:
    def sound(self):
        print("Animal makes sound")

class Dog(Animal):
    def bark(self):
        print("Dog barks")

d = Dog()
d.sound()
d.bark()

Important OOP Terms

TermMeaning
ClassBlueprint for objects
ObjectInstance of a class
AttributeVariable inside object
MethodFunction inside class
InheritanceOne class gets features from another class

Practical Task

Create a BankAccount class.

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print("New balance:", self.balance)

    def withdraw(self, amount):
        if amount <= self.balance:
            self.balance -= amount
            print("New balance:", self.balance)
        else:
            print("Not enough balance")

account = BankAccount("Kumar", 5000)
account.deposit(1000)
account.withdraw(2000)

Quiz 12

What is a class?

13. Modules, pip, Virtual Environment

Module

A module is a Python file that contains reusable code.

import math

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

Install Packages with pip

pip install requests

Using a Package

import requests

response = requests.get("https://example.com")
print(response.status_code)

Virtual Environment

A virtual environment keeps project packages separate.

python -m venv myenv

Activate on Windows:

myenv\Scripts\activate

Activate on macOS/Linux:

source myenv/bin/activate

Practical Task

Create a random number guessing game using the random module.

import random

secret = random.randint(1, 10)
guess = int(input("Guess number 1 to 10: "))

if guess == secret:
    print("Correct!")
else:
    print("Wrong. Number was", secret)

Quiz 13

Which command creates a virtual environment?

14. Final Practical Projects

Project 1: Student Grade System

name = input("Enter student name: ")
marks = float(input("Enter marks: "))

if marks >= 75:
    grade = "A"
elif marks >= 65:
    grade = "B"
elif marks >= 50:
    grade = "C"
else:
    grade = "Fail"

print("Student:", name)
print("Grade:", grade)

Project 2: Simple Login System

correct_username = "admin"
correct_password = "1234"

username = input("Username: ")
password = input("Password: ")

if username == correct_username and password == correct_password:
    print("Login successful")
else:
    print("Invalid username or password")

Project 3: To-Do List

tasks = []

while True:
    print("\n1. Add Task")
    print("2. View Tasks")
    print("3. Exit")

    choice = input("Choose: ")

    if choice == "1":
        task = input("Enter task: ")
        tasks.append(task)
        print("Task added.")
    elif choice == "2":
        for index, task in enumerate(tasks, start=1):
            print(index, task)
    elif choice == "3":
        break
    else:
        print("Invalid choice")

Project 4: Contact Book

contacts = {}

while True:
    print("\n1. Add Contact")
    print("2. Search Contact")
    print("3. Exit")

    choice = input("Choose: ")

    if choice == "1":
        name = input("Name: ")
        phone = input("Phone: ")
        contacts[name] = phone
        print("Contact saved.")
    elif choice == "2":
        name = input("Enter name to search: ")
        if name in contacts:
            print("Phone:", contacts[name])
        else:
            print("Contact not found.")
    elif choice == "3":
        break
    else:
        print("Invalid choice")

Final Exam Style Questions and Answers

Q1: What is Python?

A: Python is a high-level programming language used for software, web, automation, AI, and data science.

Q2: What is indentation?

A: Indentation means spaces at the beginning of a line. Python uses indentation to define code blocks.

Q3: What is a function?

A: A reusable block of code that performs a specific task.

Q4: Difference between list and tuple?

A: List is changeable. Tuple is unchangeable.

Q5: What is dictionary?

A: A collection that stores values using key-value pairs.

Q6: What is exception handling?

A: Handling runtime errors using try, except, else, and finally.

Q7: What is OOP?

A: Object-Oriented Programming is a method of programming using classes and objects.

Final Quiz

Which project is best to practice list operations?