Take your first step into the world of Python — your journey from zero to hero starts here!
Python is a high-level programming language created by Guido van Rossum in 1991. It is designed to be simple and readable — just like reading English!
| Field | Use Case | Example |
|---|---|---|
| Web Development | Building websites | Instagram, Pinterest |
| Data Science | Data analysis | Netflix recommendations |
| AI/ML | Building smart apps | ChatGPT, Self-driving cars |
| Automation | Automating boring tasks | File organizer, Email sender |
| Game Dev | Building games | Pygame projects |
# Python vs Other Languages — See the difference!
# Python mein Hello World:
print("Hello, World!")
# Java mein (kitna lamba hai!):
# public class Main {
# public static void main(String[] args) {
# System.out.println("Hello, World!");
# }
# }
Installing Python is very easy. Just go to python.org and download!
python --version
# Output: Python 3.12.x
# Install via Homebrew (recommended)
brew install python3
# Check version
python3 --version
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip
# Check version
python3 --version
print() is Python's most basic function — it shows anything on the screen.
print() like a speaker —
whatever you tell it, it will say it out loud on screen!# Example 1: Print simple text
print("Hello, World!")
print("Namaste World!")
print("I am learning Python!")
# Example 2: Print numbers
print(42)
print(3.14)
print(100 + 200)
# Example 3: Multiple values together
print("My age:", 20)
print("Sum:", 10 + 5, "and", "Diff:", 10 - 5)
# Example 4: Special characters
print("Line 1\nLine 2") # \n = New line
print("Tab\there") # \t = Tab space
print("He said \"Hello\"") # \" = Quote inside string
print('It\'s Python!') # \' = Apostrophe
# sep parameter — change separator
print("Python", "is", "awesome", sep="-")
# Output: Python-is-awesome
print("A", "B", "C", sep=" ❤️ ")
# Output: A ❤️ B ❤️ C
# end parameter — change line end
print("Hello", end=" ")
print("World!")
# Output: Hello World! (in same line)
# Single line comment — starts with #
print("Hello") # This is also a comment, after code
"""
Multi-line comment (Docstring)
You can write comments
in multiple lines
"""
# Python ignores comments — they are only for our understanding!
A variable is a container where we store data. Like a box where we keep things!
name = "Himanshu" stores "Himanshu" inside name!
# Creating variables — no special keyword needed!
name = "Himanshu" # String (text)
age = 20 # Integer (whole number)
height = 5.8 # Float (decimal number)
is_student = True # Boolean (True/False)
print(name) # Himanshu
print(age) # 20
print(height) # 5.8
print(is_student) # True
| Type | Description | Example |
|---|---|---|
int |
Whole numbers | 42, -10, 0 |
float |
Decimal numbers | 3.14, -0.5, 2.0 |
str |
Text/String | "Hello", 'Python' |
bool |
True or False | True, False |
NoneType |
No value | None |
# type() function — check data type
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
# Multiple assignment — multiple variables in one line!
a, b, c = 10, 20, 30
print(a, b, c) # 10 20 30
# Same value to multiple variables
x = y = z = 100
print(x, y, z) # 100 100 100
# Convert String to Integer
num_str = "42"
num_int = int(num_str)
print(num_int + 8) # 50
# Integer to String
age = 20
msg = "I am " + str(age) + " years old"
print(msg) # I am 20 years old
# Float conversions
print(int(3.7)) # 3 (decimal cut ho jaata hai)
print(float(5)) # 5.0
print(str(3.14)) # "3.14"
# Bool conversions
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False (empty string)
print(bool("Hello")) # True (non-empty string)
# ✅ Valid names
my_name = "Himanshu"
age2 = 20
_private = "secret"
CONSTANT = 3.14
# ❌ Invalid names — ye ERROR denge!
# 2name = "wrong" # Number se start nahi ho sakta
# my-name = "wrong" # Hyphen allowed nahi
# my name = "wrong" # Space allowed nahi
# class = "wrong" # Reserved keyword nahi use kar sakte
Q1. Store your name, age, and city in variables and print them. Easy
name = "Himanshu"
age = 20
city = "Delhi"
print(f"Name: {name}, Age: {age}, City: {city}")
Q2. Store two numbers in variables and print their sum, difference, product, and division. Easy
a = 15
b = 4
print("Sum:", a + b) # 19
print("Difference:", a - b) # 11
print("Product:", a * b) # 60
print("Division:", a / b) # 3.75
Q3. Use type() to print data types of different
values.
Easy
print(type(10)) # int
print(type(3.14)) # float
print(type("Python")) # str
print(type(True)) # bool
print(type([1, 2, 3])) # list
The input() function takes data from user via keyboard. It always returns a
string!
# Basic input
name = input("Enter your name: ")
print("Hello,", name, "! Welcome to PyMaster!")
# Number input — convert using int() or float()
age = int(input("Enter your age: "))
print("You are", age, "years old!")
# Multiple values
num1 = float(input("First number: "))
num2 = float(input("Second number: "))
print("Sum =", num1 + num2)
name = "Himanshu"
age = 20
cgpa = 8.75
# f-string (Python 3.6+) — The Best Method!
print(f"My name is {name}")
print(f"Age: {age}, CGPA: {cgpa}")
print(f"After 5 years I will be {age + 5} years old!")
print(f"CGPA formatted: {cgpa:.1f}") # 8.8 (1 decimal)
# You can also write expressions!
print(f"10 + 20 = {10 + 20}")
print(f"Name uppercase: {name.upper()}")
# Method 1: .format()
print("Name: {}, Age: {}".format("Himanshu", 20))
print("Name: {0}, Age: {1}".format("Himanshu", 20))
# Method 2: % formatting (old style)
print("Name: %s, Age: %d" % ("Himanshu", 20))
# Method 3: String concatenation
print("Name: " + "Himanshu" + ", Age: " + str(20))
Q1. Take name and age from user and print a greeting using f-string. Easy
name = input("Your name: ")
age = int(input("Your age: "))
print(f"Hello {name}! You are {age} years old.")
Q2. Take temperature in Celsius and convert to Fahrenheit. Medium
celsius = float(input("Temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit:.2f}°F")
a, b = 17, 5
print(f"Add: {a + b}") # 22
print(f"Subtract: {a - b}") # 12
print(f"Multiply: {a * b}") # 85
print(f"Divide: {a / b}") # 3.4 (float division)
print(f"Floor Div: {a // b}")# 3 (integer division)
print(f"Modulus: {a % b}") # 2 (remainder)
print(f"Power: {a ** b}") # 1419857 (17^5)
x, y = 10, 20
print(x == y) # False — Equal?
print(x != y) # True — Not Equal?
print(x > y) # False — Greater?
print(x < y) # True — Less than?
print(x >= 10) # True — Greater or equal?
print(x <= 5) # False — Less or equal?
age = 20
has_id = True
# and — BOTH conditions must be true
print(age >= 18 and has_id) # True
# or — ANY ONE condition must be true
print(age >= 21 or has_id) # True
# not — Reverses the result
print(not has_id) # False
print(not (age < 18)) # True
x = 10
x += 5 # x = x + 5 → 15
x -= 3 # x = x - 3 → 12
x *= 2 # x = x * 2 → 24
x /= 4 # x = x / 4 → 6.0
x //= 2 # x = x // 2 → 3.0
x **= 3 # x = x ** 3 → 27.0
print(x) # 27.0
Q1. Take 2 numbers from user and show results of all arithmetic operations. Easy
a = float(input("Number 1: "))
b = float(input("Number 2: "))
print(f"Sum: {a+b}, Diff: {a-b}, Product: {a*b}, Div: {a/b}")
Q2. Check if a number is even or odd (use modulus operator). Easy
num = int(input("Enter number: "))
print(f"{num} is {'Even' if num % 2 == 0 else 'Odd'}")
Just like we make decisions in real life — "If it rains, take an umbrella", in Python we use
if/elif/else.
# Example 1: Simple if/else
age = 20
if age >= 18:
print("You are an adult! ✅")
else:
print("You are still a minor! ❌")
# Example 2: if/elif/else — Multiple conditions
marks = 85
if marks >= 90:
print("Grade: A+ 🌟")
elif marks >= 80:
print("Grade: A 🎉")
elif marks >= 70:
print("Grade: B 👍")
elif marks >= 60:
print("Grade: C 😊")
else:
print("Grade: F 😢 — Work harder!")
# Output: Grade: A 🎉
# Example 3: Nested if
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive! 🚗")
else:
print("Get a license first! 📝")
else:
print("Wait until you turn 18! ⏳")
# Example 4: With logical operators
username = "admin"
password = "1234"
if username == "admin" and password == "1234":
print("Login successful! ✅")
else:
print("Wrong credentials! ❌")
# Example 5: Ternary operator (one-liner)
age = 20
status = "Adult" if age >= 18 else "Minor"
print(f"Status: {status}") # Adult
Q1. Take a number from user and check if it's positive, negative, or zero. Easy
num = float(input("Enter number: "))
if num > 0:
print("Positive ➕")
elif num < 0:
print("Negative ➖")
else:
print("Zero 0️⃣")
Q2. Create a grading system: 90+ = A+, 80+ = A, 70+ = B, 60+ = C, else F. Medium
marks = int(input("Enter marks: "))
if marks >= 90: grade = "A+"
elif marks >= 80: grade = "A"
elif marks >= 70: grade = "B"
elif marks >= 60: grade = "C"
else: grade = "F"
print(f"Grade: {grade}")
Q3. Create a leap year checker. Medium
year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a Leap Year! 🎉")
else:
print(f"{year} is NOT a Leap Year")
Loops allow us to do a task repeatedly — without writing code again and again!
print() 100 times? No! Use a Loop — done in one line!
# Example 1: With range()
for i in range(5):
print(f"Count: {i}")
# 0, 1, 2, 3, 4
# Example 2: Iterate a list
fruits = ["Apple", "Banana", "Mango", "Orange"]
for fruit in fruits:
print(f"I like {fruit}! 🍎")
# Example 3: range(start, stop, step)
for i in range(2, 11, 2):
print(i, end=" ") # 2 4 6 8 10
# Example 4: Iterate a string
for char in "Python":
print(char, end="-") # P-y-t-h-o-n-
# Example 1: Simple countdown
count = 5
while count > 0:
print(f"⏳ {count}...")
count -= 1
print("🚀 Launch!")
# Example 2: User input loop
while True:
answer = input("Quit? (yes/no): ")
if answer.lower() == "yes":
print("Bye! 👋")
break
# Example 3: Sum of numbers
total = 0
num = 1
while num <= 10:
total += num
num += 1
print(f"Sum of 1-10: {total}") # 55
# break — Exit the loop
for i in range(10):
if i == 5:
break # Stop at 5
print(i) # 0 1 2 3 4
# continue — Skip current iteration
for i in range(6):
if i == 3:
continue # Skip 3
print(i) # 0 1 2 4 5
# pass — Do nothing (placeholder)
for i in range(3):
pass # Write code later
# Star Triangle Pattern
for i in range(1, 6):
print("⭐" * i)
# ⭐
# ⭐⭐
# ⭐⭐⭐
# ⭐⭐⭐⭐
# ⭐⭐⭐⭐⭐
# Multiplication Table
num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Q1. Print all even numbers from 1 to 50. Easy
for i in range(2, 51, 2):
print(i, end=" ")
Q2. Create a factorial calculator (e.g., 5! = 120). Medium
n = int(input("Enter number: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"{n}! = {fact}")
Q3. Print Fibonacci series (first 10 numbers). Medium
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
# 0 1 1 2 3 5 8 13 21 34
Q4. Create a star pyramid pattern (5 rows). Hard
n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "⭐" * (2*i - 1))
A String is a sequence of characters — used to store text data.
# String Slicing — Extract parts
text = "Python Master"
print(text[0]) # P (first character)
print(text[-1]) # r (last character)
print(text[0:6]) # Python
print(text[7:]) # Master
print(text[::-1]) # retsaM nohtyP (reverse!)
# String Methods
msg = " Hello Python World! "
print(msg.strip()) # Remove spaces
print(msg.lower()) # all lowercase
print(msg.upper()) # ALL UPPERCASE
print(msg.title()) # Every Word Capital
print(msg.replace("Python", "Java"))
print(msg.split()) # Break into List
print("Python" in msg) # True — check
print(msg.count("l")) # 2 — how many times appeared
print(msg.find("Python")) # 8 — where found
print(msg.startswith(" ")) # True
print("-".join(["A","B","C"])) # A-B-C
Q1. Take a string from user and reverse it. Easy
text = input("Enter string: ")
print(f"Reversed: {text[::-1]}")
Q2. Check if a string is a palindrome (e.g., "madam"). Medium
text = input("Enter string: ").lower()
if text == text[::-1]:
print(f"'{text}' is a Palindrome! ✅")
else:
print(f"'{text}' is NOT a Palindrome ❌")
Q3. Count vowels in a string. Medium
text = input("Enter string: ").lower()
count = sum(1 for c in text if c in "aeiou")
print(f"Vowels: {count}")