Guides › Python Programming
Python Programming: Complete Beginner to Advanced Guide
Learn Python from scratch with variables, data types, conditions, loops, functions, collections, exceptions, modules, file handling, and practical coding exercises.
Python Programming: Complete Beginner to Advanced Guide
Python is a popular, general-purpose programming language known for its readable syntax and broad ecosystem. It is used in web development, automation, data analysis, artificial intelligence, testing, and scripting.
This guide introduces Python step by step, from your first program to functions, object-oriented programming fundamentals, file handling, and practical projects.
1. What Is Python?
Python is a high-level programming language designed to make code readable and expressive.
Common uses include:
- Web development
- Task automation
- Data analysis
- Artificial intelligence and machine learning
- Testing and scripting
- Educational projects
Python is beginner-friendly, but mastering it still requires practice and problem-solving.
2. Install Python and Set Up Your Editor
To get started:
- Install a current stable version of Python from the official Python website.
- Install an editor such as VS Code, or use another Python-compatible IDE.
- Open a terminal and verify the installation with
python --versionorpython3 --version. - Create a file named
main.py. - Run it using your Python interpreter.
You can also begin in an online Python environment if you do not want to install anything yet.
3. Your First Python Program
print("Hello, World!")
print("Welcome to Python programming")
The print() function displays information on the screen.
Python uses indentation to define code blocks. Consistent indentation is important for readable, correct programs.
4. Variables and Data Types
Variables give names to values.
name = "Shubham"
age = 21
height = 1.63
is_learning = True
print(name)
print(age)
print(height)
print(is_learning)
Common built-in types include:
str: textint: integersfloat: decimal numbersbool: True or Falselist: ordered, mutable collectiontuple: ordered, immutable collectiondict: key-value mappingset: collection of unique elements
Use type(value) to inspect a value's type.
5. Taking User Input
The input() function reads text entered by the user.
name = input("Enter your name: ")
print("Hello,", name)
Input is returned as a string. Convert it when a numeric value is needed.
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
For production programs, validate user input and handle invalid conversions.
6. Operators
Python supports arithmetic operators such as +, -, *, /, //, %, and **.
a = 10
b = 3
print(a + b)
print(a // b)
print(a % b)
print(a ** b)
Comparison operators include ==, !=, <, >, <=, and >=.
Logical operators include and, or, and not.
7. Conditions
Conditions let a program make decisions.
marks = int(input("Enter your marks: "))
if marks >= 80:
print("Excellent")
elif marks >= 60:
print("Good")
elif marks >= 40:
print("Passed")
else:
print("Keep practising")
The conditions are checked from top to bottom. The first matching branch executes.
8. Loops
Loops repeat a block of code.
For Loop
for number in range(1, 6):
print(number)
While Loop
count = 1
while count <= 5:
print(count)
count += 1
Learn break, continue, and loop nesting. Make sure while-loop conditions eventually change when termination is intended.
9. Strings
Strings represent text.
message = "Learn Python"
print(message.lower())
print(message.upper())
print(message.replace("Python", "Coding"))
print(len(message))
print(message[0])
Learn indexing, slicing, searching, splitting, joining, and formatted strings.
name = "Shubham"
print(f"Welcome, {name}!")
Strings are immutable: operations create new strings instead of changing individual characters in place.
10. Lists, Tuples, Sets, and Dictionaries
Lists
numbers = [10, 20, 30]
numbers.append(40)
numbers.remove(20)
print(numbers)
Lists are ordered and mutable.
Tuples
coordinates = (10, 20)
print(coordinates[0])
Tuples are ordered and cannot be reassigned item by item.
Sets
unique_numbers = {1, 2, 2, 3}
print(unique_numbers)
Sets store unique elements.
Dictionaries
student = {
"name": "Shubham",
"marks": 85
}
print(student["name"])
print(student.get("marks"))
Dictionaries store key-value pairs. Learn when each collection type is appropriate.
11. Functions
Functions make code reusable and easier to maintain.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Learn parameters, return values, default arguments, keyword arguments, scope, and docstrings.
A function should ideally perform a clear, focused task.
12. List Comprehensions
List comprehensions provide a concise way to create lists.
squares = [number ** 2 for number in range(1, 6)]
print(squares)
They can also include conditions:
even_numbers = [
number for number in range(1, 11)
if number % 2 == 0
]
print(even_numbers)
Prefer readable code over overly complicated one-line expressions.
13. Modules and Packages
A module is a Python file that can contain reusable functions, classes, and variables.
import math
print(math.sqrt(25))
print(math.pi)
Learn how to import standard-library modules, create your own modules, organise packages, and use a virtual environment for project dependencies.
14. Exception Handling
Exceptions allow a program to handle certain runtime errors.
try:
number = int(input("Enter a number: "))
print(100 / number)
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("The number must not be zero.")
Handle expected errors clearly. Avoid hiding every error with a broad exception handler.
15. File Handling
Files let programs save information between runs.
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("My first Python note")
with open("notes.txt", "r", encoding="utf-8") as file:
print(file.read())
Common modes include:
r: readw: write, replacing existing contentsa: appendb: binary mode
The with statement helps ensure that files are properly closed.
16. Object-Oriented Programming Basics
Classes define the structure and behaviour of objects.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def introduce(self):
print(f"I'm {self.name}. My marks are {self.marks}.")
student = Student("Shubham", 85)
student.introduce()
Learn classes, objects, constructors, instance methods, inheritance, encapsulation, and composition.
Use object-oriented programming when it makes the design clearer; not every small script needs classes.
17. Useful Standard-Library Modules
Python includes modules for many common tasks.
math: mathematical functionsrandom: random selections and valuesdatetime: dates and timespathlib: filesystem pathsjson: JSON encoding and decodingcsv: CSV file handlingcollections: specialised collection typesstatistics: basic statistical calculations
Explore the official documentation before adding third-party dependencies.
18. Debugging and Testing
Learn to:
- Read tracebacks from the bottom up
- Print or inspect intermediate values
- Use breakpoints in your editor
- Reproduce errors with small examples
- Write tests for important functions
Example:
def square(number):
return number * number
assert square(4) == 16
assert square(0) == 0
For larger projects, learn Python's unittest framework or another suitable testing tool.
19. Beginner Python Projects
Build these projects in order:
- Calculator: practise input, operators, and functions.
- Number Guessing Game: practise conditions and loops.
- Quiz Application: practise lists, dictionaries, and scoring.
- To-Do List: practise functions and data storage.
- Expense Tracker: practise records, calculations, and file handling.
- File Organiser: practise paths and filesystem operations.
- Weather App: practise APIs, JSON, and error handling.
- Automation Script: automate a repetitive task safely.
Start with simple versions. Add persistence, validation, testing, and a better interface as you progress.
20. Python Learning Roadmap
| Stage | Topics | Practice |
|---|---|---|
| Week 1 | Syntax, variables, input, operators | Small calculations |
| Week 2 | Conditions, loops, strings | Number and text exercises |
| Week 3 | Lists, dictionaries, functions | Quiz application |
| Week 4 | Modules, exceptions, files | To-do list |
| Weeks 5–6 | OOP, testing, project structure | Expense tracker |
| Weeks 7–8 | APIs or automation | Practical portfolio project |
This is a suggested schedule. Adjust it to your experience and study time.
21. Common Python Beginner Mistakes
- Mixing tabs and spaces
- Forgetting that input returns a string
- Using
=instead of==for comparison - Ignoring error messages
- Writing the same code repeatedly instead of using functions
- Catching errors without understanding them
- Hardcoding paths and sensitive credentials
- Copying solutions without practising independently
Write small programs regularly and explain each important line in your own words.
Conclusion
Python is a versatile language that can lead to automation, backend development, data analysis, and AI projects. Start with the fundamentals, practise daily, and build small programs before moving to larger applications.
Your first task: Create a calculator, then a number guessing game, and finally a to-do list that saves data to a file.
Keep practising, keep building, and turn your ideas into working programs!
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.