Loading...
Loading...
Python is the #1 language for beginners and data scientists worldwide.
✅ Simple, English-like syntax
✅ Huge library ecosystem (pip install anything)
✅ Used in Web, ML, Data Science, Automation, Scripting
✅ Top choice for B.Tech placements (after DSA)
✅ Jupyter Notebooks for data science
Installation:
python --version in terminal# Python mein type declare karna zaruri nahi
name = "Rahul" # str
age = 21 # int
cgpa = 8.5 # float
is_placed = True # bool
nothing = None # None type
# Type check
print(type(name)) # <class 'str'>
# Multiple assignment
x = y = z = 0
a, b, c = 1, 2, 3 # Tuple unpacking
name = input("Enter your name: ") # Always returns string
age = int(input("Enter age: ")) # Convert to int
# f-strings (Python 3.6+) — best way to format
print(f"Hello {name}, you are {age} years old!")
# Older style
print("Hello %s, age %d" % (name, age))
print("CGPA: {:.2f}".format(8.567)) # 8.57
# Arithmetic
10 + 3 = 13 | 10 - 3 = 7 | 10 * 3 = 30
10 / 3 = 3.33 | 10 // 3 = 3 | 10 % 3 = 1 | 2**10 = 1024
# Comparison → returns bool
x == y | x != y | x > y | x >= y
# Logical
True and False → False
True or False → True
not True → False
# Python-specific
5 in [1,2,3,5] → True
x is None → True (identity check)
marks = 75
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
# One-liner (ternary)
status = "Pass" if marks >= 40 else "Fail"
# for loop
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 11, 2): # 1,3,5,7,9 (step=2)
print(i)
# Iterate over list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
# enumerate — index + value
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# while loop
n = 1
while n <= 5:
print(n)
n += 1
# Loop control
break # Exit loop
continue # Skip to next iteration
pass # Do nothing (placeholder)
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested
matrix = [[i*j for j in range(4)] for i in range(4)]
# Basic function
def greet(name, greeting="Hello"): # Default argument
return f"{greeting}, {name}!"
print(greet("Priya")) # Hello, Priya!
print(greet("Amit", "Namaste")) # Namaste, Amit!
# Multiple return values
def min_max(nums):
return min(nums), max(nums)
low, high = min_max([3, 1, 7, 2])
# *args — variable positional arguments
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3, 4, 5) # 15
# **kwargs — variable keyword arguments
def show_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_info(name="Rahul", college="IIT", cgpa=9.1)
# Lambda (anonymous function)
square = lambda x: x**2
double = lambda x, y: x + y
sorted_data = sorted(students, key=lambda s: s['cgpa'], reverse=True)
# Recursion
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
factorial(5) # 120
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.append(7) # Add at end
nums.insert(0, 100) # Insert at index 0
nums.remove(1) # Remove first occurrence of 1
popped = nums.pop() # Remove + return last
nums.sort() # Sort in-place
nums.sort(reverse=True) # Descending
sorted_copy = sorted(nums) # Returns new list
nums[0] # First element
nums[-1] # Last element
nums[1:4] # Slice [1,4)
nums[::-1] # Reverse
len(nums), sum(nums), min(nums), max(nums)
student = {
"name": "Priya",
"rollno": 42,
"cgpa": 8.9,
"subjects": ["DSA", "OS", "DBMS"]
}
# Access
student["name"] # Priya
student.get("grade", "N/A") # Default if not found
# Modify
student["cgpa"] = 9.1
student["college"] = "VIT"
# Iteration
for key in student: # Keys only
print(key)
for key, value in student.items(): # Key + value
print(f"{key}: {value}")
# Dict comprehension
squares = {x: x**2 for x in range(6)} # {0:0, 1:1, 2:4, ...}
# Set — unordered, unique elements
skills = {"Python", "SQL", "Git"}
skills.add("JavaScript")
skills.remove("Git")
set1 & set2 # Intersection
set1 | set2 # Union
set1 - set2 # Difference
# Tuple — immutable list
coords = (28.6, 77.2) # lat, long — can't change
x, y = coords # Unpack
s = "Hello, World!"
s.upper() # HELLO, WORLD!
s.lower() # hello, world!
s.strip() # Remove whitespace
s.split(",") # ['Hello', ' World!']
s.replace("Hello", "Namaste")
s.startswith("Hello") # True
s.find("World") # 7 (index)
",".join(["a","b","c"]) # "a,b,c"
s[0:5] # Hello
len(s) # 13
# Write file
with open("notes.txt", "w") as f:
f.write("First line\n")
f.writelines(["Line 2\n", "Line 3\n"])
# Read file
with open("notes.txt", "r") as f:
content = f.read() # Entire file
lines = f.readlines() # List of lines
# Append mode
with open("notes.txt", "a") as f:
f.write("New line\n")
# CSV with pandas
import pandas as pd
df = pd.read_csv("students.csv")
df.head(10)
df.to_csv("output.csv", index=False)
Exception Handling:
try:
result = int(input("Enter number: "))
print(10 / result)
except ValueError:
print("Invalid number!")
except ZeroDivisionError:
print("Can't divide by zero!")
except Exception as e:
print(f"Error: {e}")
else:
print("No error occurred")
finally:
print("Always runs")
# Raise custom exception
def validate_age(age):
if age < 0:
raise ValueError(f"Age can't be negative: {age}")
class Student:
university = "VIT" # Class variable (shared)
def __init__(self, name, rollno, cgpa):
# Instance variables
self.name = name
self.rollno = rollno
self.__cgpa = cgpa # Private (name mangling)
def get_cgpa(self): # Getter
return self.__cgpa
def set_cgpa(self, cgpa): # Setter
if 0 <= cgpa <= 10:
self.__cgpa = cgpa
def introduce(self):
return f"I'm {self.name}, Roll: {self.rollno}"
def __str__(self): # Called by print()
return f"Student({self.name}, {self.rollno})"
def __repr__(self): # Developer representation
return f"Student(name={self.name!r})"
# Inheritance
class TopStudent(Student):
def __init__(self, name, rollno, cgpa, scholarship):
super().__init__(name, rollno, cgpa) # Call parent
self.scholarship = scholarship
def introduce(self): # Override method
base = super().introduce()
return f"{base} — Scholarship: ₹{self.scholarship}"
# Usage
s1 = Student("Rahul", 42, 8.9)
s2 = TopStudent("Priya", 1, 9.8, 50000)
print(s1.introduce())
print(s2.introduce())
print(Student.university) # Class variable
students = {}
def add_student(name, marks):
grade = "A" if marks>=90 else "B" if marks>=75 else "C" if marks>=60 else "F"
students[name] = {"marks": marks, "grade": grade}
def show_all():
for name, data in students.items():
print(f"{name}: {data['marks']} → Grade {data['grade']}")
def top_student():
return max(students, key=lambda n: students[n]['marks'])
add_student("Rahul", 88)
add_student("Priya", 95)
add_student("Amit", 72)
show_all()
print(f"Top student: {top_student()}")
import json
FILENAME = "todos.json"
def load():
try:
with open(FILENAME) as f:
return json.load(f)
except FileNotFoundError:
return []
def save(todos):
with open(FILENAME, "w") as f:
json.dump(todos, f, indent=2)
todos = load()
def add(task): todos.append({"task": task, "done": False}); save(todos)
def done(i): todos[i]["done"] = True; save(todos)
def show():
for i, t in enumerate(todos):
status = "✅" if t["done"] else "⬜"
print(f"{i}. {status} {t['task']}")
import random
def play():
target = random.randint(1, 100)
attempts = 0
print("Guess a number between 1 and 100!")
while True:
try:
guess = int(input("Your guess: "))
attempts += 1
if guess < target:
print("Too low! ⬇️")
elif guess > target:
print("Too high! ⬆️")
else:
print(f"🎉 Correct! You got it in {attempts} attempts!")
break
except ValueError:
print("Please enter a valid number")
play()
| Track | Topics | Libraries | |---|---|---| | Data Science | Numpy, Pandas, Matplotlib, EDA | pandas, matplotlib, seaborn | | Machine Learning | Regression, Classification, Clustering | scikit-learn, XGBoost | | Deep Learning | Neural Networks, CNNs, RNNs | TensorFlow, PyTorch | | Web Development | REST APIs, Databases | Flask, Django, FastAPI | | Automation | Web scraping, file automation | selenium, requests, BeautifulSoup | | DSA with Python | Solve LeetCode problems | heapq, collections, bisect |
Recommended Daily Practice: 2 hours theory + 30 min solving problems on LeetCode Easy
Sirf ek computer aur VS Code ya PyCharm IDE. Python.org se free download karo. Koi prior programming experience zaruri nahi.
Syntax, variables, loops, functions, lists, dictionaries, file I/O, basic OOP, aur 3 mini projects. Industry-ready beginner level.
Web (Django/Flask), Data Science (pandas/numpy), ML (sklearn/TensorFlow), Automation (selenium), DevOps (scripts), and Backend APIs.
Python is cleaner, less boilerplate, faster to prototype. Java is more structured. For data science/ML — Python is #1. For Android — Java/Kotlin.
JavaScript Complete Guide — Beginner to Advanced (2026)
40 min · Beginner
ToolsGit & GitHub Complete Guide — Version Control for Students (2026)
20 min · Beginner
DatabaseSQL Complete Guide — Database Queries for B.Tech & Placements (2026)
30 min · Intermediate
ReactReact Hooks Explained: useState, useEffect, useContext & More
14 min · Intermediate
DSAData Structures and Algorithms: Full Fundamentals + Interview Prep
35 min · Intermediate
JavaTop 50 Java Interview Questions — B.Tech Placements 2026
18 min · Advanced
Your feedback helps us improve notes and tutorials.