Strings And Numbers β Complete Deep Dive
Strings & Numbers β Complete Deep Dive π€π’
Strings ka har method β creation, search, modify, split, join, check, escape characters. Numbers ka deep dive β math module, random module, precision handling. Real-world examples ke saath complete handbook. Data Insights par.
π Is Part Mein Kya Sikhenge:
- Strings: Creation, Quotes, Concatenation, len()
- String Methods: Case, Search, Modify, Split, Join, Check
- Escape Characters: \n, \t, \\, raw strings
- String Membership: in, not in operators
- Numbers: Built-in functions, Math module, Random module
- Precision: Float issues, rounding, formatting
1. String Creation & Quotes
π Definition: Strings in Python can be created using single quotes ('text'), double quotes ("text"), or triple quotes ('''text''' / """text"""). Single and double quotes are interchangeable β use one when the string contains the other. Triple quotes are used for multi-line strings and docstrings.
π― Samjho Hinglish Mein: Python mein string banane ke 3 tarike hain. 'Hello' aur "Hello" β dono same hain, koi farak nahi. Kab kya use karo? Agar string mein apostrophe hai β "It's good" (double quotes use karo). Agar string mein double quotes hain β 'He said "Hi"' (single quotes use karo). Multi-line text ke liye β triple quotes use karo.
π» Examples:
# Example 1: Single vs Double Quotes name1 = 'Jatin' name2 = "Jatin" print(name1 == name2) # True β exactly same!
# When to use which?
msg1 = "It's a beautiful day" # Apostrophe inside β use double
msg2 = 'He said "Hello World"' # Double quote inside β use single
print(msg1)
print(msg2)
Output: True It's a beautiful day He said "Hello World"# Example 2: Triple Quotes β Multi-line strings address = """Jatin Kumar Data Analyst Gurugram, Haryana India""" print(address)Output: Jatin Kumar Data Analyst Gurugram, Haryana India# Example 3: Empty string & String from number empty = "" # Empty string (length 0) num_str = str(42) # Number β String: "42" space_str = " " # Space string (length 3, not empty!) print(len(empty)) # 0 print(len(space_str)) # 3 print(bool(empty)) # False (empty = Falsy) print(bool(space_str)) # True (has characters β spaces count!)π¬ Interview Q&A:
Q: Single aur double quotes mein koi difference hai Python mein?
Ans: Functionally koi difference nahi hai β 'Hello' aur "Hello" exactly same hain. Convention: agar string mein apostrophe hai toh double quotes use karo ("It's"), agar double quotes hain toh single use karo ('He said "Hi"'). PEP 8 (Python style guide) mein koi strict rule nahi β consistency maintain karo project mein.
2. String Concatenation & Repetition
π Definition: Concatenation joins two or more strings together using the + operator. Repetition repeats a string multiple times using the * operator. Both create NEW strings (original unchanged β strings are immutable).
π― Samjho Hinglish Mein: + se strings jodh sakte ho β "Hello" + " " + "World" = "Hello World". * se repeat karo β "Ha" * 3 = "HaHaHa". Important: string + number DIRECTLY nahi ho sakta! "Age: " + 25 β ERROR. Pehle str(25) karo ya f-string use karo.
π» Examples:
# Example 1: Concatenation with + first = "Jatin" last = "Kumar" full_name = first + " " + last print(full_name) # Jatin Kumar
# String + Number β ERROR!
# print("Age: " + 25) β TypeError!
print("Age: " + str(25)) # Fix: convert to str first
print(f"Age: {25}") # Better: use f-string!
# Example 2: Repetition with * print("Ha" * 3) # HaHaHa print("β" * 30) # βββββββββββββββββββββββββββββ (line separator) print("π₯" * 5) # π₯π₯π₯π₯π₯# Example 3: Practical β formatted output name = "Jatin" print("=" * 30) print(f" Welcome, {name}!") print("=" * 30)Output: ============================== Welcome, Jatin! ==============================result += "text") slow hai β har baar new string banti hai. Bahut saare strings jodne ke liye "".join(list) use karo β bahut faster hai. Yeh Part 2 ke Topic 7 (Split & Join) mein detail mein cover karenge. 3. String Length β len()
π Definition: The len() function returns the total number of characters in a string β including spaces, special characters, and emojis. It works on strings, lists, tuples, dictionaries, and other iterables.
π» Examples:
# Example 1: Basic length print(len("Python")) # 6 print(len("Hello World")) # 11 (space counts!) print(len("")) # 0 (empty string) print(len(" ")) # 3 (spaces are characters!)# Example 2: Practical β Password length check password = "Jatin@123" if len(password) >= 8:
print("β
Password strength: Good") else:
print("β Password too short! Minimum 8 characters.")# Example 3: Last character using len() text = "PYTHON" last_index = len(text) - 1 print(text[last_index]) # N # But easier way: text[-1] β N4. Case Methods β upper(), lower(), title(), capitalize(), swapcase()
π Definition: Case methods change the letter casing of strings. They return a NEW string (original unchanged). upper() converts all to uppercase. lower() converts all to lowercase. title() capitalizes first letter of each word. capitalize() capitalizes only first character. swapcase() swaps upperβlower.
π All Case Methods:
| Method | Purpose | Input | Output |
|---|---|---|---|
| .upper() | All uppercase | "hello world" | "HELLO WORLD" |
| .lower() | All lowercase | "HELLO WORLD" | "hello world" |
| .title() | First letter of each word capital | "hello world" | "Hello World" |
| .capitalize() | Only first character capital | "hello world" | "Hello world" |
| .swapcase() | Swap upperβlower | "Hello World" | "hELLO wORLD" |
π» Examples:
# Example 1: All case methods text = "hello WORLD python" print(text.upper()) # HELLO WORLD PYTHON print(text.lower()) # hello world python print(text.title()) # Hello World Python print(text.capitalize()) # Hello world python print(text.swapcase()) # HELLO world PYTHON# Example 2: Practical β Case-insensitive comparison user_input = "YES" if user_input.lower() == "yes":
print("User agreed!") # "YES", "Yes", "yes", "yEs" β sab work karenge!# Example 3: Data Cleaning β Name standardization names = ["jatin KUMAR", "PRIYA patel", "rahul VERMA"] cleaned = [name.title() for name in names] print(cleaned) # ['Jatin Kumar', 'Priya Patel', 'Rahul Verma'].lower() aur .strip() sabse zyada use hote hain. Inconsistent data (DELHI, delhi, Delhi) ko pehle lowercase mein convert karo β phir comparison karo. Pandas mein: df['city'] = df['city'].str.lower().str.strip(). π¬ Interview Q&A:
Q: title() aur capitalize() mein kya difference hai?
Ans: title() har word ka first letter capitalize karta hai β "hello world" β "Hello World". capitalize() sirf string ka first character capitalize karta hai, baaki sab lowercase β "hello world" β "Hello world". Names ke liye title() use karo, sentences ke liye capitalize().
5. Search Methods β find(), index(), count(), startswith(), endswith()
π Definition: Search methods help find substrings within strings. find() returns the index of first occurrence (-1 if not found). index() same as find but raises ValueError if not found. count() counts occurrences. startswith() / endswith() check beginning/ending.
π Search Methods Comparison:
| Method | Returns | If Not Found |
|---|---|---|
| .find(sub) | Index of first match | -1 (safe) |
| .index(sub) | Index of first match | ValueError (crashes!) |
| .count(sub) | Number of occurrences | 0 |
| .startswith(sub) | True/False | False |
| .endswith(sub) | True/False | False |
π» Examples:
# Example 1: find() vs index() text = "Hello World Python" print(text.find("World")) # 6 (starts at index 6) print(text.find("Java")) # -1 (not found β safe!) print(text.index("World")) # 6 # text.index("Java") # ValueError! β crashes# Example 2: count(), startswith(), endswith() text = "banana" print(text.count("a")) # 3 print(text.count("na")) # 2 email = "jatin@gmail.com" print(email.startswith("jatin")) # True print(email.endswith(".com")) # True print(email.endswith(".org")) # False# Example 3: Practical β Email domain extraction email = "jatin@gmail.com" at_pos = email.find("@") domain = email[at_pos + 1:] print(f"Domain: {domain}") # gmail.comfind() safe hai β not found par -1 return karta hai. index() risky hai β not found par crash hota hai (ValueError). Production code mein hamesha find() use karo ya in operator se pehle check karo. 6. Modify Methods β replace(), strip(), lstrip(), rstrip()
π Definition: replace(old, new) replaces all occurrences of a substring with another. strip() removes leading and trailing whitespace (or specified characters). lstrip() removes from left only, rstrip() from right only. All return NEW strings.
π» Examples:
# Example 1: replace() text = "Hello World World" print(text.replace("World", "Python")) # Hello Python Python (ALL occurrences replaced)
# Replace only first N occurrences
print(text.replace("World", "Python", 1))
# Hello Python World (only first replaced)
# Data Cleaning β remove unwanted characters
phone = "+91-9876-543-210"
clean_phone = phone.replace("-", "").replace("+", "")
print(clean_phone) # 919876543210
# Example 2: strip(), lstrip(), rstrip() text = " Hello World " print(f"'{text}'") # ' Hello World ' print(f"'{text.strip()}'") # 'Hello World' (both sides trimmed) print(f"'{text.lstrip()}'") # 'Hello World ' (left only) print(f"'{text.rstrip()}'") # ' Hello World' (right only)# Example 3: strip() with specific characters url = "###Hello###" print(url.strip("#")) # Hello price = "βΉβΉβΉ999βΉβΉ" print(price.strip("βΉ")) # 999 # Most common use β clean user input user_input = " jatin@gmail.com " clean_email = user_input.strip().lower() print(clean_email) # jatin@gmail.comstrip() data cleaning ka bread & butter hai. CSV files mein columns ke values mein leading/trailing spaces bahut common hain β "Delhi " aur "Delhi" alag treat hote hain! Pandas mein: df['city'] = df['city'].str.strip(). Hamesha strip karo pehle β comparison fail nahi hoga. 7. Split & Join β Most Important String Methods!
π Definition: split(separator) breaks a string into a list of substrings based on the separator. Default separator is whitespace. join(iterable) combines a list of strings into one string with the specified separator. splitlines() splits by line breaks. Split & Join are the most used string methods in data processing.
π― Samjho Hinglish Mein: split() = todna β ek string ko tukdon mein todta hai aur list banata hai. "Jatin Kumar" split karo space se β ["Jatin", "Kumar"]. CSV data "A,B,C" split karo comma se β ["A", "B", "C"]. join() = jodna β list ke elements ko ek string mein jodta hai. ["Jatin", "Kumar"] join karo space se β "Jatin Kumar". Split aur Join ulte kaam karte hain β data parsing mein sabse useful hain.
π» Examples:
# Example 1: split() basics text = "Hello World Python" words = text.split() # Split by whitespace (default) print(words) # ['Hello', 'World', 'Python']
csv_data = "Jatin,25,Gurugram,Analyst"
fields = csv_data.split(",") # Split by comma
print(fields) # ['Jatin', '25', 'Gurugram', 'Analyst']
print(fields[0]) # Jatin
print(fields[2]) # Gurugram
# Split with maxsplit (limit splits)
text = "one-two-three-four"
print(text.split("-", 2)) # ['one', 'two', 'three-four'] (max 2 splits)
# Example 2:
join() β opposite of split words = ["Jatin", "Kumar", "Analytics"] result = " ".
join(words) #
Join with space print(result) # Jatin Kumar Analytics csv_line = ",".
join(words) #
Join with comma print(csv_line) # Jatin,Kumar,Analytics path = "/".
join(["home", "user", "documents"]) print(path) # home/user/documents# Example 3: Real-world β Name parsing full_name = "Jatin Kumar Sharma" parts = full_name.split() first_name = parts[0] # Jatin last_name = parts[-1] # Sharma middle_name = " ".join(parts[1:-1]) # Kumar print(f"First: {first_name}") print(f"Middle: {middle_name}") print(f"Last: {last_name}")result += item) slow hai β O(nΒ²). "".join(list) fast hai β O(n). 10,000 strings join karne mein join() 100x+ faster hai. Hamesha join() prefer karo loops mein. π¬ Interview Q&A:
Q: split() aur join() mein kya relationship hai?
Ans: Split aur Join inverse operations hain β ek doosre ko undo karte hain. "A,B,C".split(",") β ["A","B","C"]. ",".join(["A","B","C"]) β "A,B,C". Split string β list. Join list β string. Data parsing mein split se todho, process karo, join se wapas banao.
Q: Sentence ke words reverse kaise karo? (Interview classic)
Ans: " ".join("Hello World Python".split()[::-1]) β "Python World Hello". Step 1: split() β ["Hello", "World", "Python"]. Step 2: [::-1] β ["Python", "World", "Hello"]. Step 3: join() β "Python World Hello". One-liner!
8. Check Methods β isdigit(), isalpha(), isalnum(), isspace()
π Definition: Check methods return True/False based on the string content. They are used for input validation β checking if string contains only digits, only letters, only alphanumeric characters, etc.
π All Check Methods:
| Method | True When | "Jatin123" | "12345" | "Hello" |
|---|---|---|---|---|
| .isdigit() | All characters are digits | False | True | False |
| .isalpha() | All characters are letters | False | False | True |
| .isalnum() | All letters or digits | True | True | True |
| .isspace() | All whitespace characters | False | False | False |
| .isupper() | All uppercase | False | False | False |
| .islower() | All lowercase | False | False | False |
π» Examples:
# Example 1: Input validation age_input = "25" if age_input.isdigit(): age = int(age_input) print(f"Valid age: {age}") else:
print("Invalid! Enter numbers only.")# Example 2: Username validation username = "Jatin_123" if username.isalnum():
print("β
Valid username") else:
print("β Only letters and numbers allowed") # β β underscore is not alphanumeric!# Example 3: Password strength checker password = "Jatin@2026" has_upper = any(c.isupper() for c in password) has_lower = any(c.islower() for c in password) has_digit = any(c.isdigit() for c in password) long_enough = len(password) >= 8 if has_upper and has_lower and has_digit and long_enough:
print("β
Strong password!") else:
print("β Weak β need upper, lower, digit, 8+ chars")9. Escape Characters β \n, \t, \\, Raw Strings
π Definition: Escape characters are special characters starting with backslash \ that represent actions like newline, tab, or allow special characters inside strings. Raw strings (r"text") treat backslash as a literal character β no escaping happens.
π Common Escape Characters:
| Escape | Name | Effect |
|---|---|---|
| \n | New Line | Moves to next line |
| \t | Tab | Horizontal tab space |
| \\ | Backslash | Prints literal \ |
| \' | Single Quote | Prints ' inside single-quoted string |
| \" | Double Quote | Prints " inside double-quoted string |
π» Examples:
# Example 1: \n and \t print("Line 1\nLine 2\nLine 3") # Line 1 # Line 2 # Line 3
print("Name\tAge\tCity")
print("Jatin\t25\tGurugram")
# Name Age City
# Jatin 25 Gurugram
# Example 2: Backslash & quotes print("File path: C:\\Users\\Jatin\\Documents") # File path: C:\Users\Jatin\Documents print('He said \'Hello\' to everyone') # He said 'Hello' to everyone# Example 3: Raw strings (r"...") β no escaping # Normal string β \n becomes newline print("Hello\nWorld") # Hello # World # Raw string β \n stays as literal \n print(r"Hello\nWorld") # Hello\nWorld # Raw strings useful for file paths and regex path = r"C:\Users\Jatin\new_folder" print(path) # C:\Users\Jatin\new_folder (no escaping!)π¬ Interview Q&A:
Q: Raw string kya hai aur kab use hota hai?
Ans: Raw string r"text" mein backslash ko escape character nahi maana jaata β literal character treat hota hai. r"C:\new" mein \n newline nahi banega β literal \n rahega. Use cases: (1) Windows file paths (r"C:\Users\folder"), (2) Regular expressions (r"\d{3}-\d{4}"). Bina raw string ke "C:\new" mein \n newline ban jaata hai β galat path!
10. String Membership & Comparison β in, not in
π Definition: The in operator checks if a substring exists within a string β returns True/False. not in checks if a substring does NOT exist. Both are case-sensitive. These are heavily used in conditions, filtering, and validation.
π» Examples:
# Example 1: Basic in / not in text = "Hello World Python" print("World" in text) # True print("Java" in text) # False print("Java" not in text) # True print("world" in text) # False (case sensitive! World β world)# Example 2: Practical β Email validation email = "jatin@gmail.com" if "@" in email and "." in email:
print("β
Valid email format") else:
print("β Invalid email")# Example 3: Case-insensitive check text = "Hello World Python" # Wrong way β case mismatch! print("hello" in text) # False # Right way β convert to lower first print("hello" in text.lower()) # True β
# Bad words filter comment = "This is SPAM content" blocked = ["spam", "scam", "fake"] for word in blocked:
if word in comment.lower():
print(f"π« Blocked word found: {word}") breakin operator find() se zyada readable hai. "Kya Python text mein hai?" β "Python" in text β
better than text.find("Python") != -1 β. Simple checks ke liye hamesha in use karo. Position chahiye tabhi find() use karo. π¬ Interview Q&A:
Q: in operator aur find() mein kya difference hai?
Ans: in operator sirf True/False return karta hai β "exists ya nahi?" find() position (index) return karta hai β "kahan hai?" Agar sirf check karna hai ki substring hai ya nahi β in use karo (readable, fast). Agar position bhi chahiye (substring kahan se start hota hai) β find() use karo.
π String Methods β Complete Cheat Sheet
| Category | Method | Purpose | Example Output |
|---|---|---|---|
| Case | .upper() | All uppercase | "hello" β "HELLO" |
| .lower() | All lowercase | "HELLO" β "hello" | |
| .title() | Each word capitalized | "hello world" β "Hello World" | |
| .capitalize() | First char only | "hello world" β "Hello world" | |
| .swapcase() | Swap upperβlower | "Hello" β "hELLO" | |
| Search | .find(sub) | Find position (-1 if not found) | "hello".find("ll") β 2 |
| .index(sub) | Find position (error if not found) | "hello".index("ll") β 2 | |
| .count(sub) | Count occurrences | "banana".count("a") β 3 | |
| .startswith() | Starts with? | "hello".startswith("he") β True | |
| .endswith() | Ends with? | "file.csv".endswith(".csv") β True | |
| Modify | .replace(old,new) | Replace substring | "hello".replace("l","r") β "herro" |
| .strip() | Remove leading/trailing whitespace | " hi " β "hi" | |
| .lstrip() | Remove left whitespace | " hi " β "hi " | |
| .rstrip() | Remove right whitespace | " hi " β " hi" | |
| Split/Join | .split(sep) | String β List | "a,b,c".split(",") β ["a","b","c"] |
| sep.join(list) | List β String | ",".join(["a","b"]) β "a,b" | |
| Check | .isdigit() | All digits? | "123".isdigit() β True |
| .isalpha() | All letters? | "Hello".isalpha() β True | |
| .isalnum() | Letters or digits? | "Hi123".isalnum() β True | |
| .isspace() | All whitespace? | " ".isspace() β True |
11. Number Types Deep β int, float, complex
π Definition: Python has three numeric types: int (whole numbers with unlimited size), float (decimal numbers using 64-bit double precision), and complex (numbers with real + imaginary parts). Python automatically handles type promotion β when int and float are mixed, result is float. Integers in Python have no size limit β they can be as large as your memory allows.
π― Samjho Hinglish Mein: int = poore numbers (10, -5, 0). Python mein int ki koi limit nahi β 2**1000 bhi calculate ho jaayega! float = decimal wale numbers (3.14, -0.5). Float mein precision issue hota hai (0.1 + 0.2 β 0.3 exactly). complex = imaginary numbers (3+4j) β engineering/science mein use hote hain, data analysis mein rarely. Important: 10/3 = 3.333 (float), 10//3 = 3 (int). Division (/) hamesha float return karta hai!
π Number Types Comparison:
| Type | Stores | Size Limit | Examples | Precision |
|---|---|---|---|---|
| int | Whole numbers | Unlimited! | 10, -5, 0, 2**1000 | Exact |
| float | Decimal numbers | Β±1.8 Γ 10Β³β°βΈ | 3.14, -0.5, 1e10 | ~15-17 digits |
| complex | Real + Imaginary | Same as float | 3+4j, 2-1j | ~15-17 digits |
π» Examples:
# Example 1: int β unlimited size small = 42 big = 2 ** 100 print(big) # 1267650600228229401496703205376 # Python handles this natively β no overflow error!
# Underscores for readability (Python 3.6+)
population = 1_40_00_00_000 # 1.4 billion β same as 14000000000
salary = 50_000 # 50000 β easier to read
print(population) # 14000000000
# Example 2: float β scientific notation normal = 3.14 scientific = 1.5e6 # 1.5 Γ 10βΆ = 1500000.0 tiny = 2.5e-4 # 2.5 Γ 10β»β΄ = 0.00025 print(scientific) # 1500000.0 print(tiny) # 0.00025 # Type promotion: int + float = float print(10 + 3.5) # 13.5 (float) print(type(10 + 3.5)) # <class 'float'> print(10 / 2) # 5.0 (/ always gives float!)# Example 3: Number base conversions decimal = 255 print(bin(decimal)) # 0b11111111 (binary) print(oct(decimal)) # 0o377 (octal) print(hex(decimal)) # 0xff (hexadecimal) # Create from other bases print(0b1010) # 10 (binary β decimal) print(0xFF) # 255 (hex β decimal)π¬ Interview Q&A:
Q: Python mein integer ka maximum size kya hai?
Ans: Python mein integer ka koi maximum size nahi hai β unlimited precision hai! C/Java mein int 32-bit (max ~2 billion) ya 64-bit limit hota hai β overflow error aata hai. Python mein 2**10000 bhi calculate ho jaayega β Python internally arbitrary precision arithmetic use karta hai. Yeh Python ka unique feature hai. Memory jitni hai utna bada number ban sakta hai.
Q: 10/2 ka result 5 hai ya 5.0?
Ans: 10/2 = 5.0 (float!) β Python mein / operator HAMESHA float return karta hai, chahe result exactly divisible ho. Integer result chahiye toh // use karo: 10//2 = 5 (int). Yeh Python 3 ka behavior hai β Python 2 mein / integer division karta tha.
12. Built-in Number Functions β abs(), round(), min(), max(), pow(), sum()
π Definition: Python provides several built-in functions for numeric operations without importing any module. abs() returns absolute value, round() rounds to specified decimals, min()/max() return smallest/largest, pow() calculates power, sum() adds all items in an iterable.
π Built-in Number Functions:
| Function | Purpose | Example | Result |
|---|---|---|---|
| abs(x) | Absolute value (remove negative) | abs(-42) | 42 |
| round(x, n) | Round to n decimal places | round(3.14159, 2) | 3.14 |
| min(a, b, ...) | Smallest value | min(10, 5, 8) | 5 |
| max(a, b, ...) | Largest value | max(10, 5, 8) | 10 |
| pow(x, y) | x raised to power y | pow(2, 10) | 1024 |
| sum(iterable) | Sum of all items in list/tuple | sum([10, 20, 30]) | 60 |
| divmod(x, y) | Returns (quotient, remainder) | divmod(17, 5) | (3, 2) |
π» Examples:
# Example 1: abs() and round() print(abs(-42)) # 42 print(abs(42)) # 42 print(abs(-3.14)) # 3.14
print(round(3.14159)) # 3 (default: 0 decimals)
print(round(3.14159, 2)) # 3.14
print(round(3.14159, 4)) # 3.1416
# β οΈ Banker's Rounding β 0.5 rounds to nearest EVEN!
print(round(0.5)) # 0 (not 1!)
print(round(1.5)) # 2
print(round(2.5)) # 2 (not 3!)
print(round(3.5)) # 4
# Example 2: min(), max(), sum() numbers = [45, 12, 78, 33, 90, 5] print(min(numbers)) # 5 print(max(numbers)) # 90 print(sum(numbers)) # 263 # Average calculation avg = sum(numbers) / len(numbers) print(f"Average: {avg:.2f}") # Average: 43.83 # min/max with multiple arguments (no list needed) print(min(10, 5, 8)) # 5 print(max(10, 5, 8)) # 10# Example 3: pow() and divmod() print(pow(2, 10)) # 1024 (same as 2 ** 10) print(pow(25, 0.5)) # 5.0 (square root) print(pow(2, 10, 1000)) # 24 (2ΒΉβ° % 1000 β modular power) # divmod β quotient and remainder together quotient, remainder = divmod(17, 5) print(f"17 Γ· 5 = {quotient} remainder {remainder}") # 17 Γ· 5 = 3 remainder 2 # Practical: Convert seconds to min:sec total_seconds = 185 mins, secs = divmod(total_seconds, 60) print(f"Duration: {mins}:{secs:02d}") # Duration: 3:05round() "Banker's Rounding" use karta hai β exactly 0.5 par nearest EVEN number ki taraf round karta hai. round(0.5) = 0, round(1.5) = 2, round(2.5) = 2. Yeh mathematically "Round Half to Even" strategy hai β financial calculations mein bias reduce karta hai. Agar traditional rounding chahiye (0.5 hamesha upar) toh math.floor(x + 0.5) use karo. π¬ Interview Q&A:
Q: round(2.5) ka result kya hoga β 2 ya 3?
Ans: round(2.5) = 2 (not 3!). Python Banker's Rounding use karta hai β exactly 0.5 par nearest EVEN number ki taraf jaata hai. round(0.5)=0, round(1.5)=2, round(2.5)=2, round(3.5)=4. Yeh IEEE 754 standard follow karta hai. Interview mein yeh trick question bahut aata hai!
Q: pow(2, 10, 1000) mein teesra argument kya karta hai?
Ans: Teesra argument modulus hai β pow(base, exp, mod) = (base ** exp) % mod. pow(2, 10, 1000) = (1024) % 1000 = 24. Lekin internally yeh bahut optimized hai β pehle poora calculate nahi karta phir mod β step-by-step modular exponentiation karta hai. Cryptography aur competitive programming mein use hota hai.
13. Math Module β Advanced Mathematical Functions
π Definition: The math module provides advanced mathematical functions and constants that go beyond basic arithmetic. It must be imported before use with import math. It includes functions for rounding (ceil, floor), roots, logarithms, trigonometry, and mathematical constants (pi, e).
π― Samjho Hinglish Mein: Built-in functions (abs, round, min, max) basic kaam karte hain β lekin square root, log, ceiling, floor jaise advanced calculations ke liye math module chahiye. import math likho program ke top mein β phir math.sqrt(25), math.ceil(3.1), math.pi sab use kar sakte ho. Data analysis mein math.log aur math.ceil/floor bahut use hote hain.
π Most Used math Functions:
| Function | Purpose | Example | Result |
|---|---|---|---|
| math.ceil(x) | Round UP to nearest integer | math.ceil(3.1) | 4 |
| math.floor(x) | Round DOWN to nearest integer | math.floor(3.9) | 3 |
| math.sqrt(x) | Square root | math.sqrt(144) | 12.0 |
| math.log(x) | Natural log (base e) | math.log(100) | 4.605 |
| math.log10(x) | Log base 10 | math.log10(1000) | 3.0 |
| math.pi | Constant Ο | math.pi | 3.14159... |
| math.e | Constant e (Euler's) | math.e | 2.71828... |
| math.factorial(n) | n! (factorial) | math.factorial(5) | 120 |
| math.gcd(a, b) | Greatest Common Divisor | math.gcd(12, 8) | 4 |
π» Examples:
import math
# Example 1: ceil() vs floor() vs round()
x = 3.3
print(math.ceil(x)) # 4 (always UP)
print(math.floor(x)) # 3 (always DOWN)
print(round(x)) # 3 (nearest β standard rounding)
x = 3.7
print(math.ceil(x)) # 4
print(math.floor(x)) # 3
print(round(x)) # 4
# Practical: Pages needed for items
total_items = 97
items_per_page = 10
pages = math.ceil(total_items / items_per_page)
print(f"Pages needed: {pages}") # 10 (not 9!)
# Example 2: sqrt(), log(), pi print(math.sqrt(144)) # 12.0 print(math.sqrt(2)) # 1.4142... # Area of circle radius = 7 area = math.pi * radius ** 2 print(f"Circle area: {area:.2f}") # 153.94 # Logarithm print(math.log(100)) # 4.605 (natural log, base e) print(math.log10(100)) # 2.0 (log base 10) print(math.log2(1024)) # 10.0 (log base 2)# Example 3: factorial() and gcd() print(math.factorial(5)) # 120 (5! = 5Γ4Γ3Γ2Γ1) print(math.factorial(10)) # 3628800 print(math.gcd(12, 8)) # 4 (Greatest Common Divisor) print(math.gcd(100, 75)) # 25 # Infinity print(math.inf) # inf print(math.inf > 99999999) # True (infinity is always largest)π¬ Interview Q&A:
Q: math.ceil() aur math.floor() mein kya difference hai?
Ans: ceil() hamesha UPAR round karta hai β ceil(3.1) = 4, ceil(3.9) = 4. floor() hamesha NEECHE round karta hai β floor(3.1) = 3, floor(3.9) = 3. Negative numbers mein: ceil(-3.1) = -3 (towards 0), floor(-3.1) = -4 (towards negative infinity). Practical use: pagination mein ceil (97 items, 10 per page = ceil(9.7) = 10 pages).
14. Random Module β Random Number Generation
π Definition: The random module generates pseudo-random numbers for various purposes β random selection, shuffling, sampling, simulations. It must be imported with import random. Key functions: random(), randint(), choice(), shuffle(), sample(), uniform().
π Random Module Functions:
| Function | Returns | Example |
|---|---|---|
| random() | Float between 0.0 and 1.0 | 0.7234... |
| randint(a, b) | Random int from a to b (inclusive) | randint(1, 100) β 42 |
| uniform(a, b) | Random float from a to b | uniform(1.0, 10.0) β 5.678 |
| choice(seq) | Random item from list/string | choice(["a","b","c"]) β "b" |
| shuffle(list) | Shuffles list IN PLACE | [1,2,3] β [3,1,2] |
| sample(seq, k) | k unique random items (no repeat) | sample([1,2,3,4,5], 3) β [4,1,3] |
π» Examples:
import random
# Example 1: Basic random numbers
print(random.random()) # 0.7456... (float 0-1)
print(random.randint(1, 100)) # 42 (random int 1-100)
print(random.uniform(1, 10)) # 5.678... (float 1-10)
# Dice roll
dice = random.randint(1, 6)
print(f"π² Dice: {dice}")
# Example 2: choice(), shuffle(), sample() colors = ["Red", "Blue", "Green", "Yellow", "Purple"] # Random pick print(random.choice(colors)) # Blue (random pick) # Shuffle (modifies original list!) random.shuffle(colors) print(colors) # ['Green', 'Red', 'Purple', 'Yellow', 'Blue'] # Sample (pick k unique items β original unchanged) picked = random.sample(colors, 3) print(picked) # ['Red', 'Purple', 'Green'] (3 random, no repeats)# Example 3: Practical β Password Generator import string # All possible characters chars = string.ascii_letters + string.digits + "!@#$%" # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$% # Generate 12-character random password password = "".join(random.choices(chars, k=12)) print(f"π Generated Password: {password}") # π Generated Password: kR3$mN8pQ!xL # Generate 6-digit OTP otp = random.randint(100000, 999999) print(f"π± Your OTP: {otp}") # π± Your OTP: 482916random module pseudo-random hai β truly random nahi. Reproducible results ke liye random.seed(42) set karo β same seed = same sequence har baar. Data science mein train-test split consistency ke liye seed use hota hai. Security-critical applications (passwords, encryption) ke liye secrets module use karo β woh cryptographically secure hai. π¬ Interview Q&A:
Q: random.choice() aur random.sample() mein kya difference hai?
Ans: choice() ek single random item return karta hai list se. sample(seq, k) k unique random items return karta hai β repeats nahi hote. choice() se same item baar baar aa sakta hai (agar loop mein use karo). sample() guarantee karta hai ki selected items unique hain. Lottery numbers ke liye sample() use karo (no repeats), dice roll ke liye choice() (repeats OK).
15. Number Formatting β Display Numbers Properly
π Definition: Number formatting controls how numbers are displayed β decimal places, comma separators, percentage, currency, padding, scientific notation. Python's f-strings and format() function provide powerful formatting capabilities for professional output in reports and dashboards.
π Number Formatting Cheat Sheet:
| Format | Purpose | Code | Output |
|---|---|---|---|
| :.2f | 2 decimal places | f"{3.14159:.2f}" | 3.14 |
| :, | Comma separator | f"{1234567:,}" | 1,234,567 |
| :,.2f | Comma + 2 decimals | f"{50000.5:,.2f}" | 50,000.50 |
| :.1% | Percentage (auto Γ100) | f"{0.156:.1%}" | 15.6% |
| :.2e | Scientific notation | f"{123456:.2e}" | 1.23e+05 |
| :0>5 | Zero-padded, 5 digits | f"{42:0>5}" | 00042 |
| :+.2f | Show +/- sign always | f"{42:+.2f}" | +42.00 |
π» Examples:
# Example 1: Financial Report Formatting revenue = 5843567.897 growth = 0.1567 loss = -23456.50
print(f"Revenue: βΉ{revenue:,.2f}")
# Revenue: βΉ5,843,567.90
print(f"Growth: {growth:.1%}")
# Growth: 15.7%
print(f"Profit/Loss: {loss:+,.2f}")
# Profit/Loss: -23,456.50
# Example 2: Data Report Table products = [ ("Laptop", 85000, 0.23), ("Mouse", 500, -0.05), ("Monitor", 18000, 0.12) ] print(f"{' Product':12} {'Growth':>10}") print("β" * 40) for name, price, growth in products:
print(f" {name:10,.0f} {growth:>+9.1%}")Output: Product Price Growth ββββββββββββββββββββββββββββββββββββββββ Laptop βΉ 85,000 +23.0% Mouse βΉ 500 -5.0% Monitor βΉ 18,000 +12.0%# Example 3: Indian Lakhs/Crores format (Custom) def indian_format(n):
if n >= 10000000:
return f"βΉ{n/10000000:.2f} Cr" elif n >= 100000:
return f"βΉ{n/100000:.2f} L" elif n >= 1000:
return f"βΉ{n/1000:.1f} K" else:
return f"βΉ{n:.0f}" print(indian_format(58435678)) # βΉ5.84 Cr print(indian_format(850000)) # βΉ8.50 L print(indian_format(50000)) # βΉ50.0 K16. Integer vs Float Precision β The Famous 0.1 + 0.2 Problem
π Definition: Floating-point numbers are stored in binary (base-2) representation using IEEE 754 standard. Some decimal fractions (like 0.1) cannot be represented exactly in binary β causing tiny precision errors. This is NOT a Python bug β it happens in ALL programming languages that use floating-point arithmetic. Solutions include round(), decimal module, and comparison with tolerance.
π― Samjho Hinglish Mein: Computer binary mein kaam karta hai (0 aur 1). Decimal 0.1 ko binary mein exactly represent nahi kar sakta β jaise 1/3 ko decimal mein exactly nahi likh sakte (0.333...), waise hi 0.1 ko binary mein exactly nahi likh sakte. Isliye 0.1 + 0.2 = 0.30000000000000004 β exactly 0.3 nahi! Yeh bahut famous problem hai aur interview mein puchha jaata hai.
π» Examples:
# Example 1: The Problem β 0.1 + 0.2 print(0.1 + 0.2) # 0.30000000000000004 β NOT exactly 0.3!
print(0.1 + 0.2 == 0.3)
# False! β This is NOT a bug
print(0.1 + 0.1 + 0.1 - 0.3)
# 5.551115123125783e-17 β tiny error, not zero!
# More examples:
print(1.1 + 2.2) # 3.3000000000000003
print(0.7 + 0.1) # 0.7999999999999999
# Example 2: Solutions # Solution 1: round() β simplest print(round(0.1 + 0.2, 1)) # 0.3 β
print(round(0.1 + 0.2, 10) == 0.3) # True β
# Solution 2: Compare with tolerance (epsilon) a = 0.1 + 0.2 b = 0.3 epsilon = 1e-9 # tolerance print(abs(a - b) < epsilon) # True β
# Solution 3: math.isclose() β best for comparisons import math print(math.isclose(0.1 + 0.2, 0.3)) # True β
# Example 3: decimal module β exact arithmetic from decimal import Decimal # float version (imprecise) print(0.1 + 0.2) # 0.30000000000000004 # Decimal version (exact!) β use strings! print(Decimal('0.1') + Decimal('0.2')) # 0.3 β
(exactly!) print(Decimal('0.1') + Decimal('0.2') == Decimal('0.3')) # True β
# β οΈ Decimal(0.1) WITHOUT quotes β still imprecise! print(Decimal(0.1)) # 0.1000000000000000055511151231257827021... (float already converted!) # ALWAYS use string: Decimal('0.1') β
β’ Financial calculations: βΉ0.01 difference matters β use
Decimal moduleβ’ General data analysis:
round() kaafi hai β precision error negligibleβ’ Float comparison:
== directly compare mat karo β math.isclose() ya tolerance use karoβ’ Display: f-string formatting (
:.2f) handles display β internal precision issue dikhta nahi π¬ Interview Q&A:
Q: 0.1 + 0.2 == 0.3 ka result kya hoga Python mein aur kyun?
Ans: Result False hoga! Kyunki 0.1 + 0.2 = 0.30000000000000004 (exactly 0.3 nahi). Yeh floating-point precision issue hai β binary mein 0.1 exactly represent nahi hota. Solutions: (1) round(0.1+0.2, 10) == 0.3 β True. (2) math.isclose(0.1+0.2, 0.3) β True. (3) Decimal('0.1') + Decimal('0.2') == Decimal('0.3') β True. Yeh sirf Python ka issue nahi β JavaScript, Java, C++ sab mein same hai. IEEE 754 standard ki limitation hai.
Q: Decimal module kab use karna chahiye?
Ans: Jab exact decimal arithmetic chahiye β financial calculations (βΉ, $), accounting, billing systems, tax calculations. Wahan 0.01 ka difference bhi matter karta hai. General data analysis (Pandas, NumPy) mein float kaafi hai kyunki precision error negligible hoti hai. Decimal slow hai float se β performance-sensitive code mein avoid karo. Rule: Money = Decimal, Science = float.
Quick Revision β Part 2 Complete Summary
| # | Topic | Key Takeaway |
|---|---|---|
| 1 | String Creation | 'single' == "double", '''triple''' for multi-line |
| 2 | Concatenation | + joins, * repeats, str+int = ERROR |
| 3 | len() | Counts all characters including spaces |
| 4 | Case Methods | upper(), lower(), title(), capitalize(), swapcase() |
| 5 | Search Methods | find()=-1 safe, index()=error, count(), startswith() |
| 6 | Modify Methods | replace(), strip() β data cleaning essentials |
| 7 | Split & Join | split() = strβlist, join() = listβstr, inverse ops |
| 8 | Check Methods | isdigit(), isalpha(), isalnum() β input validation |
| 9 | Escape Characters | \n newline, \t tab, r"..." raw string |
| 10 | String Membership | in / not in β substring check, case sensitive |
| 11 | Number Types | int=unlimited, float=15-17 digits, / always float |
| 12 | Built-in Functions | abs(), round() (Banker's!), min(), max(), sum(), divmod() |
| 13 | Math Module | ceil(), floor(), sqrt(), log(), pi, factorial() |
| 14 | Random Module | randint(), choice(), shuffle(), sample(), seed() |
| 15 | Number Formatting | :.2f, :,, :.1%, :.2e β f-string formatting power |
| 16 | Float Precision | 0.1+0.2β 0.3! Use round(), math.isclose(), Decimal |
Next: Python Handbook β Part 3
Agle part mein hum cover karenge: Data Structures β List, Tuple, Set, Dictionary. Creation, indexing, slicing, methods, nested structures, comprehensions, comparison tables β sab kuch. Yeh Python ka backbone hai β data manipulation isi par based hai. Part 1 (Basics) aur Part 2 (Strings & Numbers) Data Insights par available hain.
Happy Learning & Keep Coding! π
π¬ Comments (0)
Loading comments...