Python Notes
Python syntax ke rules aur structure ko samjhein — indentation, statements, keywords, identifiers aur code likhne ka sahi tarika.
Hindi: Python syntax matlab Python ka grammar — woh rules jinke anusaar aap Python code likhte hain. Jaise Urdu/Hindi mein grammar hoti hai, waise hi Python ka apna ek set of rules hai.
2. Your First Python Program
# Hello World — every programmer's first step!
print("Hello, World!")Hello, World!
Hindi: print() ek built-in function hai jo screen par kuch bhi dikhata hai. Quotes ke andar jo bhi likhein, woh display hoga.3. Python Indentation (सबसे ज़रूरी नियम)
Python uses indentation (spaces/tabs at the start of a line) to define code blocks. This is Python's most unique and important rule.
Hindi: Indentation Python ka sabse important rule hai. Doosri languages mein {} curly braces use hote hain blocks ke liye, lekin Python mein spaces/tabs use hote hain.Comparison with Other Languages
C / Java / JavaScript
if (x > 0) {
print(x); // block defined by {}
}
Python
if x > 0:
print(x) # block defined by indentation
Correct Indentation Example
age = 20
if age >= 18:
print("Adult") # 4 spaces indented — inside if block
print("Can vote!") # same block
else:
print("Minor") # inside else block
print("Program ends") # outside if-else, no indentationAdult Can vote! Program ends
Wrong Indentation — SyntaxError!
if True:
print("Hello") # ❌ IndentationError: expected an indented blockIndentationError: expected an indented block after 'if' statement on line 1
ASCII Diagram — Indentation Blocks
Hindi: Ek rule yaad rakhein: ek hi block ke andar sabhi statements ka indentation SAME hona chahiye. Standard Python style 4 spaces use karta hai.
4. Python Statements
A statement is a single instruction that Python executes.
Simple Statements
x = 10 # assignment statement
print(x) # function call statement
x += 5 # augmented assignment
del x # delete statement10
Multi-line Statements (Line Continuation)
100 ['apple', 'banana', 'mango', 'orange']
Hindi: Agar statement bahut lamba ho toh backslash\ya parentheses()use karke agle line mein continue kar sakte hain. Brackets ke andar line continuation automatic hoti hai.
Multiple Statements on One Line (Semicolon)
# Using semicolons — valid but NOT recommended (PEP 8 violation)
x = 5; y = 10; z = 15
print(x, y, z)5 10 15
Hindi: Semicolon se ek line mein multiple statements likh sakte hain, lekin yeh Python style ke against hai. Avoid karein.
5. Python Keywords (Reserved Words)
Keywords are reserved words that have special meaning in Python. You cannot use them as variable names.
Hindi: Keywords wo special words hain jinhe Python ne apne liye reserve kiya hua hai. Inhe variable names ke roop mein use nahi kar sakte.
import keyword
print(keyword.kwlist)['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 Table
| Keyword | Purpose | Example |
|---|---|---|
if | Conditional | if x > 0: |
else | Alternative | else: |
elif | Else-if | elif x == 0: |
for | Loop | for i in range(5): |
while | Loop | while x > 0: |
def | Function | def greet(): |
class | Class | class Dog: |
return | Return value | return x |
import | Import module | import math |
True/False | Boolean | x = True |
None | Null value | x = None |
and/or/not | Logical ops | if a and b: |
6. Identifiers (Names)
An identifier is a name given to variables, functions, classes, etc.
Hindi: Identifier matlab naam — jab aap koi variable, function ya class banate hain, toh uska naam identifier hota hai.
Rules for Identifiers
✅ VALID identifiers:
name, age, my_variable, _private, MyClass, count1, camelCase
❌ INVALID identifiers:
1name (starts with digit)
my-name (hyphen not allowed)
my name (space not allowed)
class (reserved keyword)
@value (special char not allowed)# Valid identifiers
student_name = "Rahul"
_age = 20
MyClass = "Python"
count1 = 100
print(student_name, _age, MyClass, count1)Rahul 20 Python 100
Python Naming Conventions (PEP 8)
| Type | Convention | Example |
|---|---|---|
| Variable | snake_case | student_name |
| Function | snake_case | get_marks() |
| Class | PascalCase | StudentRecord |
| Constant | UPPER_CASE | MAX_SIZE = 100 |
| Private | _underscore | _private_var |
| Dunder | __double__ | __init__ |
7. Case Sensitivity
Python is case-sensitive — Name, name, and NAME are three different identifiers!
Hindi: Python mein capital aur small letters alag hote hain.Nameaurnamedo alag variables hain.
Name = "Rahul"
name = "Priya"
NAME = "AMIT"
print(Name) # Rahul
print(name) # Priya
print(NAME) # AMITRahul Priya AMIT
8. Comments in Syntax Context
# This is a single-line comment — Python ignores this
x = 10 # inline comment
"""
This is a multi-line string
often used as a docstring
"""
def greet(name):
"""This function greets a person.""" # docstring
print(f"Hello, {name}!")
greet("Rahul")Hello, Rahul!
9. Python Script Structure
A well-structured Python script follows this pattern:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module Docstring: Describe what this script does.
Author: WoHoTech
Date: 2026-06-12
"""
# 1. Standard library imports
import os
import sys
# 2. Third-party imports
# import numpy as np
# 3. Local imports
# from mymodule import myfunction
# 4. Constants
MAX_SIZE = 100
PI = 3.14159
# 5. Functions and Classes
def main():
"""Main function — entry point."""
print("Python script running!")
print(f"Python version: {sys.version}")
print(f"Working directory: {os.getcwd()}")
# 6. Entry point
if __name__ == "__main__":
main()Python script running! Python version: 3.11.x ... Working directory: C:\Users\...
Hindi: if __name__ == "__main__": block tab run hota hai jab aap script directly chalate hain. Yeh professional Python code ka standard pattern hai.10. Common Syntax Errors and Fixes
# Error 1: Missing colon
# ❌ Wrong
# if x > 0
# print(x)
# ✅ Fix
x = 5
if x > 0:
print(x)5
# Error 2: Wrong quotes
# ❌ Wrong
# print("Hello, World!') # mixed quotes
# ✅ Fix
print("Hello, World!")
print('Hello, World!') # both work if consistentHello, World! Hello, World!
# Error 3: Missing parentheses in function call
# ❌ Wrong (Python 2 style)
# print "Hello"
# ✅ Fix (Python 3)
print("Hello")Hello
# Error 4: Undefined variable
# ❌ Wrong
# print(z) # NameError: name 'z' is not defined
# ✅ Fix — define before use
z = 42
print(z)42
11. Interactive Python (REPL)
Hindi: REPL (Read-Eval-Print Loop) ek interactive environment hai jahan aap ek ek line Python code likh kar test kar sakte hain. Terminal mein python3 type karo aur enter karo.12. PEP 8 — Python Style Guide Quick Reference
| Rule | Bad | Good |
|---|---|---|
| Indentation | 2 spaces / tabs | 4 spaces |
| Line length | >79 chars | ≤79 chars |
| Blank lines | Random | 2 between functions |
| Spaces in expression | x=10 | x = 10 |
| Import style | import os,sys | One import per line |
| Naming | MyVariable | my_variable |
# PEP 8 compliant code example
import os
import sys
MAX_RETRIES = 3
def calculate_area(radius):
"""Calculate circle area."""
pi = 3.14159
return pi * radius ** 2
def main():
area = calculate_area(5)
print(f"Area = {area:.2f}")
if __name__ == "__main__":
main()Area = 78.54
Summary — Python Syntax Rules
Practice Exercises
Exercise 1 — Fix the Syntax Errors
# Fix all errors in this code:
# if True
# print("Hello"
# x=10
# y = 20
# Print(x + y)Expected output:
Hello 30
Exercise 2 — Naming Convention
Create variables for:
- A student's full name
- Their age
- Their class section (constant)
- A function to print their info
Exercise 3 — Script Structure
Write a complete Python script with:
- Proper docstring
- At least 2 functions
- A
main()function if __name__ == "__main__":block
Interview Questions
Q1. What is the significance of indentation in Python? > Python uses indentation to define code blocks instead of curly braces {}. It is mandatory — incorrect indentation causes IndentationError. Standard is 4 spaces per level.
Q2. Is Python case-sensitive? > Yes, Python is case-sensitive. Variable, variable, and VARIABLE are three distinct identifiers.
Q3. What are Python keywords? Give 5 examples. > Keywords are reserved words with special meaning: if, else, for, while, def, class, return, import, True, False. They cannot be used as variable names.
Q4. What is PEP 8? > PEP 8 is Python's official style guide. It defines conventions for indentation (4 spaces), naming (snake_case for variables, PascalCase for classes), line length (79 chars max), and code organization.
Q5. What is the difference between a syntax error and a runtime error? > A syntax error occurs when the code violates Python's grammar rules and is detected before execution (e.g., missing colon). A runtime error occurs during execution (e.g., dividing by zero, accessing undefined variable).
⚠️ Common Mistakes
1. Indentation Mix — Tabs aur Spaces Mix karna 🚫
# ❌ Wrong — tab aur spaces mix
if True:
print("Hello") # spaces
print("World") # tab — IndentationError!Hindi: Kabhi bhi tabs aur spaces mix mat karo. Hamesha 4 spaces use karo. Editor mein "Convert Tabs to Spaces" enable rakhein.
2. Colon ( : ) Bhool Jaana 😅
# ❌ Wrong
if x > 5
print(x)
# ✅ Correct
if x > 5:
print(x)Hindi:if,else,for,while,def,classke baad colon:lagana zaruri hai. Yeh sabse common beginner mistake hai.
3. = aur == ka Confusion 🔄
# ❌ Wrong — assignment use kiya comparison ke jagah
if x = 10: # SyntaxError!
print("yes")
# ✅ Correct
if x == 10:
print("yes")Hindi:=assignment ke liye hai (value dena),==comparison ke liye hai (check karna ki equal hai ya nahi).
4. Keyword ko Variable Name banana 🚷
# ❌ Wrong
class = "10th" # SyntaxError! 'class' is a keyword
for = 5 # SyntaxError! 'for' is a keyword
# ✅ Correct
student_class = "10th"
loop_count = 5Hindi: Python ke reserved keywords (jaiseclass,for,if,return) ko variable name ke roop mein use karna allowed nahi hai.
5. Brackets/Parentheses Band na karna 🔓
Hindi: Har opening bracket(,[,{ke liye closing bracket),],}hona chahiye. Editor mein bracket matching enable karein.
6. Quotes Mismatch karna 🔀
# ❌ Wrong
message = "Hello, World!' # single aur double mix
name = 'Rahul" # mismatch!
# ✅ Correct
message = "Hello, World!"
name = 'Rahul'Hindi: String start aur end mein same type ke quotes hone chahiye — ya toh dono single' 'ya dono double" ".
7. print mein Parentheses Bhoolna (Python 3) 🖨️
# ❌ Wrong (Python 2 style)
# print "Hello" # SyntaxError in Python 3!
# ✅ Correct (Python 3)
print("Hello")Hindi: Python 3 mein()zaroori hain. Python 2 styleprint "text"ab kaam nahi karta.
✅ Key Takeaways
- 🔹 Indentation is KING — Python mein indentation code blocks define karta hai. Hamesha 4 spaces use karein, tabs se bachein.
- 🔹 Colon rule —
if,else,elif,for,while,def,classke baad hamesha colon:lagaein. - 🔹 Case-sensitive — Python mein
Name,name, aurNAMEteen alag cheezein hain. Naming mein consistent rahein. - 🔹 Keywords are reserved — Python ke 35 keywords (jaise
if,for,class,return) ko variable name ke roop mein use nahi kar sakte. - 🔹 PEP 8 follow karein — Variables ke liye
snake_case, Classes ke liyePascalCase, Constants ke liyeUPPER_CASEuse karein. - 🔹 Line continuation — Long statements ke liye parentheses
()ya backslash\use karein. Parentheses preferred hain. - 🔹 Comments likhein —
#se single-line comments aur"""..."""se docstrings likhein. Code readable banayein. - 🔹 REPL for testing — Terminal mein
python3type karke interactive mode mein quick testing karein. - 🔹 Script structure — Professional code mein imports → constants → functions →
if __name__ == "__main__":pattern follow karein. - 🔹 Syntax Error = Grammar Error — Agar Python
SyntaxErrorde, toh samjho code ka grammar galat hai. Colon, brackets, quotes check karein.
❓ FAQ
Q1. Kya Python mein semicolons zaroori hain? > ❌ Nahi! Python mein semicolons optional hain. Aap ek line mein multiple statements likh sakte hain x = 5; y = 10 lekin yeh PEP 8 ke against hai. Recommended: har statement alag line mein likhein.
Q2. Indentation ke liye Tabs use karein ya Spaces? > Hamesha 4 spaces use karein. Python officially spaces recommend karta hai (PEP 8). Tabs aur spaces mix karna TabError deta hai. Apne editor mein "Insert Spaces" option enable karein.
Q3. Python mein kitne keywords hain? > Python 3.11+ mein 35 keywords hain. import keyword; print(len(keyword.kwlist)) se check kar sakte hain. Yeh list Python version ke saath thoda change ho sakti hai.
Q4. Kya variable name mein Hindi/Unicode characters use kar sakte hain? > Technically haan — Python 3 Unicode identifiers support karta hai (नाम = "Rahul" valid hai). Lekin professional code mein English names hi use karein for readability aur team collaboration.
Q5. SyntaxError: invalid syntax ka kya matlab hai? > Iska matlab hai ki Python aapke code ko samajh nahi paa raha. Common reasons: colon : missing, bracket band nahi kiya, quotes mismatch, ya keyword galat use kiya. Error message mein line number dekhein aur us line ke aas-paas check karein.
Q6. Kya Python mein blank lines matter karti hain? > Code execution mein blank lines se koi fark nahi padta — Python unhe ignore karta hai. Lekin readability ke liye PEP 8 kehta hai: functions ke beech 2 blank lines, class methods ke beech 1 blank line rakhein.
Q7. Python mein maximum line length kitni honi chahiye? > PEP 8 ke according 79 characters per line recommended hai. Comments ke liye 72 characters. Agar line lamba ho toh parentheses () ya backslash \ se break karein. Modern projects mein kuch teams 100-120 chars bhi allow karti hain.
Q8. if __name__ == "__main__": ka kya role hai? > Yeh line check karti hai ki script directly run ho rahi hai ya import ho rahi hai. Agar directly run ho (python script.py) toh __name__ ki value "__main__" hoti hai aur block execute hota hai. Import hone par yeh block skip ho jaata hai. Yeh professional Python code ka standard pattern hai.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Syntax.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, syntax, python syntax
Related Python Master Course Topics