Python Fundamentals
Har ek topic ki simple definition aur clear examples ke saath — Python seekhna ab bahut aasan hai!
Watch the Video Lesson
Python Fundamentals — Knobly YouTube
Introduction to Python
Simple explanation: Python ek aisi programming language hai jisme aap English jaisi simple bhasha mein code likh sakte ho. Ye beginners ke liye sabse best language hai kyunki iska code padhna aur likhna bahut aasan hai.
Python kyun banaya gaya?
Guido van Rossum 1980s mein ABC language par kaam kar rahe the. Unhone socha ki ek aisi language honi chahiye jo simple ho, powerful ho, aur sabke liye accessible ho. Issi idea se Python bani!
Naam "Python" British comedy show Monty Python's Flying Circus se liya gaya hai — saanp (snake) se nahi! 😄
Python kya kya kar sakti hai?
- Web Development — Websites banao (Django, Flask)
- Data Science — Data analyze karo (Pandas, NumPy)
- AI / Machine Learning — Smart apps banao (TensorFlow, PyTorch)
- Automation — Boring tasks automate karo
- Game Development — Games banao (Pygame)
Python vs Other Languages
# Python mein Hello World — sirf 1 line!
print("Hello, World!")
# C++ mein same kaam — 5 lines!
# #include <iostream>
# using namespace std;
# int main() {
# cout << "Hello, World!";
# return 0;
# }Python Versions
| Version | Year | Kya Naya Aaya? |
|---|---|---|
| Python 1.0 | 1994 | Sabse pehla major release |
| Python 2.0 | 2000 | List comprehensions aaye |
| Python 2.7 | 2010 | Python 2 ka aakhri version |
| Python 3.0 | 2008 | Bahut bade changes — naya Python! |
| Python 3.11 | 2022 | Bahut fast + better error messages |
| Python 3.12 | 2023 | Latest version ✨ — Use this! |
Advantages of Python
📚 Easy to Learn
Python ka code English jaisa hota hai. Beginners sirf kuch hi dino mein Python seekh sakte hain.
🚀 Versatile
Web apps, AI, data analysis, games — Python se sab kuch bana sakte ho!
📦 Huge Library
Thousands of ready-made libraries available hain — aapko sab kuch scratch se nahi banana padta.
⚡ Interpreted
Code ek ek line execute hota hai. Error aaye to turant pata chal jaata hai!
🔓 Free & Open Source
Python free hai! Koi bhi download karke use kar sakta hai — commercial use bhi!
🤝 Big Community
Lakho developers worldwide. Koi bhi problem ho — Stack Overflow par answer mil jaata hai!
Working with Python
Step 1: Python Install Karo
- Download karo: python.org/downloads par jaake latest version download karo
- Install karo: Installer open karo. ⚠️ "Add Python to PATH" checkbox zaroor tick karo!
- Check karo: Command Prompt open karo aur type karo:
python --version\n# Output: Python 3.12.xStep 2: Interactive Mode (Direct Typing)
Command Prompt mein python type karo aur directly code likho. Ye testing ke liye best hai!
>>> print("Hello, World!")
Hello, World!
>>> 2 + 3
5
>>> name = "Python"
>>> print(f"I love {name}!")
I love Python!
>>> exit() # Interactive mode se bahar aane ke liyeStep 3: Program Mode (File mein Code)
Bade programs ke liye code ek .py file mein likho:
# hello.py file banao aur ye likho:
print("Namaste! Mera naam Python hai!")
print("Mein ek programming language hoon.")
for i in range(1, 6):
print(f"Counting: {i}")Phir terminal mein run karo: python hello.py
Modules and Program Files
import karke use bhi kar sakte ho.Python File kaise banaye?
- Koi bhi text editor kholo (VSCode, Notepad++, PyCharm)
- Naya file banao aur Python code likho
- File ko
.pyextension ke saath save karo (jaise:calculator.py)
# calculator.py - ek simple calculator
num1 = 10
num2 = 5
print(f"Jod (Sum): {num1 + num2}") # 15
print(f"Ghata (Diff): {num1 - num2}") # 5
print(f"Guna (Multiply): {num1 * num2}") # 50
print(f"Bhaag (Divide): {num1 / num2}") # 2.0Run karo: python calculator.py
Python Tokens
1. Identifiers (Naam)
Simple definition: Identifier ek naam hai jo aap apne variables, functions, ya classes ko dete ho. Jaise aapka naam aapki pehchaan hai, waise hi identifier code ki pehchaan hai.
Rules (Niyam):
- Letter (A-Z, a-z) ya underscore (_) se shuru hona chahiye
- Numbers bhi ho sakte hain lekin pehla character number nahi ho sakta
- Case-sensitive hai —
name,Name,NAMEteen alag cheezein hain! - Special characters (@, #, $, !) allowed nahi hain
# ✅ Sahi (Valid) Identifiers:
name = "Rahul"
student_1 = "Priya"
_private = "Secret"
totalMarks = 450
# ❌ Galat (Invalid) Identifiers:
# 123name = "Error" → Number se shuru nahi ho sakta
# my-var = 10 → Hyphen (-) allowed nahi
# for = 5 → Reserved keyword hai
# $price = 100 → Special symbol nahi chalega2. Keywords (Reserved Words)
Simple definition: Keywords woh special words hain jo Python ne pehle se book kar rakhe hain. Inhe aap apne variable naam ke roop mein use nahi kar sakte.
| Python ke 35 Keywords | ||||
|---|---|---|---|---|
| False | None | True | and | as |
| assert | async | await | break | class |
| continue | def | del | elif | else |
| except | finally | for | from | global |
| if | import | in | is | lambda |
| nonlocal | not | or | pass | raise |
| return | try | while | with | yield |
# Keywords check karne ka tarika:
import keyword
print(keyword.kwlist)
print(f"Total keywords: {len(keyword.kwlist)}")Literals
10, "Hello", True — ye sab literals hain.String Literals (Text)
Text ko single quotes, double quotes, ya triple quotes mein likha jaata hai.
# Single quotes
name = 'Rahul'
# Double quotes
city = "Delhi"
# Triple quotes - jab text multiple lines mein ho
poem = """Twinkle twinkle little star,
How I wonder what you are.
Up above the world so high,
Like a diamond in the sky."""
print(poem)Numeric Literals (Numbers)
# Integer (poore numbers)
age = 18
marks = 95
# Float (decimal wale numbers)
height = 5.8
pi = 3.14159
# Binary (0b se shuru)
binary = 0b1010 # ye hai 10
# Hexadecimal (0x se shuru)
hex_num = 0xFF # ye hai 255
print(f"Age: {age}, Height: {height}")
print(f"Binary 0b1010 = {binary}") # Output: 10Boolean & None
Boolean: Sirf do values — True (haan) ya False (nahi)
None: Koi value nahi hai — khaali (empty)
# Boolean - True ya False
is_student = True
has_passed = False
print(is_student) # True
# None - koi value nahi
result = None
print(result) # None
print(type(result)) # <class 'NoneType'>Variables & Data Types
Real life example: Jaise ek dabba hai jisme aap apna naam likh sakte ho, ya number daal sakte ho — Python variable bhi exactly aisa hai!
# Variable banane ka tarika: naam = value
name = "Rahul" # String (text)
age = 18 # Integer (poora number)
height = 5.8 # Float (decimal number)
is_student = True # Boolean (haan/nahi)
fav_fruits = ["Apple", "Mango"] # List
# Type check karo - Python khud batata hai!
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
# Variable ki value change bhi kar sakte ho!
age = 19 # ab age 19 hai
print(f"{name} ki age {age} hai aur height {height} hai")x = 10 ke baad x = "hello" likh sakte ho — koi error nahi aayega!Operators
Arithmetic Operators (Math wale)
| Symbol | Kaam | Example | Answer |
|---|---|---|---|
| + | Jod (Add) | 10 + 3 | 13 |
| - | Ghatao (Subtract) | 10 - 3 | 7 |
| * | Guna (Multiply) | 10 * 3 | 30 |
| / | Bhaag (Divide) | 10 / 3 | 3.33 |
| // | Floor Division | 10 // 3 | 3 |
| % | Remainder | 10 % 3 | 1 |
| ** | Power | 2 ** 3 | 8 |
a = 10
b = 3
print(f"Jod: {a + b}") # 13
print(f"Ghatao: {a - b}") # 7
print(f"Guna: {a * b}") # 30
print(f"Bhaag: {a / b}") # 3.333...
print(f"Floor: {a // b}") # 3 (decimal hata do)
print(f"Remainder: {a % b}") # 1
print(f"Power: {a ** b}") # 1000Comparison Operators (Compare karo)
Do values ko compare karte hain aur result True ya False aata hai:
x = 5
y = 10
print(x == y) # False (5 barabar 10? Nahi!)
print(x != y) # True (5 alag hai 10 se? Haan!)
print(x > y) # False (5 bada hai 10 se? Nahi!)
print(x < y) # True (5 chhota hai 10 se? Haan!)
print(x >= 5) # True (5 barabar ya bada 5 se? Haan!)
print(x <= 3) # False (5 barabar ya chhota 3 se? Nahi!)Identity Operators (is / is not)
Simple: == value check karta hai, is check karta hai ki dono same object hain ya nahi.
a = [1, 2, 3]
b = [1, 2, 3] # Same value, but different object!
c = a # Same object
print(a == b) # True (values same hain)
print(a is b) # False (objects alag hain)
print(a is c) # True (c toh a ka hi naam hai!)Membership Operators (in / not in)
Simple: Check karo ki koi cheez list/string mein hai ya nahi.
fruits = ["apple", "banana", "mango"]
print("banana" in fruits) # True ✅ hai!
print("grape" in fruits) # False ❌ nahi hai!
print("grape" not in fruits) # True ✅ sahi, nahi hai!
# Strings mein bhi kaam karta hai:
print("py" in "python") # True ✅Python Punctuation
- Colon
:→ if, for, while, function ke baad lagta hai - Comma
,→ Items alag karta hai (list mein, function mein) - Parentheses
()→ Function call karne mein - Square brackets
[]→ List banane ya index karne mein - Curly braces
{}→ Dictionary aur Set mein - Hash
#→ Comment likhne ke liye (Python ise ignore karta hai)
# Colon (:) - function definition mein
def namaste(name): # ← colon yahan hai
print(f"Namaste, {name}!")
# Brackets - list banao
fruits = ["Apple", "Banana", "Mango"] # ← square brackets
# Curly braces - dictionary banao
student = {"name": "Rahul", "age": 18} # ← curly braces
# Hash (#) - comments likhne ke liye
# Ye line Python ignore karegaPrint Statement
Basic Print
print("Hello, World!") # Text print karo
print(42) # Number print karo
print(True) # Boolean print karo
print("Mera naam", "Rahul") # Multiple items print karo
# Output: Mera naam RahulSeparator (sep) aur End
# sep = items ke beech mein kya aaye
print("Apple", "Banana", "Mango", sep=" | ")
# Output: Apple | Banana | Mango
# end = line ke end mein kya aaye (default: new line)
print("Hello", end=" ")
print("World!")
# Output: Hello World! (ek hi line mein!)F-strings — Sabse Best Tarika! ⭐
name = "Rahul"
age = 18
marks = 95.5
# f-string: f"..." ke andar {variable} likho
print(f"Mera naam {name} hai")
print(f"Meri age {age} hai")
print(f"Mere marks {marks} hain")
print(f"Next year meri age {age + 1} hogi")
# Old tarika (format method)
print("Naam: {}, Age: {}".format(name, age))f"..." likho aur variables {} mein daalo.Input Statement
Basic Input
# User se naam pucho
name = input("Aapka naam kya hai? ")
print(f"Namaste, {name}! Kaise ho?")
# Output:
# Aapka naam kya hai? Rahul ← user type karega
# Namaste, Rahul! Kaise ho?Number Input (Type Convert)
# ⚠️ input() hamesha STRING deta hai!
age_str = input("Age batao: ") # ye string hai: "18"
age = int(age_str) # ab integer hai: 18
# Short tarika — ek hi line mein:
age = int(input("Age batao: "))
next_year = age + 1
print(f"Next year aap {next_year} saal ke ho jaoge!")
# Float ke liye
height = float(input("Height batao (meters): "))
print(f"Aapki height {height} meters hai")Multiple Inputs Ek Line Mein
# Ek line mein do numbers lo
x, y = input("Do numbers likho (space se alag): ").split()
x, y = int(x), int(y)
print(f"Jod: {x + y}")
print(f"Guna: {x * y}")int() error de dega. Real programs mein try-except se error handle karo!String Operations
name = "Knobly Web"
# Length (kitne characters hain)
print(len(name)) # 9
# Uppercase / Lowercase
print(name.upper()) # Knobly Web
print(name.lower()) # Knobly Web
# Slicing (hissa nikalo)
print(name[0:6]) # Knobly (index 0 se 5 tak)
print(name[-2:]) # OS (last 2 characters)
# Replace (badal do)
print(name.replace("OS", "System")) # Knobly System
# Check karo kuch hai ya nahi
print("Knobly" in name) # True ✅
print("Python" in name) # False ❌
# Split (tod do)
words = "apple,banana,mango".split(",")
print(words) # ['apple', 'banana', 'mango']MCQ Quiz — Apna Knowledge Test Karo!
Neeche 10 important MCQs hain — har ek question ka answer select karo aur check karo kitna samjhe!
Who developed Python?
Which of the following is a valid Python identifier?
What is the output of 10 // 3?
Which keyword is NOT a Python keyword?
What does the input() function return?
What is the output of type(3.14)?
Which operator is used for exponentiation?
What is the output of "banana" in ["apple", "banana"]?
Which is NOT a valid string literal?
What does is operator check?
Practice Questions — Khud Karo!
In questions ka output khud socho, phir code chalake check karo! 💪
Arithmetic Operators
Output kya hoga? Pehle socho, phir check karo! 🤔
a = 10
b = 3
print(a // b) # ?
print(a % b) # ?
print(a ** b) # ?💡 Hint: Floor division, modulus aur power calculate karo.
Comparison & Logical
Output kya hoga? Pehle socho, phir check karo! 🤔
x = 5
y = 10
print(x == 5) # ?
print(x != y) # ?
print(x > y or x == 5) # ?💡 Hint: Har expression ko step by step solve karo.
Identity vs Equality
Output kya hoga? Pehle socho, phir check karo! 🤔
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # ?
print(list1 is list2) # ?
print(list1 is list3) # ?💡 Hint: == value check karta hai, is object check karta hai.
Assignment Operators
Output kya hoga? Pehle socho, phir check karo! 🤔
x = 10
x += 5 # x = 10 + 5 = ?
x *= 2 # x = ? * 2 = ?
x //= 3 # x = ? // 3 = ?
print(x) # Final answer?💡 Hint: Har step mein x ki value calculate karo.