Complete Python Tutorial — Step by Step
Open one lesson at a time. Understand the rule, type the program yourself, predict the output and then complete the practice task. Every example includes the idea behind the code so students learn logic, not only syntax.
1. Introduction & Setup
Understand Python thoroughly, install it correctly and learn different ways to run a program.
What is Python? — Detailed Explanation
Python is a programming language used to give clear instructions to a computer. A program is a set of instructions written in a language that the computer can process. Python is popular because its commands are close to ordinary English and usually require fewer lines than many older languages.
Python is a high-level, interpreted and general-purpose language. Each term explains an important quality:
- High-level: the programmer writes human-readable commands instead of machine-level binary instructions. Python automatically manages many technical details such as memory allocation.
- Interpreted: the Python interpreter reads and executes the program. Students can run code immediately and see errors without first performing a separate manual compilation step.
- General-purpose: Python is not limited to one field. The same language can be used for websites, desktop programs, calculations, automation, data analysis, AI and education.
- Dynamically typed: a variable does not need a fixed type declaration before use. Python determines the type from the assigned value.
- Object-oriented: Python can organise related data and behaviour into classes and objects, while also supporting procedural and functional styles.
student = "Aman" # Python understands this as text marks = 86 # Python understands this as an integer percentage = 86.5 # Python understands this as a decimal number print(student, marks, percentage)
History and Development of Python
Python was created by Dutch programmer Guido van Rossum. Work began in the late 1980s, and the first public release appeared in 1991. The language was designed to make programming clearer, more productive and enjoyable.
- The name “Python” was inspired by the comedy programme Monty Python’s Flying Circus, not by the snake.
- Python 1 established the language’s early foundation.
- Python 2 introduced many improvements but is now discontinued.
- Python 3 is the modern version students should install and learn.
- Python is maintained as an open-source project by a worldwide developer community.
Main Features of Python — Explained One by One
- Simple and readable syntax: indentation and English-like keywords make programs easier to read and maintain.
- Interpreted execution: code can be tested quickly, which makes learning and debugging easier.
- Free and open source: students can download, use and study Python without purchasing a licence.
- Cross-platform: Python works on Windows, macOS, Linux and many other systems.
- Large standard library: ready-made modules support mathematics, dates, files, JSON, internet tasks and much more.
- Large package ecosystem: additional packages support web development, data analysis, automation, AI and scientific work.
- Multiple programming styles: Python supports procedural, object-oriented and functional programming.
- Automatic memory management: Python handles allocation and cleanup of many objects automatically.
- Interactive learning: commands can be tested one at a time in the Python shell.
- Extensible and embeddable: Python can work with code and libraries written in other languages.
Where is Python Used?
Python is used in classrooms, offices, research laboratories, technology companies and personal projects. Important application areas include:
- Web development: creating server-side websites and web applications with frameworks such as Django or Flask.
- Automation: renaming files, preparing reports, processing spreadsheets, sending routine notifications and reducing repetitive work.
- Data analysis: cleaning, calculating, summarising and visualising data.
- Artificial intelligence and machine learning: training models for prediction, classification, language and images.
- Scientific computing: simulations, research calculations and laboratory-data processing.
- Testing and cybersecurity learning: creating authorised testing tools and automating software checks.
- Desktop applications and games: building interfaces, utilities and beginner game projects.
- Education: teaching programming logic, algorithms and problem solving.
# A tiny automation-style example
for student_number in range(1, 6):
print("Preparing result for student", student_number)
Preparing result for student 1 Preparing result for student 2 Preparing result for student 3 Preparing result for student 4 Preparing result for student 5
How Does a Python Program Work?
The programmer writes source code in a .py file. The Python implementation processes that source and executes its instructions. In the common CPython implementation, source code is converted to an intermediate form called bytecode and then executed by the Python virtual machine.
- You write instructions in a file such as hello.py.
- Python checks the syntax and prepares the code for execution.
- The Python runtime executes the instructions.
- The result appears in the shell or terminal.
- If Python finds a problem, it displays an error message and the relevant line.
Python Compared with C and C++
- Python generally uses shorter, more readable code.
- Python determines variable types dynamically; C and C++ commonly require explicit type declarations.
- Python uses indentation to define blocks; C and C++ use braces.
- C and C++ normally compile to native machine code and often provide greater low-level control.
- Python is especially productive for learning, scripting, automation, data work and rapid development.
# Python
for number in range(1, 6):
print(number)
Install Python on Windows — Complete Steps
- Open the official Python website and choose the current stable Python 3 installer for Windows.
- Run the downloaded installer.
- Very important: select the option Add Python to PATH before continuing.
- Choose the normal installation option unless your teacher or system administrator requires a custom location.
- Wait for the installation to finish, then close the installer.
- Open Command Prompt from the Start menu.
- Verify the installation with one of the commands below.
python --version
If Windows uses the Python launcher, this command may be used:
py --version
Python 3.x.x
Install Python on macOS or Linux
macOS and Linux users should check whether Python 3 is already available before installing anything.
python3 --version
If Python 3 is installed, the version is displayed. The command used to run a script is commonly:
python3 filename.py
IDLE, Python Shell, VS Code and Terminal
- Python Shell: runs one command at a time and displays the result immediately. It is useful for quick experiments.
- IDLE: Python’s beginner-friendly editor and shell. It is suitable for first classroom programs.
- VS Code: a general code editor with extensions, file navigation, terminal access and debugging tools.
- Terminal or Command Prompt: runs saved scripts through commands such as python program.py.
Interactive mode example:
>>> 10 + 5
15
>>> print("Hello")
Hello
Script mode: write several instructions in a file, save it and run the complete program.
Create, Save and Run Your First File
- Open IDLE or VS Code.
- Create a new file.
- Type the program below exactly.
- Save the file as first_program.py. Avoid spaces in the filename while learning.
- Run it from the editor or open a terminal in the same folder.
- Type python first_program.py on Windows, or python3 first_program.py where required.
print("Welcome to Python Programming")
print("My first program is running successfully.")
Welcome to Python Programming My first program is running successfully.
Five First Programs with Explanations
Program 1 — Display personal information
print("Name: Aman")
print("Course: Python")
print("Centre: GD INFOTECH")
Program 2 — Perform a calculation
print("Total =", 25 + 35)
print("Product =", 8 * 7)
Program 3 — Store values in variables
student = "Simran" marks = 92 print(student, "scored", marks)
Program 4 — Accept the student's name
name = input("Enter your name: ")
print("Welcome,", name)
Program 5 — Add two user-entered numbers
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
total = first + second
print("Total =", total)
Common Installation and First-Program Errors
- Command not found: Python is not installed correctly or not added to PATH.
- Wrong folder: the terminal cannot find the .py file. Open the correct folder first.
- Incorrect filename: the saved name may be first_program.py.txt because file extensions are hidden.
- SyntaxError: check missing quotation marks, parentheses or colons.
- IndentationError: align statements consistently, normally using four spaces inside a block.
- NameError: check spelling and ensure a variable was assigned before use.
- Using Python 2 material: follow Python 3 syntax and examples.
# Wrong: quotation mark is not closed
print("Hello)
# Correct
print("Hello")
Introduction Revision Questions
- Who created Python and when was its first public release?
- Why is Python called a high-level language?
- What does an interpreter do?
- What is the difference between interactive mode and script mode?
- Why is “Add Python to PATH” important on Windows?
- What is the purpose of the .py extension?
- Name five fields in which Python is used.
- Why must numerical input sometimes be converted with int() or float()?
- What is the difference between Python, IDLE and VS Code?
- Which current major version should a beginner learn?
2. Syntax, Variables & Input
Learn indentation, comments, variables and user input.
Syntax and Indentation
Python uses indentation to form code blocks. Use four spaces consistently. A single-line comment begins with #.
# This is a comment
name = "Aman"
if name == "Aman":
print("Hello", name)Variables and Naming Rules
A variable is created when a value is assigned. Names can contain letters, digits and underscores, but cannot begin with a digit or use a keyword.
student_name = "Simran" age = 18 fee_paid = True print(student_name, age, fee_paid)
Input and Conversion
input() returns text. Convert it before numerical calculation.
name = input("Enter your name: ")
marks = float(input("Enter marks: "))
print(name, "scored", marks)3. Data Types & Conversion
Store numbers, text, truth values and collections.
Built-in Data Types
Common types are int, float, complex, bool, str, list, tuple, set, dict and NoneType.
a = 25 b = 3.14 c = 2 + 3j active = True course = "Python" print(type(a), type(course))
Type Casting
x = "50" y = int(x) z = float(y) print(y + 10) print(z)
4. Operators & Expressions
Perform calculations, comparisons and logical tests.
Operator Types
Arithmetic: + - * / // % ** • Comparison: == != > < >= <= • Logical: and, or, not • Assignment: = += -= • Membership: in, not in • Identity: is, is not.
a, b = 17, 5 print(a + b) print(a / b) print(a // b) print(a % b) print(a ** b)
Mini Calculator
a = float(input("First number: "))
b = float(input("Second number: "))
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Division:", a / b)5. Decision Making
Use if, elif and else to make choices.
if–elif–else
marks = float(input("Enter marks: "))
if marks >= 80:
grade = "A"
elif marks >= 60:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Needs Improvement"
print("Grade:", grade)Nested Decision
age = int(input("Enter age: "))
has_id = input("Do you have ID? y/n: ").lower() == "y"
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Bring your ID")
else:
print("Not eligible")6. Loops
Repeat work efficiently using for and while.
for Loop and range()
number = int(input("Enter a number: "))
for i in range(1, 11):
print(number, "x", i, "=", number * i)while Loop
count = 1
while count <= 5:
print(count)
count += 1Nested Loop Pattern
for row in range(1, 5):
for column in range(row):
print("*", end=" ")
print()* * * * * * * * * *
7. Strings
Work with text using indexing, slicing and methods.
Indexing and Slicing
text = "Python Programming" print(text[0]) print(text[-1]) print(text[0:6]) print(text[::-1])
Useful Methods
message = " learn python step by step "
print(message.strip())
print(message.upper())
print(message.title())
print(message.replace("python", "coding"))
print(message.count("e"))8. Lists & Tuples
Store ordered collections and process their values.
Lists
Lists are ordered, mutable and allow duplicate values.
marks = [72, 88, 65, 91]
marks.append(79)
marks.sort()
print(marks)
print("Highest:", max(marks))
print("Average:", sum(marks) / len(marks))Tuples
Tuples are ordered but immutable.
location = (30.7333, 76.7794) latitude, longitude = location print(latitude, longitude)
9. Sets & Dictionaries
Manage unique values and key-value records.
Sets
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)
print(a & b)
print(a - b)Dictionaries
student = {"name": "Aman", "course": "Python", "marks": 86}
student["city"] = "Sirhind"
for key, value in student.items():
print(key, ":", value)10. Functions & Recursion
Create reusable blocks of code.
Parameters and Return Values
def calculate_total(price, quantity=1):
return price * quantity
print(calculate_total(250, 3))
print(calculate_total(price=100, quantity=5))*args and Lambda
def total(*numbers):
return sum(numbers)
square = lambda x: x * x
print(total(5, 10, 15))
print(square(6))Recursion
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))11. Modules & Packages
Reuse standard and custom Python code.
Importing Modules
import math import random from datetime import date print(math.sqrt(81)) print(random.randint(1, 10)) print(date.today())
Installing Packages
python -m pip install package_name
12. File Handling
Create, read and append files safely.
Write and Read Text
with open("students.txt", "w", encoding="utf-8") as file:
file.write("Aman, Python, 86\n")
with open("students.txt", "r", encoding="utf-8") as file:
print(file.read())Append Records
name = input("Student name: ")
marks = input("Marks: ")
with open("marks.txt", "a", encoding="utf-8") as file:
file.write(f"{name},{marks}\n")13. Exception Handling
Prevent crashes and show helpful messages.
try, except, else and finally
try:
a = float(input("First number: "))
b = float(input("Second number: "))
result = a / b
except ValueError:
print("Please enter valid numbers.")
except ZeroDivisionError:
print("A number cannot be divided by zero.")
else:
print("Result:", result)
finally:
print("Program finished.")14. Object-Oriented Python
Use classes, objects, constructors and inheritance.
Class, Object and Constructor
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print(self.name, "scored", self.marks)
s1 = Student("Simran", 92)
s1.display()Inheritance and Overriding
class Course:
def details(self):
print("General course")
class PythonCourse(Course):
def details(self):
print("Python practical course")
course = PythonCourse()
course.details()15. Projects & Next Steps
Combine your skills in complete applications.
Project — Number Guessing Game
import random
secret = random.randint(1, 20)
attempts = 0
while True:
guess = int(input("Guess 1 to 20: "))
attempts += 1
if guess == secret:
print("Correct in", attempts, "attempts!")
break
print("Too low" if guess < secret else "Too high")More Project Ideas
- Menu-driven calculator
- Student result manager
- Contact book
- Expense tracker
- Quiz with score
- Library manager using classes
- To-do list
Final Revision Checklist
Can you use input/output, conditions, loops, collections, functions, files, errors and classes without copying? If yes, begin an independent project.
16. Number Program Lab
Strengthen logic through small numerical programs.
Program 1 — Positive, Negative or Zero
Logic: Compare the number with zero. Only one of the three conditions can be true.
number = float(input("Enter a number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")Program 2 — Largest of Three Numbers
Logic: A number is largest only when it is greater than or equal to both remaining numbers.
a = float(input("First: "))
b = float(input("Second: "))
c = float(input("Third: "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Largest =", largest)Program 3 — Factorial Using a Loop
Logic: The factorial of n is the product 1 × 2 × ... × n. The factorial of 0 is 1.
n = int(input("Enter a non-negative integer: "))
factorial = 1
if n < 0:
print("Factorial is not defined for negative numbers")
else:
for value in range(1, n + 1):
factorial *= value
print("Factorial =", factorial)Program 4 — Prime Number Test
Logic: A prime number is greater than 1 and has no divisor from 2 through its square root.
n = int(input("Enter an integer: "))
is_prime = n > 1
divisor = 2
while divisor * divisor <= n and is_prime:
if n % divisor == 0:
is_prime = False
divisor += 1
print("Prime" if is_prime else "Not prime")Program 5 — Fibonacci Series
Logic: Each new term is the sum of the previous two terms.
terms = int(input("How many terms? "))
a, b = 0, 1
for _ in range(terms):
print(a, end=" ")
a, b = b, a + bFor 7 terms: 0 1 1 2 3 5 8
Program 6 — Armstrong Number
Logic: Raise every digit to the power equal to the number of digits, then add the results.
number = int(input("Enter a positive integer: "))
digits = str(number)
power = len(digits)
total = sum(int(digit) ** power for digit in digits)
print("Armstrong number" if total == number else "Not an Armstrong number")17. Collection Program Lab
Use lists, tuples, sets and dictionaries to solve practical problems.
Program 7 — Second Largest List Value
Logic: Remove duplicates, sort the remaining values and take the second value from the end.
numbers = [12, 45, 7, 45, 30, 18]
unique = sorted(set(numbers))
if len(unique) >= 2:
print("Second largest =", unique[-2])
else:
print("A second distinct value is not available")Program 8 — Separate Even and Odd Values
numbers = [11, 20, 33, 42, 55, 60]
even = [n for n in numbers if n % 2 == 0]
odd = [n for n in numbers if n % 2 != 0]
print("Even:", even)
print("Odd:", odd)Program 9 — Frequency of Every Value
values = [2, 4, 2, 5, 4, 2]
frequency = {}
for value in values:
frequency[value] = frequency.get(value, 0) + 1
print(frequency){2: 3, 4: 2, 5: 1}Program 10 — Student Marks Dictionary
students = {
"Aman": [78, 82, 74],
"Simran": [92, 88, 95],
"Gurpreet": [65, 71, 69]
}
for name, marks in students.items():
average = sum(marks) / len(marks)
print(f"{name}: {average:.2f}")Program 11 — Merge Two Dictionaries
personal = {"name": "Riya", "city": "Amloh"}
academic = {"course": "Python", "marks": 89}
student = {**personal, **academic}
print(student)18. String Program Lab
Understand text processing through useful programs.
Program 12 — Palindrome Checker
Logic: Normalise the text and compare it with its reverse.
text = input("Enter text: ")
clean = "".join(ch.lower() for ch in text if ch.isalnum())
print("Palindrome" if clean == clean[::-1] else "Not palindrome")Program 13 — Count Vowels, Consonants, Digits and Spaces
text = input("Enter a sentence: ")
vowels = consonants = digits = spaces = 0
for ch in text.lower():
if ch in "aeiou":
vowels += 1
elif ch.isalpha():
consonants += 1
elif ch.isdigit():
digits += 1
elif ch.isspace():
spaces += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Digits:", digits)
print("Spaces:", spaces)Program 14 — Word Frequency
sentence = input("Enter a sentence: ").lower()
words = sentence.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
for word, count in frequency.items():
print(word, count)Program 15 — Password Strength Check
password = input("Create password: ")
long_enough = len(password) >= 8
has_upper = any(ch.isupper() for ch in password)
has_lower = any(ch.islower() for ch in password)
has_digit = any(ch.isdigit() for ch in password)
has_symbol = any(not ch.isalnum() for ch in password)
if all([long_enough, has_upper, has_lower, has_digit, has_symbol]):
print("Strong password")
else:
print("Use 8+ characters with upper, lower, digit and symbol")19. OOP & File Program Lab
Connect classes, validation and permanent file storage.
Program 16 — Bank Account Class
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
else:
print("Insufficient balance or invalid amount")
def display(self):
print(self.owner, "Balance:", self.balance)
account = BankAccount("Aman", 1000)
account.deposit(500)
account.withdraw(300)
account.display()Program 17 — Inheritance: Employee and Manager
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def details(self):
return f"{self.name}: ₹{self.salary}"
class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary)
self.department = department
def details(self):
return f"{super().details()} — {self.department}"
m = Manager("Simran", 45000, "Admissions")
print(m.details())Program 18 — Safe Student Record File
def add_student(filename, name, marks):
with open(filename, "a", encoding="utf-8") as file:
file.write(f"{name},{marks}\n")
def show_students(filename):
try:
with open(filename, "r", encoding="utf-8") as file:
for line in file:
name, marks = line.strip().split(",")
print(f"{name}: {marks}")
except FileNotFoundError:
print("No record file exists yet.")
add_student("student_records.txt", "Riya", 91)
show_students("student_records.txt")Program 19 — JSON Data Storage
JSON stores lists and dictionaries in a widely used text format.
import json
students = [{"name": "Aman", "marks": 85}, {"name": "Riya", "marks": 91}]
with open("students.json", "w", encoding="utf-8") as file:
json.dump(students, file, indent=2)
with open("students.json", "r", encoding="utf-8") as file:
saved_students = json.load(file)
print(saved_students)20. Practice Assignments & Viva Questions
Check understanding without immediately looking at a solution.
20 Beginner Programming Assignments
- Calculate simple interest and total amount.
- Convert kilometres to miles.
- Swap two values with and without a third variable.
- Check whether a year is a leap year.
- Display the multiplication table of a number.
- Calculate the sum of the first n natural numbers.
- Reverse an integer and find its digit sum.
- Print all prime numbers in a given range.
- Find HCF and LCM of two integers.
- Count positive, negative and zero values in a list.
- Remove duplicate list elements while preserving order.
- Find common elements in two lists.
- Sort student records by marks.
- Count every character in a string.
- Find the longest word in a sentence.
- Create a menu-driven calculator using functions.
- Save and search contacts in a text file.
- Build a quiz using a list of dictionaries.
- Create Product and Cart classes.
- Build a to-do list that saves tasks in JSON.
Concept Viva Questions
- Why is indentation compulsory in Python?
- What is the difference between = and ==?
- Why does input() return a string?
- How are list and tuple different?
- When should a set be used?
- What does a dictionary key do?
- What is the difference between break and continue?
- What is a function return value?
- What is local scope?
- Why is with open() preferred?
- What problem does exception handling solve?
- What are class, object, attribute and method?
- What does inheritance reuse?
- What is method overriding?
- Why should programs validate user input?
Debugging Checklist
- Read the last line of the error message first.
- Check spelling, brackets, quotes, colons and indentation.
- Confirm whether input needs int() or float().
- Print intermediate values to understand program flow.
- Test normal, boundary and invalid inputs.
- Change only one part at a time and run again.
- Never hide every error with a broad except unless you also report it.