Chapter 1: Core Python - Simple Samjhao (Easy Explanation) 🐍

Dost, ye chapter mein main tujhe Python ka basics samjhaunga, bilkul simple language mein! Jaise main tere saath baith kar explain kar raha hun.

Table of Contents

  1. Variables & Data Types (Variables aur Data Types)
  2. Type Conversion & Casting (Type Badalna)
  3. Input/Output Operations (User se Input Lena)
  4. Operators (Mathematical Operations)
  5. Control Flow (Conditions aur Loops)
  6. Functions (Reusable Code)
  7. Common Interview Questions (Interview ke Sawal)
  8. Practice Problems (Practice ke Liye)

Variables & Data Types (Variables aur Data Types)

Basic Data Types (Basic Data Types)

Dost, samjho ki Python mein different types ke data hote hain, jaise different types ke boxes hote hain different cheezein rakhne ke liye!

1. Numbers (Numbers - Gintein)

Dost, numbers matlab gintein! Python mein 3 types ke numbers hote hain:

# Integer (Pura number) - jaise 1, 2, 3, 100
age = 25
print(type(age))  # <class 'int'> - ye bata raha hai ki age ek integer hai
 
# Float (Decimal number) - jaise 5.9, 3.14
height = 5.9
print(type(height))  # <class 'float'> - ye bata raha hai ki height ek float hai
 
# Complex (Complex number) - advanced math ke liye
complex_num = 3 + 4j
print(type(complex_num))  # <class 'complex'>

Simple samjho:

  • Integer = Pura number (25, 100, -50)
  • Float = Decimal wala number (5.9, 3.14, 2.5)
  • Complex = Advanced math (abhi ke liye ignore kar sakte ho)

2. Strings (Text - Shabd)

Dost, string matlab text! Jaise tumhara naam, address, koi bhi text string hai.

# String creation (String banane ke tarike)
name = "John Doe"          # Double quotes mein
message = 'Hello World'    # Single quotes mein (donon same hain)
multiline = """This is a
multiline string"""        # Multiple lines ke liye
 
# String methods (String ke saath kaam karne ke tarike)
text = "  Hello World  "
print(text.strip())        # "Hello World" - spaces hata deta hai
print(text.upper())        # "  HELLO WORLD  " - sabko capital banata hai
print(text.lower())        # "  hello world  " - sabko small banata hai
print(text.split())        # ['Hello', 'World'] - words ko alag kar deta hai
print(text.replace("World", "Python"))  # "  Hello Python  " - word replace kar deta hai

Simple samjho:

  • String = Text (naam, address, koi bhi shabd)
  • strip() = Extra spaces hata deta hai
  • upper() = Sabko capital letters banata hai
  • lower() = Sabko small letters banata hai
  • split() = Words ko alag kar deta hai
  • replace() = Ek word ko dusre se replace kar deta hai

3. Boolean (True/False - Sach/Jhooth)

Dost, boolean matlab sach ya jhooth! Sirf 2 values hain - True ya False.

is_student = True    # True matlab sach
is_working = False   # False matlab jhooth
print(type(is_student))  # <class 'bool'> - ye bata raha hai ki boolean hai
 
# Truthy and Falsy values (Kya sach hai, kya jhooth)
print(bool(0))      # False - 0 jhooth hai
print(bool(1))      # True - 1 sach hai
print(bool(""))     # False - empty string jhooth hai
print(bool("hi"))   # True - koi bhi text sach hai
print(bool([]))     # False - empty list jhooth hai
print(bool([1,2]))  # True - list mein kuch hai to sach hai

Simple samjho:

  • Boolean = Sirf True ya False
  • True = Sach, haan, correct
  • False = Jhooth, nahi, wrong
  • 0, empty string, empty list = False
  • Koi bhi number (except 0), text, list with items = True

4. Lists (Lists - Items ki List)

Dost, list matlab items ki list! Jaise tumhara shopping list - apple, banana, cherry sab ek list mein.

# List creation and manipulation (List banane aur modify karne ke tarike)
fruits = ["apple", "banana", "cherry"]  # Square brackets mein items
numbers = [1, 2, 3, 4, 5]               # Numbers ki list
 
# Common list operations (List ke saath common kaam)
fruits.append("orange")        # Add to end - last mein add karta hai
fruits.insert(1, "grape")      # Insert at index - specific position mein add karta hai
fruits.remove("banana")        # Remove first occurrence - pehla wala remove karta hai
fruits.pop()                   # Remove and return last element - last wala nikalta hai
fruits.pop(0)                  # Remove and return element at index - specific position wala nikalta hai
 
# List slicing (List ka hissa nikalna - interview mein bahut important!)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])    # [2, 3, 4] - index 2 se 5 tak (5 include nahi)
print(numbers[:3])     # [0, 1, 2] - start se 3 tak
print(numbers[3:])     # [3, 4, 5, 6, 7, 8, 9] - 3 se end tak
print(numbers[::2])    # [0, 2, 4, 6, 8] - har 2nd element
print(numbers[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] - reverse order

Simple samjho:

  • List = Items ki list (shopping list jaisi)
  • append() = Last mein add karna
  • insert() = Specific position mein add karna
  • remove() = Item ko remove karna
  • pop() = Last item ko nikalna
  • Slicing [start:end] = List ka hissa nikalna
  • Indexing = 0 se start hota hai (pehla item = 0, dusra = 1, etc.)

5. Tuples (Tuples - Fixed Lists)

Dost, tuple bhi list jaisa hai, lekin ye change nahi ho sakta! Jaise tumhara birth date - fix hai, change nahi kar sakte.

# Tuple creation (immutable - change nahi ho sakta)
coordinates = (10, 20)           # Round brackets mein
person = ("John", 25, "Engineer") # Multiple values
 
# Tuple unpacking (Tuple ko alag variables mein dalna - interview mein common sawal)
name, age, job = person
print(name)  # John
 
# Single element tuple (ek element wala tuple - comma zaroori hai!)
single = (42,)  # Comma zaroori hai, nahi to tuple nahi banta

Simple samjho:

  • Tuple = List jaisa, lekin change nahi ho sakta
  • Round brackets () = Tuple banane ke liye
  • Immutable = Change nahi kar sakte (add, remove, modify nahi)
  • Unpacking = Tuple ko alag variables mein dalna
  • Single element tuple = Comma zaroori hai (42,) - (42) tuple nahi hai!

6. Dictionaries (Dictionaries - Key-Value Pairs)

Dost, dictionary matlab key-value pairs! Jaise tumhara phone book - naam (key) aur number (value).

# Dictionary creation (Dictionary banane ka tarika)
person = {
    "name": "John",      # "name" = key, "John" = value
    "age": 25,           # "age" = key, 25 = value
    "city": "New York"   # "city" = key, "New York" = value
}
 
# Dictionary operations (Dictionary ke saath kaam karne ke tarike)
person["email"] = "john@email.com"  # Add new key-value - naya add karna
person["age"] = 26                  # Update existing - existing ko change karna
del person["city"]                  # Delete key - key ko delete karna
 
# Common dictionary methods (Dictionary ke common functions)
print(person.get("name"))           # John - value nikalna
print(person.get("phone", "N/A"))   # N/A - value nahi mili to default dega
print(person.keys())                # dict_keys(['name', 'age', 'email']) - sabhi keys
print(person.values())              # dict_values(['John', 26, 'john@email.com']) - sabhi values
print(person.items())               # dict_items([('name', 'John'), ('age', 26)]) - sabhi pairs

Simple samjho:

  • Dictionary = Key-value pairs (phone book jaisa)
  • Key = Unique identifier (naam, ID, etc.)
  • Value = Data (number, address, etc.)
  • get() = Value nikalna safely
  • keys() = Sabhi keys nikalna
  • values() = Sabhi values nikalna
  • items() = Sabhi pairs nikalna

7. Sets (Sets - Unique Items)

Dost, set matlab unique items ki collection! Duplicate nahi hote, sirf unique items.

# Set creation (unique elements only - duplicate nahi hote)
fruits = {"apple", "banana", "cherry", "apple"}  # Duplicate removed automatically
print(fruits)  # {'apple', 'banana', 'cherry'} - duplicate apple remove ho gaya
 
# Set operations (Set ke saath mathematical operations)
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
 
print(set1.union(set2))        # {1, 2, 3, 4, 5, 6} - dono sets ko combine karna
print(set1.intersection(set2)) # {3, 4} - common elements
print(set1.difference(set2))   # {1, 2} - set1 mein jo set2 mein nahi hai
print(set1.symmetric_difference(set2))  # {1, 2, 5, 6} - jo dono mein common nahi hai

Simple samjho:

  • Set = Unique items ki collection (duplicate nahi hote)
  • Curly braces {} = Set banane ke liye
  • Union = Dono sets ko combine karna
  • Intersection = Common elements nikalna
  • Difference = Ek mein jo dusre mein nahi hai
  • Symmetric Difference = Jo dono mein common nahi hai

Type Conversion & Casting (Type Badalna)

Dost, type conversion matlab ek type ko dusre type mein badalna! Jaise string ko number mein convert karna.

# Converting between types (Types ko convert karne ke tarike)
# String to number (String se number banane ka tarika)
age_str = "25"           # Ye string hai
age_int = int(age_str)   # Ab ye integer ban gaya
age_float = float(age_str)  # Ab ye float ban gaya
 
# Number to string (Number se string banane ka tarika)
number = 42
number_str = str(number)  # Ab ye string ban gaya
 
# List to tuple and vice versa (List aur tuple mein convert karna)
my_list = [1, 2, 3]      # List hai
my_tuple = tuple(my_list)  # Ab tuple ban gaya
my_list_again = list(my_tuple)  # Wapas list ban gaya
 
# String to list (String ko list mein convert karna)
sentence = "hello world"
words = sentence.split()  # ['hello', 'world'] - words ko alag kar diya
chars = list(sentence)    # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] - har character alag
 
# List to string (List ko string mein convert karna)
words = ['hello', 'world']
sentence = ' '.join(words)  # 'hello world' - words ko join kar diya

Simple samjho:

  • int() = String ko integer mein convert karna
  • float() = String ko float mein convert karna
  • str() = Kisi bhi cheez ko string mein convert karna
  • tuple() = List ko tuple mein convert karna
  • list() = Tuple ko list mein convert karna
  • split() = String ko words mein break karna
  • join() = Words ko string mein join karna

Input/Output Operations (User se Input Lena aur Output Dena)

Dost, input/output matlab user se data lena aur user ko data dena! Jaise form fill karna.

# Basic input/output (Basic input aur output)
name = input("Enter your name: ")    # User se naam lena
age = int(input("Enter your age: ")) # User se age lena (int mein convert karna)
 
print(f"Hello {name}, you are {age} years old")  # Output dena
 
# Multiple values in one line (Ek line mein multiple values lena)
values = input("Enter two numbers: ").split()  # Split karke list banaya
num1, num2 = int(values[0]), int(values[1])    # Dono numbers ko alag variables mein dala
 
# Formatted output (Formatted output - different tarike)
name = "John"
age = 25
print("Name: {}, Age: {}".format(name, age))  # Old style - format() use kiya
print(f"Name: {name}, Age: {age}")            # f-string (preferred) - f use kiya
print("Name: %s, Age: %d" % (name, age))      # % formatting - % use kiya

Simple samjho:

  • input() = User se data lena
  • print() = Data display karna
  • f-string = Modern way to format strings (f”text {variable}”)
  • format() = Old way to format strings
  • % formatting = Oldest way to format strings
  • split() = String ko parts mein break karna

Operators

Arithmetic Operators

a, b = 10, 3
 
print(a + b)   # 13 (addition)
print(a - b)   # 7 (subtraction)
print(a * b)   # 30 (multiplication)
print(a / b)   # 3.333... (division)
print(a // b)  # 3 (floor division)
print(a % b)   # 1 (modulo)
print(a ** b)  # 1000 (exponentiation)

Comparison Operators

x, y = 5, 10
 
print(x == y)  # False (equal)
print(x != y)  # True (not equal)
print(x < y)   # True (less than)
print(x > y)   # False (greater than)
print(x <= y)  # True (less than or equal)
print(x >= y)  # False (greater than or equal)

Logical Operators

a, b = True, False
 
print(a and b)  # False
print(a or b)   # True
print(not a)    # False
 
# Short-circuit evaluation
def expensive_function():
    print("This won't be called")
    return True
 
result = False and expensive_function()  # expensive_function() not called

Assignment Operators

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 %= 2   # x = x % 2 = 1.0

Identity and Membership Operators

# Identity operators (is, is not)
a = [1, 2, 3]
b = [1, 2, 3]
c = a
 
print(a is b)     # False (different objects)
print(a is c)     # True (same object)
print(a == b)     # True (same values)
 
# Membership operators (in, not in)
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)      # True
print("orange" not in fruits) # True

Control Flow

If/Else Statements

# Basic if-else
age = 18
if age >= 18:
    print("Adult")
else:
    print("Minor")
 
# if-elif-else
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
 
# Nested conditions
temperature = 25
is_sunny = True
 
if temperature > 20:
    if is_sunny:
        print("Great weather for a walk!")
    else:
        print("Warm but cloudy")
else:
    print("Too cold")
 
# Ternary operator (conditional expression)
age = 20
status = "Adult" if age >= 18 else "Minor"

For Loops

# Basic for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
 
# Loop with index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
 
# Range function
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)
 
for i in range(1, 6):     # 1, 2, 3, 4, 5
    print(i)
 
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
    print(i)
 
# Loop through dictionary
person = {"name": "John", "age": 25, "city": "NYC"}
for key, value in person.items():
    print(f"{key}: {value}")
 
# Nested loops
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()  # New line after each row

While Loops

# Basic while loop
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1
 
# While with break and continue
count = 0
while count < 10:
    count += 1
    if count == 3:
        continue  # Skip rest of loop, go to next iteration
    if count == 7:
        break     # Exit loop completely
    print(count)
 
# While with else (executes when loop completes normally)
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print("Loop completed normally")

Loop Control Statements

# break - exit loop completely
for i in range(10):
    if i == 5:
        break
    print(i)  # Prints 0, 1, 2, 3, 4
 
# continue - skip current iteration
for i in range(5):
    if i == 2:
        continue
    print(i)  # Prints 0, 1, 3, 4
 
# pass - do nothing (placeholder)
for i in range(5):
    if i == 2:
        pass  # Do nothing
    print(i)  # Prints 0, 1, 2, 3, 4

Functions

Basic Function Definition

def greet(name):
    """Function to greet a person"""
    return f"Hello, {name}!"
 
# Function call
message = greet("John")
print(message)  # Hello, John!

Function Parameters

# Default parameters
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"
 
print(greet("John"))                    # Hello, John!
print(greet("John", "Hi"))             # Hi, John!
 
# Keyword arguments
def create_profile(name, age, city="Unknown"):
    return f"Name: {name}, Age: {age}, City: {city}"
 
print(create_profile(age=25, name="John"))  # Name: John, Age: 25, City: Unknown
print(create_profile("Jane", city="NYC", age=30))  # Name: Jane, Age: 30, City: NYC

*args and **kwargs (Very Important for Interviews!)

# *args - variable number of positional arguments
def sum_all(*args):
    """Sum all arguments passed"""
    total = 0
    for num in args:
        total += num
    return total
 
print(sum_all(1, 2, 3))        # 6
print(sum_all(1, 2, 3, 4, 5))  # 15
 
# **kwargs - variable number of keyword arguments
def print_info(**kwargs):
    """Print all keyword arguments"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")
 
print_info(name="John", age=25, city="NYC")
# name: John
# age: 25
# city: NYC
 
# Combining *args and **kwargs
def flexible_function(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)
 
flexible_function(1, 2, 3, name="John", age=25)
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'John', 'age': 25}

Lambda Functions (nameless function)

# Basic lambda
square = lambda x: x ** 2
print(square(5))  # 25
 
# Lambda with multiple parameters
add = lambda x, y: x + y
print(add(3, 4))  # 7
 
# Lambda in higher-order functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]
 
# Filter with lambda
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4]

Function Scope and Global Variables

# Global vs Local scope
global_var = "I'm global"
 
def my_function():
    local_var = "I'm local"
    print(global_var)  # Can access global
    print(local_var)   # Can access local
 
# Modifying global variables
counter = 0
 
def increment():
    global counter
    counter += 1
 
increment()
print(counter)  # 1

Common Interview Questions

1. What are the different data types in Python?

Answer: Python has several built-in data types:

  • Numbers: int, float, complex
  • Sequences: str, list, tuple
  • Mappings: dict
  • Sets: set, frozenset
  • Boolean: bool
  • Binary: bytes, bytearray

2. What’s the difference between a list and a tuple?

Answer:

  • Lists are mutable (can be modified after creation)
  • Tuples are immutable (cannot be modified after creation)
  • Lists use square brackets [], tuples use parentheses ()
  • Lists have more methods (append, remove, etc.)
  • Tuples are faster and use less memory

3. What’s the difference between == and is?

Answer:

  • == compares values
  • is compares object identity (memory location)
a = [1, 2, 3]
b = [1, 2, 3]
c = a
 
print(a == b)  # True (same values)
print(a is b)  # False (different objects)
print(a is c)  # True (same object)

4. What are *args and **kwargs?

Answer:

  • *args allows a function to accept any number of positional arguments
  • **kwargs allows a function to accept any number of keyword arguments
  • Both are commonly used for function decorators and flexible APIs

5. What’s the difference between append() and extend()?

Answer:

  • append() adds a single element to the end of the list
  • extend() adds all elements from an iterable to the end of the list
list1 = [1, 2, 3]
list2 = [1, 2, 3]
 
list1.append([4, 5])    # [1, 2, 3, [4, 5]]
list2.extend([4, 5])    # [1, 2, 3, 4, 5]

Practice Problems

Easy Level

  1. Factorial Function
def factorial(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)
 
# Test
print(factorial(5))  # 120
  1. Fibonacci Sequence
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)
 
# Test
for i in range(10):
    print(fibonacci(i), end=" ")  # 0 1 1 2 3 5 8 13 21 34
  1. Check Prime Number
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True
 
# Test
print(is_prime(17))  # True
print(is_prime(15))  # False
  1. Reverse a String
def reverse_string(s):
    return s[::-1]
 
# Test
print(reverse_string("hello"))  # olleh
  1. Count Vowels
def count_vowels(s):
    vowels = "aeiouAEIOU"
    count = 0
    for char in s:
        if char in vowels:
            count += 1
    return count
 
# Test
print(count_vowels("Hello World"))  # 3

Medium Level

  1. Find Maximum in List
def find_max(numbers):
    if not numbers:
        return None
    max_num = numbers[0]
    for num in numbers[1:]:
        if num > max_num:
            max_num = num
    return max_num
 
# Test
print(find_max([3, 7, 2, 9, 1]))  # 9
  1. Remove Duplicates from List
def remove_duplicates(lst):
    return list(set(lst))
 
# Test
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))  # [1, 2, 3, 4, 5]
  1. Check Anagram
def is_anagram(s1, s2):
    return sorted(s1.lower()) == sorted(s2.lower())
 
# Test
print(is_anagram("listen", "silent"))  # True
print(is_anagram("hello", "world"))    # False

Key Takeaways for Interviews

  1. Always explain your thought process - Interviewers want to see how you think
  2. Consider edge cases - Empty lists, None values, single elements
  3. Optimize when possible - But don’t over-optimize initially
  4. Use Pythonic code - Leverage built-in functions and idioms
  5. Test your code - Walk through examples mentally or with test cases

Next Steps

After mastering these core concepts, move on to:

  • Chapter 2: Data Structures & Built-ins (Lists, Tuples, Sets, Dictionaries in detail)
  • Chapter 3: Intermediate Python (List comprehensions, Lambda functions, File handling)
  • Chapter 4: Object-Oriented Programming
  • Chapter 5: Important Libraries
  • Chapter 6: Problem-Solving (DSA)

Remember: Practice is key! Try to implement these concepts from scratch without looking at the solutions.