Introduction to Python
Python is a powerful and easy-to-learn programming language used for web development, automation, data science, artificial intelligence, and more.
It is beginner-friendly and widely used by professionals to build real-world applications.
Why Learn Python?
| Feature | Description |
|---|---|
| Easy Syntax | Simple and readable like English |
| Versatile | Used in web, AI, automation, apps |
| High Demand | Popular in jobs and freelancing |
| Large Community | Lots of tutorials and support available |
Steps to Run Your First Python Program
| Step | Action |
|---|---|
| 1 | Install Python on your system |
| 2 | Open code editor (VS Code) |
| 3 | Create a new file hello.py |
| 4 | Write and run the program |
Example
print("Hello, World!")
Where Python is Used
- Web Development
- Automation & Scripting
- Game Development
- Data Science & AI
- Desktop Applications
Important Concepts
- Python is an interpreted language
- No need to compile code
- Indentation is important
Tips
- Practice daily
- Start with small programs
- Focus on logic building
Common Mistakes
- Ignoring indentation ❌
- Copy-paste without understanding ❌
- Not practicing enough ❌
Install Python & Setup
To start programming in Python, you first need to install it on your computer and set up a proper development environment.
This section will guide you step-by-step to install Python and configure your system correctly.
System Requirements
| Requirement | Description |
|---|---|
| Operating System | Windows / macOS / Linux |
| RAM | Minimum 4 GB |
| Storage | At least 500 MB free space |
| Internet | Required for download and setup |
Steps to Install Python
| Step | Action |
|---|---|
| 1 | Go to official Python website |
| 2 | Download latest version |
| 3 | Run installer |
| 4 | Check "Add Python to PATH" |
| 5 | Click Install Now |
Verify Installation
After installation, check if Python is installed correctly:
python --version
If installed properly, it will display the Python version.
Install Code Editor (VS Code)
| Step | Action |
|---|---|
| 1 | Download VS Code |
| 2 | Install the software |
| 3 | Open VS Code |
| 4 | Install Python extension |
Steps to Run Python in VS Code
| Step | Action |
|---|---|
| 1 | Open VS Code |
| 2 | Create new file main.py |
| 3 | Write Python code |
| 4 | Click Run ▶️ button |
Example
print("Python is installed successfully!")
Important Concepts
- PATH allows Python to run from any folder
- .py files are Python program files
- Interpreter runs Python code line by line
Tips
- Always install latest Python version
- Use VS Code for better experience
- Keep your setup clean and organized
Common Mistakes
- Not adding Python to PATH ❌
- Installing wrong version ❌
- Forgetting to install extension in VS Code ❌
First Python Program
Writing your first program is the beginning of your journey in Python. It helps you understand how code works and how output is displayed.
The most common first program is the Hello World program.
Basic Syntax of Python Program
| Concept | Description |
|---|---|
| print() | Used to display output on screen |
| Quotes | Text must be inside " " or ' ' |
| Case Sensitivity | Python is case-sensitive (Print ≠ print) |
Steps to Write First Program
| Step | Action |
|---|---|
| 1 | Open VS Code |
| 2 | Create a new file hello.py |
| 3 | Write Python code |
| 4 | Run the program |
Example
print("Hello, World!")
Output
Hello, World!
More Examples
print("Welcome to Python")
print("My name is Mohit")
print(10 + 5)
When to Use print()
- Displaying messages to user
- Showing output of calculations
- Debugging code
Important Concepts
- Python executes code line by line
- Each print() statement runs separately
- No semicolon required at end
Tips
- Always use correct spelling: print
- Use quotes for text
- Run code frequently to test
Common Mistakes
- Using Print instead of print ❌
- Forgetting quotes ❌
- Missing parentheses ❌
🎯 Practice Task
- Write a program to print your name
- Print your school or college name
- Print any number calculation (e.g., 20 + 30)
- Try printing 3 lines of text
Python Syntax
Python Syntax refers to the set of rules that define how Python programs are written and executed. It is simple, clean, and easy to understand compared to other programming languages.
Learning syntax is important because even a small mistake can cause errors in your program.
Basic Syntax Rules
| Rule | Description |
|---|---|
| Indentation | Spaces are used to define blocks of code |
| Case Sensitive | Variables and keywords are case-sensitive |
| No Semicolon | No need to end lines with ; |
| Statements | Each line is a statement executed by Python |
Indentation Example
if 5 > 2:
print("5 is greater than 2")
Indentation is mandatory in Python. Without proper indentation, code will give an error.
Case Sensitivity Example
name = "Mohit"
Name = "Kumar"
print(name)
print(Name)
Multiple Statements
print("Hello")
print("Welcome to Python")
print("Learning Syntax")
Comments in Python
Comments are used to explain code and are ignored during execution.
# This is a single-line comment
print("Hello") # This is an inline comment
When to Follow Syntax Rules
- Writing any Python program
- Using conditions and loops
- Defining functions
- Working with classes
Important Concepts
- Indentation replaces curly braces { }
- Each block must have same indentation
- Python code is easy to read due to clean syntax
Tips
- Use 4 spaces for indentation
- Keep code clean and readable
- Use comments to explain logic
Common Mistakes
- Wrong indentation ❌
- Mixing tabs and spaces ❌
- Using wrong case in variables ❌
🎯 Practice Task
- Write an if statement with correct indentation
- Create 2 variables with different cases
- Add comments in your program
- Run code and fix syntax errors
Variables in Python
A variable is used to store data in a program. It acts like a container that holds values such as numbers, text, or other data.
In Python, you do not need to declare the type of a variable. It is automatically assigned.
Creating Variables
| Example | Description |
|---|---|
| x = 10 | Stores integer value |
| name = "Mohit" | Stores text (string) |
| price = 99.5 | Stores decimal (float) |
| is_active = True | Stores boolean value |
Rules for Naming Variables
| Rule | Example |
|---|---|
| Must start with letter or underscore | name, _value |
| Cannot start with number | ❌ 1name |
| No spaces allowed | ❌ my name |
| Use meaningful names | student_name |
Example
name = "Mohit"
age = 20
marks = 85.5
print(name)
print(age)
print(marks)
Multiple Assignment
x, y, z = 10, 20, 30
print(x, y, z)
Changing Variable Value
x = 5
x = 10 # value changed
print(x)
When to Use Variables
- Storing user input
- Performing calculations
- Saving data for reuse
- Building programs and applications
Important Concepts
- Variables do not need type declaration
- Value can be changed anytime
- Variable names should be meaningful
Tips
- Use clear names like student_name
- Follow lowercase naming style
- Avoid using reserved keywords
Common Mistakes
- Using numbers at start ❌
- Using spaces in names ❌
- Confusing uppercase/lowercase ❌
🎯 Practice Task
- Create variables for name, age, and marks
- Print all variables
- Change value of one variable
- Use multiple assignment
Data Types in Python
Data Types define the type of value a variable can hold. Python automatically detects the data type based on the value assigned.
Understanding data types is important for performing operations correctly in programs.
Common Data Types
| Data Type | Example | Description |
|---|---|---|
| int | 10 | Whole numbers |
| float | 10.5 | Decimal numbers |
| str | "Hello" | Text or string |
| bool | True / False | Boolean values |
Example
x = 10 # int
y = 5.5 # float
name = "Mohit" # string
is_active = True # boolean
print(x)
print(y)
print(name)
print(is_active)
Checking Data Type
You can check the type of a variable using type() function.
x = 10
print(type(x))
Type Conversion
Convert one data type into another using built-in functions.
x = 10
y = float(x) # convert int to float
print(y)
When to Use Data Types
- Performing calculations (int, float)
- Working with text (string)
- Making decisions (boolean)
- Storing structured data
Important Concepts
- Python is dynamically typed
- Same variable can store different data types
- Operations depend on data type
Tips
- Use correct data type for correct operation
- Use type() to debug issues
- Convert types carefully
Common Mistakes
- Mixing string and number ❌
- Wrong type conversion ❌
- Assuming type without checking ❌
🎯 Practice Task
- Create variables of all data types
- Use type() to check each variable
- Convert int to float
- Try converting string to number
Input & Output in Python
Input allows users to enter data into a program, while Output displays the result on the screen.
Python provides simple functions like input() and print() to handle user interaction.
Output using print()
| Example | Description |
|---|---|
| print("Hello") | Displays text on screen |
| print(10 + 5) | Displays result of calculation |
| print("Hi", "Mohit") | Prints multiple values |
Input using input()
The input() function takes user input as a string.
name = input("Enter your name: ")
print("Hello", name)
Example Program
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Name:", name)
print("Age:", age)
Type Conversion with Input
Since input() returns a string, you need to convert it for calculations.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum = num1 + num2
print("Sum is:", sum)
Formatted Output
name = "Mohit"
age = 20
print(f"My name is {name} and I am {age} years old")
When to Use Input & Output
- Taking user details
- Performing calculations
- Building interactive programs
- Displaying results clearly
Important Concepts
- input() always returns string
- Use int() or float() for numbers
- print() displays output instantly
Tips
- Use clear prompts in input()
- Always convert input when needed
- Use f-strings for clean output
Common Mistakes
- Not converting input to number ❌
- Forgetting quotes in print ❌
- Confusing string with number ❌
🎯 Practice Task
- Take name input and print greeting
- Take two numbers and print sum
- Use f-string for formatted output
- Create simple calculator using input()
Operators in Python
Operators are symbols used to perform operations on variables and values. They are used for calculations, comparisons, and logical decisions.
Python provides different types of operators for different purposes.
Types of Operators
| Type | Example | Description |
|---|---|---|
| Arithmetic | +, -, *, / | Used for calculations |
| Comparison | ==, !=, >, << /td> | Compare values |
| Logical | and, or, not | Combine conditions |
| Assignment | =, +=, -= | Assign values to variables |
Arithmetic Operators
x = 10
y = 5
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
print(x % y) # Modulus
Comparison Operators
x = 10
y = 5
print(x > y)
print(x == y)
print(x != y)
Logical Operators
x = 10
print(x > 5 and x < 20)
print(x > 5 or x > 20)
print(not(x > 5))
Assignment Operators
x = 10
x += 5 # x = x + 5
x -= 3 # x = x - 3
print(x)
Example Program
num1 = 20
num2 = 10
print("Addition:", num1 + num2)
print("Is num1 greater?", num1 > num2)
When to Use Operators
- Performing calculations
- Making decisions
- Updating variable values
- Combining conditions
Important Concepts
- Operators follow precedence rules
- Comparison operators return True or False
- Logical operators combine conditions
Tips
- Use parentheses for clarity
- Understand operator precedence
- Use logical operators carefully
Common Mistakes
- Using = instead of == ❌
- Wrong operator precedence ❌
- Confusing logical conditions ❌
🎯 Practice Task
- Perform all arithmetic operations
- Compare two numbers
- Use logical operators in conditions
- Update variable using assignment operators
If Else Conditions in Python
If Else statements are used to make decisions in a program. They allow your code to execute different blocks based on conditions.
Conditions return either True or False, and based on that, Python decides which block of code to run.
Basic If Statement
age = 18
if age >= 18:
print("You are eligible to vote")
If Else Statement
age = 16
if age >= 18:
print("Eligible")
else:
print("Not Eligible")
If Elif Else Statement
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Nested If Statement
age = 20
citizen = True
if age >= 18:
if citizen:
print("Eligible to vote")
Comparison Operators Used
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
Example Program
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
When to Use If Else
- Making decisions in programs
- Validating user input
- Creating conditions in games
- Controlling program flow
Important Concepts
- Indentation is required
- Condition must return True or False
- elif is used for multiple conditions
Tips
- Keep conditions simple and clear
- Use logical operators for complex conditions
- Test all possible cases
Common Mistakes
- Missing indentation ❌
- Using = instead of == ❌
- Wrong condition logic ❌
🎯 Practice Task
- Check if a number is positive or negative
- Create a grade system using marks
- Check if a number is even or odd
- Use nested if for login validation
Loops in Python (for, while)
Loops are used to repeat a block of code multiple times. They help reduce repetition and make programs efficient.
Python mainly provides two types of loops: for loop and while loop.
Types of Loops
| Loop | Description |
|---|---|
| for loop | Used when number of iterations is known |
| while loop | Used when condition-based repetition is required |
For Loop Example
for i in range(1, 6):
print(i)
This loop prints numbers from 1 to 5.
While Loop Example
i = 1
while i <= 5:
print(i)
i += 1
This loop runs until the condition becomes false.
Break Statement
Used to stop the loop immediately.
for i in range(1, 10):
if i == 5:
break
print(i)
Continue Statement
Skips current iteration and continues with next.
for i in range(1, 6):
if i == 3:
continue
print(i)
Nested Loops
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Example Program
# Print multiplication table of 5
for i in range(1, 11):
print("5 x", i, "=", 5 * i)
When to Use Loops
- Repeating tasks
- Iterating over data
- Generating patterns
- Processing lists and collections
Important Concepts
- Infinite loop occurs if condition never becomes false
- range() is commonly used with for loop
- Loops can be nested
Tips
- Use for loop when iterations are fixed
- Use while loop for conditions
- Be careful with infinite loops
Common Mistakes
- Forgetting to update variable in while loop ❌
- Wrong range values ❌
- Creating infinite loops ❌
🎯 Practice Task
- Print numbers from 1 to 10 using for loop
- Print numbers using while loop
- Create multiplication table
- Use break and continue in loop
Lists in Python
A list is a collection of items stored in a single variable. It is one of the most commonly used data structures in Python.
Lists can store multiple values of different data types and are ordered and changeable.
Creating a List
| Example | Description |
|---|---|
| numbers = [1, 2, 3] | List of integers |
| names = ["Ram", "Shyam"] | List of strings |
| mixed = [10, "Raman", 5.5] | Mixed data types |
Accessing List Elements
students = ["Ram", "Shyam", "Aman"]
print(students[0]) # First element
print(students[1]) # Second element
Negative Indexing
print(students[-1]) # Last element
List Operations
| Operation | Example |
|---|---|
| Add Item | list.append("New") |
| Insert Item | list.insert(1, "Item") |
| Remove Item | list.remove("Ram") |
| Delete Item | del list[0] |
Example Program
fruits = ["Apple", "Banana", "Mango"]
fruits.append("Orange")
fruits.remove("Banana")
print(fruits)
Looping Through List
for item in fruits:
print(item)
When to Use Lists
- Storing multiple values
- Managing collections of data
- Working with user input lists
- Building applications
Important Concepts
- Lists are ordered and indexed
- Lists are mutable (can be changed)
- Allow duplicate values
Tips
- Use meaningful list names
- Use loops to process lists
- Keep lists organized
Common Mistakes
- Index out of range ❌
- Removing non-existing item ❌
- Confusing list with string ❌
🎯 Practice Task
- Create a list of 5 numbers
- Add and remove elements
- Print all elements using loop
- Access first and last element
Tuples & Sets in Python
Tuples and Sets are important data structures in Python used to store collections of data.
While both store multiple values, they have different properties and use cases.
Tuple (Immutable Collection)
A tuple is an ordered collection of items that cannot be changed after creation.
| Feature | Description |
|---|---|
| Ordered | Items maintain order |
| Immutable | Cannot be changed |
| Allows Duplicates | Same values allowed |
Tuple Example
colors = ("Red", "Green", "Blue")
print(colors[0])
Set (Unordered Collection)
A set is an unordered collection of unique items. It does not allow duplicate values.
| Feature | Description |
|---|---|
| Unordered | No fixed order |
| No Duplicates | Unique values only |
| Mutable | Can add or remove items |
Set Example
numbers = {1, 2, 3, 3, 4}
print(numbers) # Duplicate removed
Set Operations
| Operation | Example |
|---|---|
| Add Item | set.add(5) |
| Remove Item | set.remove(2) |
| Union | set1 | set2 |
| Intersection | set1 & set2 |
Example Program
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
When to Use Tuples & Sets
- Tuple → When data should not change
- Set → When you need unique values
- Set → Removing duplicates from list
- Tuple → Fixed data like coordinates
Important Concepts
- Tuple uses ( ) and Set uses { }
- Set does not maintain order
- Tuple is faster than list
Tips
- Use tuple for fixed data
- Use set for unique elements
- Convert list to set to remove duplicates
Common Mistakes
- Trying to change tuple ❌
- Expecting ordered data in set ❌
- Confusing {} with dictionary ❌
🎯 Practice Task
- Create a tuple and access elements
- Create a set with duplicate values
- Perform union and intersection
- Convert list into set
Dictionaries in Python
A dictionary is a collection of data stored in key-value pairs. It is used to store related information in a structured way.
Dictionaries are unordered, changeable, and do not allow duplicate keys.
Creating a Dictionary
| Example | Description |
|---|---|
| student = {"name": "Raman", "age": 20} | Basic dictionary |
| data = {"a": 1, "b": 2} | Key-value pairs |
| mixed = {"name": "Raman", "marks": 85.5} | Mixed data types |
Accessing Values
student = {"name": "Raman", "age": 20}
print(student["name"])
print(student.get("age"))
Adding & Updating Items
student["marks"] = 90 # Add new key
student["age"] = 21 # Update value
Removing Items
student.pop("age")
del student["name"]
Dictionary Methods
| Method | Description |
|---|---|
| keys() | Returns all keys |
| values() | Returns all values |
| items() | Returns key-value pairs |
Looping Through Dictionary
for key, value in student.items():
print(key, ":", value)
Example Program
student = {
"name": "Raman",
"age": 20,
"marks": 85
}
print("Name:", student["name"])
print("Marks:", student["marks"])
When to Use Dictionaries
- Storing structured data
- Managing user details
- Working with APIs and JSON data
- Building real-world applications
Important Concepts
- Keys must be unique
- Values can be any data type
- Access using key, not index
Tips
- Use meaningful keys
- Use get() to avoid errors
- Keep data structured
Common Mistakes
- Using duplicate keys ❌
- Accessing non-existing key ❌
- Confusing dictionary with list ❌
🎯 Practice Task
- Create a student dictionary
- Add and update values
- Loop through dictionary
- Use keys(), values(), items()
Functions in Python
A function is a block of code that performs a specific task. It helps in reusing code and makes programs more organized.
Instead of writing the same code again and again, you can define a function and call it whenever needed.
Creating a Function
| Keyword | Description |
|---|---|
| def | Used to define a function |
| () | Used to pass parameters |
| return | Returns value from function |
Basic Function Example
def greet():
print("Hello, Welcome!")
greet()
Function with Parameters
def greet(name):
print("Hello", name)
greet("Raman")
Function with Return Value
def add(a, b):
return a + b
result = add(10, 5)
print(result)
Default Parameters
def greet(name="User"):
print("Hello", name)
greet()
greet("Raman")
Lambda Function
add = lambda a, b: a + b
print(add(3, 4))
Example Program
def square(num):
return num * num
print(square(5))
When to Use Functions
- Reusing code
- Organizing large programs
- Improving readability
- Breaking complex problems into smaller parts
Important Concepts
- Function must be defined before calling
- Parameters receive input values
- Return sends output back
Tips
- Use meaningful function names
- Keep functions small and simple
- Avoid repeating code
Common Mistakes
- Forgetting to call function ❌
- Missing return statement ❌
- Wrong number of arguments ❌
🎯 Practice Task
- Create a function to add two numbers
- Create a function with default parameter
- Use lambda to multiply two numbers
- Create function to calculate square
Modules & Packages in Python
Modules and Packages help organize Python code into reusable files and folders. They make programs more structured and easier to manage.
Instead of writing all code in one file, you can split it into multiple modules.
What is a Module?
A module is a file that contains Python code (functions, variables, classes). It has a .py extension.
| Example | Description |
|---|---|
| math.py | Custom module file |
| import math | Built-in module |
Using Built-in Modules
import math
print(math.sqrt(16))
print(math.pi)
Import Specific Functions
from math import sqrt
print(sqrt(25))
Create Your Own Module
# file: mymodule.py
def greet(name):
print("Hello", name)
# main file
import mymodule
mymodule.greet("Raman")
What is a Package?
A package is a folder that contains multiple modules. It helps organize large projects.
Package Structure Example
myproject/
│
├── main.py
├── utils/
│ ├── __init__.py
│ ├── math_utils.py
│ └── string_utils.py
Import from Package
from utils.math_utils import add
print(add(5, 3))
When to Use Modules & Packages
- Organizing large projects
- Reusing code
- Separating logic into files
- Building scalable applications
Important Concepts
- Module = Single file
- Package = Folder of modules
- Use import to access modules
Tips
- Keep modules small and focused
- Use meaningful names
- Organize code logically
Common Mistakes
- Wrong import path ❌
- Missing __init__.py in package ❌
- Naming conflict with built-in modules ❌
🎯 Practice Task
- Use math module to calculate square root
- Create your own module
- Import and use custom function
- Create a simple package structure
File Handling in Python
File Handling allows you to create, read, write, and manage files. It is useful for storing data permanently instead of losing it after program execution.
Python provides built-in functions to work with files easily.
Opening a File
Use the open() function to open a file.
file = open("data.txt", "r")
| Mode | Description |
|---|---|
| "r" | Read file |
| "w" | Write (overwrite file) |
| "a" | Append (add data) |
| "x" | Create new file |
Reading a File
file = open("data.txt", "r")
print(file.read())
file.close()
Writing to a File
file = open("data.txt", "w")
file.write("Hello Python")
file.close()
Appending to a File
file = open("data.txt", "a")
file.write("\nNew Line Added")
file.close()
Using with Statement (Best Practice)
with open("data.txt", "r") as file:
print(file.read())
The with statement automatically closes the file.
Example Program
with open("student.txt", "w") as file:
file.write("Name: Raman\nMarks: 90")
with open("student.txt", "r") as file:
print(file.read())
When to Use File Handling
- Saving user data
- Storing logs
- Reading configuration files
- Working with large datasets
Important Concepts
- Always close files after use
- Use correct mode (r, w, a)
- File path must be correct
Tips
- Use with for safe file handling
- Check file existence before reading
- Use newline (\n) for formatting
Common Mistakes
- Forgetting to close file ❌
- Wrong file mode ❌
- File not found error ❌
🎯 Practice Task
- Create and write data to a file
- Read file content
- Append new data
- Use with statement
Exception Handling in Python
Exception Handling is used to handle errors in a program. It prevents the program from crashing and allows smooth execution.
Errors that occur during program execution are called exceptions.
Common Errors
| Error | Description |
|---|---|
| ZeroDivisionError | Dividing by zero |
| ValueError | Invalid input type |
| IndexError | Invalid list index |
| FileNotFoundError | File not found |
Basic Try-Except
try:
x = int(input("Enter number: "))
print(10 / x)
except:
print("Error occurred")
Handling Specific Exceptions
try:
x = int(input("Enter number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
Using Else Block
try:
x = 5
print(x)
except:
print("Error")
else:
print("No error occurred")
Using Finally Block
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")
Raising Exceptions
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Example Program
try:
num1 = int(input("Enter number: "))
num2 = int(input("Enter number: "))
print(num1 / num2)
except Exception as e:
print("Error:", e)
When to Use Exception Handling
- Handling user input errors
- Working with files
- Preventing program crashes
- Building robust applications
Important Concepts
- try → risky code
- except → handle error
- else → runs if no error
- finally → always runs
Tips
- Handle specific exceptions
- Avoid using bare except
- Use finally for cleanup tasks
Common Mistakes
- Using only except without type ❌
- Ignoring errors silently ❌
- Wrong indentation ❌
🎯 Practice Task
- Handle division by zero
- Handle invalid input
- Use finally block
- Raise custom exception
🚧 Coming Soon!
This course content is currently under development.
Stay tuned — exciting lessons are on the way!