0% found this document useful (0 votes)
4 views20 pages

Python From Zero Notes

The document provides comprehensive beginner-to-advanced notes on Python programming, covering its introduction, installation, data types, control flow, functions, and modules. It emphasizes a structured learning approach, starting from basic concepts and building up to more complex topics, with practical coding examples. The notes are designed for complete beginners, assuming no prior knowledge of programming.

Uploaded by

prachijee02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Python From Zero Notes

The document provides comprehensive beginner-to-advanced notes on Python programming, covering its introduction, installation, data types, control flow, functions, and modules. It emphasizes a structured learning approach, starting from basic concepts and building up to more complex topics, with practical coding examples. The notes are designed for complete beginners, assuming no prior knowledge of programming.

Uploaded by

prachijee02
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🐍 PYTHON FROM ZERO

Complete Beginner-to-Topper Notes


Easy English • Full of Code • Diagrams jahan connection dikhta hai

📝 NOTE: Kaise use karein: Ye notes ekdum shuru se hain — zero knowledge assume kiya hai. Har Part ek
building block hai, upar wale Part se juda hua. Code khud type karke chalao, sirf padhna kaafi nahi.

📍 Poore safar ka naksha (Roadmap)


Data Contro Functi Modul Project
Basics → Types → l Flow → ons → es → OOP → s

Ye flow dikhata hai ki Python seekhne ka sahi order kya hai — pehle neeche wali cheez pakki karo, tabhi agla step
easy lagega. Sab kuch connected hai, isliye order mat todo.
PART 1 — Python Hai Kya? (Introduction)

1.1 Python kya hai


Python ek programming language hai — matlab computer ko instructions dene ka ek tarika, jisse English jaisa easy
syntax hai. Ise 1991 mein Guido van Rossum ne banaya tha. Aaj ye duniya ki sabse popular languages mein se ek hai.

1.2 Python itna popular kyun hai


• Easy to read — English jaisa lagta hai, isliye beginner ke liye best pehli language hai
• Free aur Open Source — koi bhi use kar sakta hai, koi cost nahi
• Sab jagah use hota hai — Web development, Data Science, AI/ML, Automation, Scripting, Game dev
• Bahut saari libraries already ban chuki hain — reinvent the wheel nahi karna padta
• Bade companies use karte hain — Google, Instagram, Netflix, NASA

1.3 Python interpreted language hai — iska matlab


Do tarah ki languages hoti hain:

Compiled Language (jaise C++) Interpreted Language (Python)

Pura code ek baar mein machine code mein convert hota hai Code line-by-line, ek ek karke run hota hai

Run karne se pehle compile karna padta hai Direct run kar sakte ho, koi extra step nahi

Speed thodi zyada hoti hai Likhna aur test karna bahut fast hota hai

💡 TIP: Isi wajah se Python mein galti turant pakdi jaati hai — jis line mein error hai, wahi rukega, poora program
nahi todega compile-time pe.
PART 2 — Setup aur Code Chalana

2.1 Python install karna


• [Link] se latest version download karo (Windows/Mac/Linux sab ke liye available)
• Install karte time 'Add Python to PATH' checkbox zaroor tick karo (Windows users)
• Terminal/Command Prompt mein 'python --version' likh ke check karo ki install hua ya nahi

2.2 Code likhne ke 2 tarike


Tarika 1: Interactive Mode (REPL)
Terminal mein sirf 'python' likho — ek prompt (>>>) khul jayega jahan ek-ek line turant test kar sakte ho.

>>> print("Hello Prachu")


Hello Prachu
>>> 5 + 3
8

Tarika 2: Script Mode (.py file)


Ek file banao jaise [Link], usme code likho, phir terminal se run karo:

python [Link]

📝 NOTE: Real projects hamesha script mode (.py files) mein likhe jaate hain. Interactive mode sirf quick testing
ke liye hai.

2.3 Kaunsa editor use karein


• VS Code — sabse popular, free, extensions ke saath (Python extension zaroor lagao)
• PyCharm — professional Python IDE, thoda heavy hai par powerful
• Jupyter Notebook — data science / experiments ke liye best
PART 3 — Variables aur Data Types

3.1 Variable kya hota hai


Variable ek 'labelled box' jaisa hai jisme hum value store karte hain. Python mein variable banane ke liye koi keyword
(like 'int' or 'let') ki zaroorat nahi — bas naam do aur value assign karo.

name = "Prachu" # ye ek string hai


age = 20 # ye ek integer hai
height = 5.6 # ye ek float hai
is_student = True # ye ek boolean hai

💡 TIP: Python 'dynamically typed' hai — matlab tumhe type batana nahi padta, Python khud samajh leta hai
value dekh ke.

3.2 Variable naming rules


• Sirf letters, numbers, underscore (_) use kar sakte ho
• Number se shuru nahi kar sakte (2name galat hai, name2 sahi hai)
• Case-sensitive hota hai — Age aur age do alag variables hain
• Meaningful naam do — 'x' ke bajaye 'total_marks' likho, padhne mein easy hoga

3.3 Python ke basic Data Types


Type Kya store karta hai Example

int Poore number (whole numbers) 10, -5, 2024

float Decimal wale number 3.14, -0.5, 5.0

str Text / string "hello", 'Prachu'

bool True ya False True, False

list Multiple values, order matters, changeable [1, 2, 3]

tuple Multiple values, order matters, NOT changeable (1, 2, 3)

dict Key-value pairs {"name": "Prachu"}

set Unique values, no duplicates, no order {1, 2, 3}

3.4 Type check karna aur convert karna


x = 10
print(type(x)) # <class 'int'>

# Type conversion (casting)


a = "25"
b = int(a) # string ko int mein badla
c = str(100) # int ko string mein badla
d = float("3.5") # string ko float mein badla

⚠ WATCH OUT: int("25.5") likhoge to error aayega — pehle float() karo, phir int() karo agar decimal remove
karna hai.

3.5 print() aur input()


print() screen pe kuch dikhane ke liye hai. input() user se kuch poochne ke liye hai — ye hamesha string return karta
hai.

name = input("Apka naam kya hai? ")


print("Hello,", name)
print(f"Hello, {name}!") # f-string, sabse modern tarika"

3.6 Comments
Comments code ke andar notes hote hain jo Python ignore karta hai — sirf humare samajhne ke liye hote hain.

# ye ek single-line comment hai


"""
ye ek multi-line comment/docstring hai,
jab lambi explanation likhni ho
"""
PART 4 — Operators

4.1 Arithmetic Operators (Maths ke liye)


Operator Matlab Example Result

+ Addition 5+2 7

- Subtraction 5-2 3

* Multiplication 5*2 10

/ Division (decimal deta hai) 5/2 2.5

// Floor Division (sirf poora number) 5 // 2 2

% Modulus (remainder deta hai) 5%2 1

** Power / Exponent 5 ** 2 25

4.2 Comparison Operators (True/False deta hai)


Operator Matlab

== Barabar hai kya

!= Barabar nahi hai kya

> Bada hai kya

< Chota hai kya

>= Bada ya barabar

<= Chota ya barabar

4.3 Logical Operators


age = 20
has_id = True

print(age >= 18 and has_id) # True — dono sahi hone chahiye


print(age >= 18 or has_id) # True — koi ek bhi sahi ho
print(not has_id) # False — ulta kar deta hai

4.4 Assignment shortcuts


score = 10
score += 5 # score = score + 5 → 15
score -= 2 # score = score - 2 → 13
score *= 2 # score = score * 2 → 26
PART 5 — Strings (Text)

5.1 String banana


s1 = 'single quotes bhi chalti hain'
s2 = "double quotes bhi chalti hain"
s3 = """multi-line
string yahan"""

5.2 Indexing aur Slicing


String ke har character ka ek position (index) hota hai, 0 se shuru hota hai.

P(0) → y(1) → t(2) → h(3) → o(4) → n(5)

word = "python"
print(word[0]) # p (pehla character)
print(word[-1]) # n (last character)
print(word[0:3]) # pyt (0 se 2 tak, 3 exclude)
print(word[::-1]) # nohtyp (poora ulta / reverse)

5.3 Useful String Methods


Method Kaam

.upper() SAB CAPITAL letters mein

.lower() sab small letters mein

.strip() shuru/end ke extra spaces hatata hai

.split() string ko list mein todta hai

.replace(a,b) a ko b se replace karta hai

.join() list ko wapas string bana deta hai

len(s) string ki length deta hai

text = " I Love Python "


print([Link]().lower()) # 'i love python'
print([Link]()) # ['I', 'Love', 'Python']
PART 6 — List, Tuple, Set, Dictionary
Ye chaaro 'collections' hain — matlab ek hi variable mein multiple values rakhne ka tarika. Sabki apni khaasiyat hai:

List Tuple Set Dictionary

Symbol [] () {} {key: value}

Order Haan, order fix rehta hai Haan, order fix rehta hai Nahi, order guarantee Insertion order (3.7+)
nahi

Changeable? Haan (mutable) Nahi (immutable) Haan, par items unique Haan (mutable)

Duplicates? Allowed Allowed Allowed NAHI Keys unique honi


chahiye

6.1 List
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
[Link]("grape") # end mein add karo
[Link]("banana") # value se remove karo
print(len(fruits)) # kitne items hain
fruits[0] = "kiwi" # list changeable hai, isliye ye chalega

6.2 Tuple
point = (10, 20)
print(point[0]) # 10
# point[0] = 5 # ERROR! tuple change nahi ho sakta

💡 TIP: Tuple use karo jab data fix rehna chahiye, jaise coordinates ya kisi cheez ki fixed settings — safe rehta
hai galti se change hone se.

6.3 Set
nums = {1, 2, 2, 3, 3, 3}
print(nums) # {1, 2, 3} — duplicates apne aap hat gaye
[Link](4)

6.4 Dictionary — sabse zyada use hone wala


Dictionary mein data key-value pairs mein store hota hai — real life mein jaise ek phonebook: naam (key) → number
(value).

student = {
"name": "Prachu",
"age": 20,
"course": "CS"
}
print(student["name"]) # Prachu
student["age"] = 21 # value update karna
student["city"] = "Nagpur" # naya key add karna

for key, value in [Link]():


print(key, "->", value)
PART 7 — Control Flow (Decisions aur Loops)

7.1 if / elif / else


Ye code ko decide karne deta hai ki kaunsa part chalana hai, condition ke hisaab se.

Condition Check → True → if block → False → else block

marks = 75

if marks >= 90:


print("A Grade")
elif marks >= 60:
print("B Grade")
else:
print("Needs Improvement")

⚠ WATCH OUT: Python mein indentation (spacing) matter karti hai! Curly braces {} nahi hote, spacing hi
block define karti hai. Hamesha 4 spaces use karo.

7.2 for loop — jab pata ho kitni baar repeat karna hai
for i in range(5): # 0,1,2,3,4
print(i)

fruits = ["apple", "mango", "grape"]


for fruit in fruits:
print(fruit)

7.3 while loop — jab tak condition True hai


count = 0
while count < 5:
print(count)
count += 1 # ye zaroor likho, warna infinite loop ban jayega!

7.4 break, continue, pass


Keyword Kaam

break Loop ko turant rok deta hai

continue Current iteration skip karke agli pe chala jata hai

pass Kuch nahi karta, sirf placeholder hai (jab code baad mein likhna ho)

for i in range(10):
if i == 5:
break # 5 pe loop poora ruk jayega
if i % 2 == 0:
Keyword Kaam

continue # even numbers skip honge


print(i)
PART 8 — Functions

8.1 Function kya hai aur kyun zaroori hai


Function code ka ek reusable chunk hai — ek kaam ka naam de dete ho, aur jab bhi zaroorat ho bas naam se bula lete
ho. Isse code repeat nahi karna padta (DRY — Don't Repeat Yourself).

def greet(name):
print(f"Hello, {name}!")

greet("Prachu") # function ko call karna


greet("Rahul")

8.2 Return value


print() sirf dikhata hai, kuch deta nahi. return function se value wapas bhejta hai jise aage use kar sako.

def add(a, b):


return a + b

result = add(5, 3)
print(result) # 8

8.3 Default aur Keyword arguments


def greet(name, greeting="Hello"): # default value
print(f"{greeting}, {name}!")

greet("Prachu") # Hello, Prachu!


greet("Prachu", greeting="Hi") # Hi, Prachu!

8.4 *args aur **kwargs (jab pata na ho kitne arguments aayenge)


def total(*numbers): # *args → sab numbers ek tuple mein aa jate hain
return sum(numbers)

print(total(1, 2, 3, 4)) # 10

def show_info(**details): # **kwargs → sab key-value dict mein aa jate hain


for k, v in [Link]():
print(k, v)

show_info(name="Prachu", age=20)

8.5 Scope — variable kahan tak 'dikhta' hai


x = 10 # global variable — pure program mein accessible

def my_func():
y = 5 # local variable — sirf isi function ke andar
print(x) # global ko read kar sakte hain

my_func()
# print(y) # ERROR! y sirf function ke andar exist karta hai

8.6 Lambda function — chota, one-line function


square = lambda x: x * x
print(square(5)) # 25

💡 TIP: Lambda tab use karo jab function bahut chota ho, jaise sort() ya map() ke andar quickly use karna ho.
PART 9 — Modules aur Packages

9.1 Module kya hai


Module ek .py file hoti hai jisme functions/classes already likhe hote hain. Import karke hum unka use kar sakte hain,
bina khud likhe.

import math
print([Link](16)) # 4.0
print([Link]) # 3.14159...

from datetime import datetime


print([Link]())

import random
print([Link](1, 10)) # 1 se 10 ke beech random number

9.2 pip — Python ka package manager


Duniya bhar ke developers ne libraries banayi hain jo hum download karke use kar sakte hain — pip se install karte
hain.

pip install requests


pip install pandas
pip list # dekhne ke liye kya kya install hai

9.3 Kuch famous libraries jo aage kaam aayengi


Library Kis liye use hoti hai

requests Internet se data fetch karna (APIs)

pandas Data analysis aur Excel jaise data ko handle karna

numpy Fast maths aur number arrays

flask / django Website / web app banana

matplotlib Graphs aur charts banana

instaloader / instagrapi Instagram related automation (content creators ke kaam ki)


PART 10 — File Handling

10.1 File open, read, write karna


with statement best tarika hai file open karne ka — ye file ko automatically close bhi kar deta hai.

# likhna (write)
with open("[Link]", "w") as f:
[Link]("Hello Prachu!")

# padhna (read)
with open("[Link]", "r") as f:
content = [Link]()
print(content)

# end mein add karna (append)


with open("[Link]", "a") as f:
[Link]("\nNaya line")

Mode Kaam

"r" sirf read (default)

"w" write — purana content delete karke naya likhta hai

"a" append — end mein add karta hai


PART 11 — Exception Handling (Errors ko Handle karna)

11.1 try / except — program ko crash hone se bachana


Agar galat input aaya ya kuch unexpected hua, try/except se program crash nahi hota, gracefully handle ho jata hai.

try:
num = int(input("Number daalo: "))
print(10 / num)
except ValueError:
print("Ye number nahi hai!")
except ZeroDivisionError:
print("Zero se divide nahi kar sakte!")
finally:
print("Ye hamesha chalega, error aaye ya na aaye")

try block → Error aaya? → except block → finally

📝 NOTE: finally block hamesha chalta hai — chahe error aaye ya na aaye. Isliye 'cleanup' code (jaise file close
karna) yahan likhte hain.
PART 12 — Object Oriented Programming (OOP)

12.1 Class aur Object kya hote hain


Class ek blueprint/design hai (jaise 'ghar ka naksha'), aur Object us blueprint se bana ek actual cheez hai (jaise 'ghar').

Class
(Blueprint) → Object 1 → Object 2 → Object 3

class Student:
def __init__(self, name, marks): # constructor — object ban ते hi ye chalta
hai
[Link] = name # self = current object khud
[Link] = marks

def show(self):
print(f"{[Link]} scored {[Link]} marks")

s1 = Student("Prachu", 90) # naya object bana


s2 = Student("Rahul", 75)
[Link]() # Prachu scored 90 marks
[Link]() # Rahul scored 75 marks

12.2 Inheritance — ek class dusri class ke features use kar sakti hai
class Animal:
def eat(self):
print("Kha raha hai")

class Dog(Animal): # Dog, Animal ko inherit kar raha hai


def bark(self):
print("Bhow Bhow!")

d = Dog()
[Link]() # Animal se mila (inherited)
[Link]() # Dog ka apna

Animal (Parent) → Dog (Child)

💡 TIP: Inheritance code repeat hone se bachata hai — common features parent class mein rakho, specific
features child class mein.

12.3 OOP ke 4 pillars — sirf naam yaad rakho abhi


Pillar Simple matlab

Encapsulation Data aur functions ko ek class mein wrap karna

Inheritance Ek class dusri se features le sakti hai


Pillar Simple matlab

Polymorphism Same method naam, alag classes mein alag kaam

Abstraction Complex cheezein chhupa ke sirf zaroori dikhana


PART 13 — Bonus: Thoda Advanced Peek

13.1 List Comprehension — list banane ka short tarika


# normal tarika
squares = []
for i in range(5):
[Link](i * i)

# list comprehension — same kaam, ek line mein


squares = [i * i for i in range(5)]
print(squares) # [0, 1, 4, 9, 16]

13.2 f-strings — string ke andar variable daalna


name = "Prachu"
followers = 5000
print(f"{name} has {followers} followers!")

13.3 Virtual Environment (venv) — projects ko alag-alag rakhna


Alag alag project ke liye alag libraries chahiye ho sakti hain — venv har project ka apna alag 'box' bana deta hai.

python -m venv myenv # naya environment banao


myenv\Scripts\activate # Windows pe activate karo
source myenv/bin/activate # Mac/Linux pe activate karo

13.4 Generators (thoda advanced, sirf awareness ke liye)


def count_up_to(n):
i = 1
while i <= n:
yield i # return jaisa, par memory bachata hai
i += 1

for num in count_up_to(5):


print(num)
PART 14 — Ab Aage Kya? (Practice Roadmap)

14.1 Order jisme practice karo


1. Basics pakke karo — variables, loops, conditions par 20-30 chote chote programs likho
2. Functions aur Data structures (list/dict) pe comfortable ho jao
3. OOP samjho — ek chota project banao (jaise Student Management using classes)
4. File handling + Exception handling milaake ek mini project banao
5. Ek library seekho — requests ya pandas se shuru karo
6. Ek real project complete karo end-to-end

14.2 Beginner Project Ideas


• Number Guessing Game (random module use karo)
• To-Do List app (file mein save hone wala)
• Simple Calculator (functions use karo)
• Password Strength Checker (strings + conditions)
• Expense Tracker (dictionary/list + file handling)
• Instagram caption/hashtag generator (content creator ke liye kaam ka!)

14.3 Golden Rules


• Roz thoda thoda code likho — sirf padhne se nahi aayega, likhna zaroori hai
• Error aaye to ghabrao mat — error message padho, Google karo, samjho
• Chote projects banao — bade project se dar lagta hai, chote se confidence banta hai
• Kisi ko explain karke dekho jo tumne seekha — teaching se sabse zyada clear hota hai

💡 TIP: Ye poore notes ek reference hain, bible nahi — jab bhi kuch bhool jao, wapas yahan aake dekh sakte ho.
Happy Coding! 🐍

You might also like