Python Notes
Write your first Python program step-by-step. Learn Hello World, variables, input/output, comments, and basic syntax. Pehla Python program kaise likhein – Hindi mein complete beginner guide.
Hindi: Congratulations! Python install ho gaya, editor ready hai – ab waqt aa gaya hai apna pehla Python program likhne ka! Yeh guide aapko step-by-step pehle simple program se lekar thoda advanced programs tak le jaayegi.
🌍 The Tradition of Hello World
When programmers learn a new language, they always start with a "Hello, World!" program. This tradition started in the 1970s from a book called "The C Programming Language."
Hindi: Har programming language mein pehla program "Hello, World!" print karna hota hai – yeh ek tradition hai jo 1970s se chali aa rahi hai. Python mein yeh program sirf ek line mein likha jaata hai – yeh Python ki simplicity ka sabse bada proof hai!
| │ Java | System.out.println("Hello, World!"); │ |
| │ C++ | cout << "Hello, World!" << endl; │ |
| │ C | printf("Hello, World!\n"); │ |
| │ Java | System.out.println("Hello, World!"); │ |
| │ PHP | echo "Hello, World!"; │ |
| │ Go | fmt.Println("Hello, World!") │ |
| │ Python | print("Hello, World!") ◄── Simplest! │ |
Python wins! Just one simple line vs multiple complex lines in other languages.
🚀 Your First Line of Code
Method 1: Python Shell (Interactive)
Open your terminal or IDLE Shell and type:
>>> print("Hello, World!")Press Enter and see the magic!
Hello, World!
🎉 Congratulations! You just ran your first Python code!
Hindi: Yeh dekho! Sirf ek line – print("Hello, World!") – aur computer ne print kar diya. Python itna simple hai!Method 2: Script File
Create a file called hello.py and write:
# hello.py – My First Python Program
# Author: Your Name
# Date: June 12, 2026
print("Hello, World!")
print("Namaste India!")
print("Python seekhna shuru karte hain!")Run it:
python hello.pyHello, World! Namaste India! Python seekhna shuru karte hain!
🏃 Running Python in Different Ways
Hindi: Python code chalane ke kai tarike hain – inhe jaanna important hai.
| │ Open IDLE | type in Shell window │ |
| │ IDLE | File → New File → write code → F5 to run │ |
| │ Open .py file | Click ▶ or press F5 │ |
| │ $ jupyter notebook | write in cells → Shift+Enter │ |
| │ https | //repl.it or https://colab.research.google.com │ |
🖨️ Understanding print()
The print() function is the most fundamental Python function – it displays output on the screen.
Hindi: print() Python ka sabse basic aur important function hai. Yeh screen par kuch bhi dikhata hai – numbers, text, variables sab kuch!Basic Usage:
# Print a string (text)
print("Hello, Python!")Hello, Python!
# Print a number
print(42)42
# Print multiple items
print("My age is", 25)My age is 25
# Print with a blank line (just call print with no args)
print("Line 1")
print()
print("Line 2")Line 1 Line 2
print() Parameters:
# sep parameter – separator between items (default: space)
print("Python", "is", "awesome", sep="-")Python-is-awesome
print("a", "b", "c", sep=", ")a, b, c
# end parameter – what to print at end (default: newline \n)
print("Hello", end=" ")
print("World")Hello World
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".", end="")
print(" Done!")Loading... Done!
# Print special characters
print("Name:\tRahul") # \t = tab
print("Line1\nLine2") # \n = new line
print("He said \"Hi\"") # \" = escaped quote
print("Path: C:\\Users") # \\ = backslashName: Rahul Line1 Line2 He said "Hi" Path: C:\Users
Hindi:print()ke andarsepparameter se items ke beech separator set karte hain, aurendparameter se line ke end mein kya aaye woh set karte hain.\nnewline hai,\ttab hai.
💬 Python Comments
Comments are notes in your code that Python ignores. They are for humans to read.
Hindi: Comments woh text hota hai jo Python execute nahi karta – yeh sirf programmers ke liye notes hain. Good comments code ko samajhne mein help karte hain.
Single-line Comments:
# This is a single-line comment
print("Hello") # This comment is after the code
# Python ignores everything after the # symbol
# name = "Rahul" ← This line is commented out (won't run)Multi-line Comments (Docstrings):
"""
This is a multi-line comment
or docstring.
It can span multiple lines.
"""
print("The docstring above is ignored")
'''
You can also use single quotes
for multi-line strings/comments
'''The docstring above is ignored
Why Use Comments?
# ❌ Bad code (no comments, hard to understand)
r = 7
a = 3.14159 * r * r
# ✅ Good code (with comments, easy to understand)
radius = 7 # radius of circle in cm
pi = 3.14159 # value of pi (π)
area = pi * radius * radius # formula: A = π × r²
print(f"Circle area: {area:.2f} cm²")Circle area: 153.94 cm²
Hindi: Comments likhna ek achhi habit hai. Chahe code simple lage, 6 mahine baad aap hi nahi samajhte ki kyun kuch kiya tha – comments yaad dilate hain!
📦 Variables – Storing Information
Variables are containers that store data values. Think of them like labeled boxes.
Hindi: Variable ek box ki tarah hai jisme koi bhi value rakh sakte hain – number, text, list kuch bhi. Box ka naam hi variable ka naam hota hai.
| Box label: name | ||
|---|---|---|
| Contents: "Rahul" | ||
| Box label: age | ||
| Contents: 25 |
Creating Variables:
# Assign a value to a variable using =
name = "Alice"
age = 30
height = 5.6
is_student = True
# Print them
print(name)
print(age)
print(height)
print(is_student)Alice 30 5.6 True
Variable Naming Rules:
# ✅ Valid variable names
my_name = "Rahul"
firstName = "Priya" # camelCase
_private = "hidden" # starts with underscore
age2 = 25 # contains number (not at start)
CONSTANT = 3.14159 # UPPERCASE for constants
# ❌ Invalid variable names
# 2age = 25 → cannot start with number
# my-name = "Raj" → hyphens not allowed
# my name = "Ali" → spaces not allowed
# class = "Python" → class is a keyword
# for = 10 → for is a keywordVariable Rules Summary:
✅ Start with a letter or underscore (_)
✅ Can contain letters, numbers, and underscores
✅ Case-sensitive (name ≠ Name ≠ NAME)
❌ Cannot start with a number
❌ Cannot contain spaces or special characters
❌ Cannot be a Python keyword (if, for, while, def, class...)Multiple Assignment:
# Assign same value to multiple variables
x = y = z = 0
print(x, y, z)0 0 0
# Assign different values in one line
a, b, c = 10, 20, 30
print(a, b, c)10 20 30
# Swap variables (Python magic!)
x = 5
y = 10
x, y = y, x # Swap!
print(f"x={x}, y={y}")x=10, y=5
Hindi: Variables Python mein dynamically typed hote hain – aapko batana nahi padta ki variable mein kaunsa type store hoga. Python automatically samajh jaata hai.
🎲 Basic Data Types
Hindi: Python mein 4 basic data types hain: int (integers/whole numbers), float (decimal numbers), str (text), aur bool (True/False).
# Integer – whole numbers
my_age = 25
year = 2026
temperature = -5
big_number = 1_000_000 # underscore as thousands separator
# Float – decimal numbers
pi = 3.14159
price = 99.99
weight = 65.5
# String – text
name = "Rahul Kumar"
city = 'Mumbai'
message = "I love Python!"
multiline = """This is
a multiline
string"""
# Boolean – True or False
is_sunny = True
has_python = False
is_adult = True# Check the type of a variable
print(type(25))
print(type(3.14))
print(type("Hello"))
print(type(True))<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
Type Conversion:
# Convert between types
age_str = "25"
age_int = int(age_str) # String to Integer
print(age_int + 5) 30
price = 99.99
price_int = int(price) # Float to Integer (truncates)
price_str = str(price) # Float to String
print(price_int)
print(price_str) 99 99.99
# Boolean conversions
print(bool(0)) # 0 = False
print(bool(1)) # 1 = True
print(bool("")) # empty string = False
print(bool("hi")) # non-empty = TrueFalse True False True
🎤 Getting User Input
Hindi: input() function se user se data le sakte hain – jaise calculator mein number type karte hain.Basic input():
# Get user's name
name = input("Enter your name: ")
print("Hello,", name + "!")Enter your name: Priya Hello, Priya!
Input is Always a String!
# This will cause an error:
age = input("Enter your age: ")
next_year_age = age + 1 # ❌ TypeError! Can't add string + int# Correct way – convert to int first:
age = int(input("Enter your age: "))
next_year_age = age + 1 # ✅ Works now
print(f"Next year you'll be {next_year_age}")Enter your age: 20 Next year you'll be 21
# Float input
price = float(input("Enter price: "))
tax = price * 0.18
total = price + tax
print(f"Price: ₹{price:.2f}")
print(f"Tax (18%): ₹{tax:.2f}")
print(f"Total: ₹{total:.2f}")Enter price: 500 Price: ₹500.00 Tax (18%): ₹90.00 Total: ₹590.00
Hindi:input()hamesha string return karta hai. Agar number chahiye tohint()yafloat()se convert karna padta hai.
✍️ String Formatting
Hindi: String formatting se text aur variables ko milaakar ek achha output bana sakte hain.
Method 1: f-Strings (Recommended – Python 3.6+)
name = "Rahul"
age = 25
city = "Delhi"
# f-string: prefix f before the string, use {} for variables
message = f"My name is {name}, I am {age} years old from {city}."
print(message)My name is Rahul, I am 25 years old from Delhi.
# f-strings support expressions inside {}
price = 1000
discount = 200
print(f"You saved ₹{discount} ({discount/price*100:.1f}% off)!")You saved ₹200 (20.0% off)!
Method 2: .format()
name = "Priya"
score = 95
print("Student: {}, Score: {}%".format(name, score))Student: Priya, Score: 95%
Method 3: % Formatting (Old style)
name = "Ali"
print("Hello, %s!" % name)
print("Pi = %.2f" % 3.14159)Hello, Ali! Pi = 3.14
Format Specifiers:
pi = 3.14159265358979
print(f"{pi:.2f}") # 2 decimal places → 3.14
print(f"{pi:.4f}") # 4 decimal places → 3.1416
print(f"{pi:10.2f}") # width 10, 2 decimal → ' 3.14'
print(f"{1000000:,}") # Thousands separator → 1,000,000
print(f"{'hello':>10}")# Right align width 10 → ' hello'
print(f"{'hello':<10}")# Left align width 10 → 'hello '
print(f"{'hello':^10}")# Center width 10 → ' hello '
print(f"{42:05d}") # Zero pad width 5 → 000423.14
3.1416
3.14
1,000,000
hello
hello
hello
00042➕ Basic Arithmetic Operations
Hindi: Python mein basic math operations karna bahut simple hai.
# Basic arithmetic operators
a = 20
b = 6
print(f"{a} + {b} = {a + b}") # Addition
print(f"{a} - {b} = {a - b}") # Subtraction
print(f"{a} * {b} = {a * b}") # Multiplication
print(f"{a} / {b} = {a / b}") # Division (float result)
print(f"{a} // {b} = {a // b}") # Floor division (int result)
print(f"{a} % {b} = {a % b}") # Modulus (remainder)
print(f"{a} ** {b} = {a ** b}") # Exponentiation (power)20 + 6 = 26 20 - 6 = 14 20 * 6 = 120 20 / 6 = 3.3333333333333335 20 // 6 = 3 20 % 6 = 2 20 ** 6 = 64000000
# Operator shorthand (augmented assignment)
x = 10
x += 5 # same as x = x + 5
print(x) # 15
x -= 3 # x = x - 3
print(x) # 12
x *= 2 # x = x * 2
print(x) # 24
x //= 5 # x = x // 5
print(x) # 415 12 24 4
Order of Operations (PEMDAS):
# Python follows standard math order of operations
result = 2 + 3 * 4 # Multiplication first: 2 + 12 = 14
print(result)
result = (2 + 3) * 4 # Brackets first: 5 * 4 = 20
print(result)
result = 10 - 2 ** 3 # Power first: 10 - 8 = 2
print(result)14 20 2
Hindi: Python mein PEMDAS order follow hota hai: Parentheses (brackets) → Exponents (power) → Multiplication/Division → Addition/Subtraction.
🎯 Your First Real Program
Now let's combine everything into a real program!
Hindi: Ab tak jo seekha hai sab use karke ek complete program banate hain – ek simple student grade calculator!
# student_grade_calculator.py
# A complete beginner Python program
# Uses: print, input, variables, arithmetic, f-strings
# ============================================
# STUDENT GRADE CALCULATOR
# WohoTech Python Master Course
# ============================================
print("=" * 50)
print(" STUDENT GRADE CALCULATOR")
print(" WohoTech Python Course")
print("=" * 50)
print()
# Get student information
student_name = input("Enter student name: ")
roll_number = input("Enter roll number: ")
print()
print("Enter marks for 5 subjects (out of 100):")
print("-" * 40)
# Get marks for 5 subjects
math = float(input("Mathematics: "))
science = float(input("Science : "))
english = float(input("English : "))
hindi = float(input("Hindi : "))
computer = float(input("Computer : "))
# Calculate results
total = math + science + english + hindi + computer
max_marks = 500
percentage = (total / max_marks) * 100
average = total / 5
# Determine grade
if percentage >= 90:
grade = "A+"
remark = "Outstanding!"
elif percentage >= 80:
grade = "A"
remark = "Excellent!"
elif percentage >= 70:
grade = "B+"
remark = "Very Good!"
elif percentage >= 60:
grade = "B"
remark = "Good!"
elif percentage >= 50:
grade = "C"
remark = "Average"
elif percentage >= 40:
grade = "D"
remark = "Below Average"
else:
grade = "F"
remark = "Fail – Please Work Harder"
# Display result card
print()
print("=" * 50)
print(" RESULT CARD")
print("=" * 50)
print(f" Student Name : {student_name}")
print(f" Roll Number : {roll_number}")
print("-" * 50)
print(f" Mathematics : {math:.1f}")
print(f" Science : {science:.1f}")
print(f" English : {english:.1f}")
print(f" Hindi : {hindi:.1f}")
print(f" Computer : {computer:.1f}")
print("-" * 50)
print(f" Total Marks : {total:.1f} / {max_marks}")
print(f" Percentage : {percentage:.2f}%")
print(f" Average : {average:.2f}")
print(f" Grade : {grade}")
print(f" Remark : {remark}")
print("=" * 50)
print()
print("Thank you for using WohoTech Grade Calculator!")==================================================
STUDENT GRADE CALCULATOR
WohoTech Python Course
==================================================
Enter student name: Anjali Sharma
Enter roll number: CS2026-42
Enter marks for 5 subjects (out of 100):
----------------------------------------
Mathematics: 92
Science : 88
English : 79
Hindi : 95
Computer : 97
==================================================
RESULT CARD
==================================================
Student Name : Anjali Sharma
Roll Number : CS2026-42
--------------------------------------------------
Mathematics : 92.0
Science : 88.0
English : 79.0
Hindi : 95.0
Computer : 97.0
--------------------------------------------------
Total Marks : 451.0 / 500
Percentage : 90.20%
Average : 90.20
Grade : A+
Remark : Outstanding!
==================================================
Thank you for using WohoTech Grade Calculator!Hindi: Yeh program ek complete grade calculator hai – student ka naam, subjects ke marks input lete hain, total, percentage, average calculate karte hain, aur grade dete hain. Ek real Python program!
📐 Python Syntax Rules
Hindi: Python mein kuch important syntax rules hain jo hamesha yaad rakhni chahiye.
Indentation Examples:
# ✅ Correct indentation (4 spaces)
if True:
print("Inside if") # 4 spaces
if True:
print("Nested if") # 8 spaces (4+4)
# ❌ Wrong – mixed indentation
if True:
print("Line 1") # 4 spaces
print("Line 2") # 2 spaces ← IndentationError!Hindi: Python mein indentation (spaces) ki galti sabse common beginner mistake hai. Hamesha 4 spaces use karein – Tab key bhi 4 spaces insert karta hai most editors mein.
⚠️ Common Beginner Mistakes
Mistake 1: Forgetting Quotes Around Strings
# ❌ Wrong
name = Rahul # NameError: Rahul is not defined
# ✅ Correct
name = "Rahul" # String in quotesMistake 2: Case Sensitivity
# ❌ Wrong
Print("Hello") # NameError: name 'Print' is not defined
Name = "Rahul"
print(name) # NameError: name 'name' is not defined
# ✅ Correct
print("Hello") # lowercase print
Name = "Rahul"
print(Name) # same case as variableMistake 3: Wrong Arithmetic with Strings
# ❌ Wrong
age = input("Enter age: ") # Returns string "25"
new_age = age + 1 # TypeError: can only concatenate str (not "int") to str
# ✅ Correct
age = int(input("Enter age: ")) # Convert to int first
new_age = age + 1 # Now it works: 25 + 1 = 26Mistake 4: Indentation Error
# ❌ Wrong
for i in range(3):
print(i) # IndentationError
# ✅ Correct
for i in range(3):
print(i) # 4 spaces before printMistake 5: Division Creates Float
# Python 3: division always returns float
result = 10 / 2
print(result) # 5.0, NOT 5
print(type(result)) # <class 'float'>
# Use // for integer division
result = 10 // 2
print(result) # 5 (int)🔧 Troubleshooting Errors
Hindi: Python mein common errors aur unke solutions yahan diye gaye hain.
SyntaxError
# Error:
print("Hello" # Missing closing parenthesis
# SyntaxError: '(' was never closed
# Fix:
print("Hello") # Add closing )NameError
# Error:
print(massage) # Typo! Should be 'message'
# NameError: name 'massage' is not defined
# Fix:
message = "Hello"
print(message) # Use the correct variable nameTypeError
# Error:
print("I am " + 25 + " years old")
# TypeError: can only concatenate str (not "int") to str
# Fix:
print("I am " + str(25) + " years old") # Convert int to str
# Or use f-string:
print(f"I am {25} years old") # Even better!IndentationError
# Error:
def greet():
print("Hi") # Not indented!
# IndentationError: expected an indented block
# Fix:
def greet():
print("Hi") # 4 spaces indentationValueError
# Error:
age = int("twenty")
# ValueError: invalid literal for int() with base 10: 'twenty'
# Fix:
age = int("20") # Use a numeric stringHindi: Error messages padna bahut important hai – woh exactly batate hain ki kya galat hua. Python ke error messages bahut descriptive hote hain.
💪 Practice Programs
Hindi: Yeh practice programs aap khud likhein aur run karein – seekhne ka sabse achha tarika practice karna hai!
Program 1: Simple Greeting
# Write a program that asks for name and age
# and prints a personalized greeting
name = input("What is your name? ")
age = int(input("How old are you? "))
birth_year = 2026 - age
print()
print(f"Hello, {name}! 👋")
print(f"You were born in {birth_year}.")
print(f"When you turn 100, it will be {birth_year + 100}.")Program 2: Temperature Converter
# Convert Celsius to Fahrenheit and Kelvin
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
kelvin = celsius + 273.15
print(f"\n{celsius}°C = {fahrenheit:.2f}°F = {kelvin:.2f}K")Program 3: Area Calculator
# Calculate area of different shapes
import math
print("=== AREA CALCULATOR ===")
print("1. Circle")
print("2. Rectangle")
print("3. Triangle")
print()
choice = input("Enter choice (1/2/3): ")
if choice == "1":
r = float(input("Enter radius: "))
area = math.pi * r ** 2
print(f"Area of Circle = {area:.4f} sq units")
elif choice == "2":
l = float(input("Enter length: "))
w = float(input("Enter width: "))
area = l * w
print(f"Area of Rectangle = {area:.2f} sq units")
elif choice == "3":
b = float(input("Enter base: "))
h = float(input("Enter height: "))
area = 0.5 * b * h
print(f"Area of Triangle = {area:.2f} sq units")
else:
print("Invalid choice!")🚀 Summary
You have written your first Python programs!
Hindi: Shabash! Aapne apna pehla Python program likha aur run kiya. Ab aap variables, print, input, aur arithmetic – yeh sab samajhte hain. Yeh foundation hai – aage aur interesting cheezein seekhenge!
Next Steps:
| Step | Topic | File |
|---|---|---|
| ← Previous | Python IDLE | python-idle.mdx |
| → Next | Environment Setup | python-environment-setup.mdx |
| → Advanced | Python Data Types | Coming Soon |
*Last Updated: June 12, 2026 | Author: WohoTech | Category: Python Setup*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Your First Python Program – Hello World & Beyond 2026.
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, setup, first, program
Related Python Master Course Topics