Python Basics โ Complete Foundation Guide
Python Basics โ Complete Foundation Guide ๐
Python programming ki neev โ Variables, Data Types, Operators, Input/Output, Strings. Zero knowledge se start karke fundamentals strong banayenge. Har concept ka Definition, Explanation, Rules, Syntax, Examples aur Interview Q&A. Data Insights par.
๐ Is Part Mein Kya Sikhenge:
- What is Python โ Overview & History
- First Program โ print() Function
- Comments โ Single & Multi-line
- Variables โ Rules & Naming Conventions
- Data Types โ int, float, str, bool
- Type Checking โ type() Function
- Type Casting โ int(), float(), str(), bool()
- Input from User โ input() Function
- Arithmetic Operators
- Comparison Operators
- Logical Operators โ and, or, not
- Assignment Operators
- String Basics โ Indexing & Slicing
- f-Strings โ Modern String Formatting
1. What is Python โ Overview
๐ Definition: Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. It emphasizes code readability and simplicity โ making it one of the easiest languages to learn. Python supports multiple programming paradigms including procedural, object-oriented, and functional programming.
๐ฏ Samjho Hinglish Mein: Python ek programming language hai jo bahut easy hai seekhne mein โ almost English jaisi padhne mein lagti hai. Jahan C++ ya Java mein 10 lines lagti hain, Python mein 3 lines mein kaam ho jaata hai. Data Analysis, Web Development, AI/ML, Automation โ sab mein Python use hota hai. 2026 mein duniya ki sabse popular programming language hai.
๐ Key Properties:
| Property | Meaning |
|---|---|
| High-Level | Human-readable โ machine details se tum door rehte ho |
| Interpreted | Line by line execute hota hai โ compile karne ki zaroorat nahi |
| Dynamically Typed | Variable ka type declare nahi karna padta โ Python khud samajh jaata hai |
| Case Sensitive | name aur Name alag variables hain |
| Indentation Based | Curly braces {} ki jagah spaces/tabs se code structure define hota hai |
๐ฌ Interview Q&A:
Q: Python interpreted language hai โ iska kya matlab hai?
Ans: Python ka code line-by-line execute hota hai at runtime โ pehle se compile nahi hota. Agar line 5 mein error hai toh line 1-4 execute ho jaayengi, line 5 par error aayega. C/Java mein pehle poora code compile hota hai โ ek bhi error toh kuch nahi chalega. Interpreted hone se development fast hota hai lekin execution speed compiled languages se slow hoti hai.
Q: Python dynamically typed kyun kehte hain?
Ans: Python mein variable declare karte waqt data type batana zaroori nahi โ Python runtime par khud detect karta hai. x = 10 likhne par Python samajh jaata hai ki x integer hai. C mein likhna padta int x = 10;. Flexibility milti hai lekin runtime errors ka risk badhta hai.
2. First Program โ print() Function
๐ Definition: The print() function outputs (displays) data to the console/screen. It is the most basic and most used function in Python. It can print strings, numbers, variables, expressions, and multiple values separated by commas.
๐ฏ Samjho Hinglish Mein: print() tumhara speaker hai โ jo bhi tum likhoge woh screen par bol dega. "Hello World" likhna hai? print("Hello World"). Number dikhana hai? print(42). Variable ki value dekhni hai? print(x). Har programmer ka pehla kaam print() se hota hai โ debugging mein bhi sabse zyada use hota hai.
๐ Syntax & Rules:
Syntax: print(value1, value2, ..., sep=' ', end='\n')
Parameters:
โข value โ What to print (string, number, variable, expression)
โข sep โ Separator between multiple values (default: space ' ')
โข end โ What to print at the end (default: newline '\n')
๐ป Examples:
# Example 1: Basic print print("Hello World") print(42) print(3.14) print(True) Output: Hello World 42 3.14 True# Example 2: Multiple values + custom sep/end print("Jatin", "Kumar", "Analytics") print("Jatin", "Kumar", sep="-") print("Hello", end=" ") print("World")Output: Jatin Kumar Analytics Jatin-Kumar Hello World# Example 3: Print expressions & variables x = 10 y = 20 print("Sum =", x + y) print("Product =", x * y)Output: Sum = 30 Product = 200Print("Hello") โ capital P se error aayega! Python case-sensitive hai โ print sahi hai, Print galat. NameError: name 'Print' is not defined aayega. ๐ฌ Interview Q&A:
Q: print() mein sep aur end parameter kya karte hain?
Ans: sep multiple values ke beech ka separator define karta hai (default space). end line ke end mein kya aaye woh define karta hai (default newline \n). print("A", "B", sep="-") โ "A-B". print("Hello", end=" ") โ next print same line par aayega.
3. Comments โ Single & Multi-line
๐ Definition: Comments are notes written in code that are ignored by the Python interpreter. They are used to explain code logic, make code readable, and temporarily disable code lines. Single-line comments start with #. Multi-line comments use triple quotes ''' or """.
๐ฏ Samjho Hinglish Mein: Comments tumhare code mein "sticky notes" hain โ Python inhein completely ignore karta hai, execute nahi karta. Yeh tumhare future self ke liye ya team members ke liye likhte ho โ "yeh code kya kar raha hai?" samjhane ke liye. Good developers hamesha comments likhte hain!
๐ป Examples:
# Example 1: Single-line comment # This calculates total salary salary = 50000 bonus = 5000 total = salary + bonus # Inline comment โ after code print(total) Output: 55000# Example 2: Multi-line comment """ This program calculates employee salary. It takes base salary and bonus as input. Returns the total compensation. Author: Jatin Kumar """ print("Program started")Output: Program started# Example 3: Commenting out code (debugging) x = 10 # print(x * 2) โ This line won't run print(x * 3) # Only this runsOutput: 30๐ฌ Interview Q&A:
Q: Python mein multi-line comment kaise likhte hain?
Ans: Python mein officially multi-line comment nahi hai. Triple quotes (''' ya """) actually multi-line strings hain โ lekin jab kisi variable ko assign nahi karte toh Python ignore kar deta hai โ effective multi-line comment ban jaata hai. Single-line ke liye # use karo โ yeh official comment syntax hai.
4. Variables โ Rules & Naming Conventions
๐ Definition: A variable is a named container that stores a value in memory. In Python, you don't need to declare the data type โ just assign a value using the = operator. Variables can be reassigned to different types at any time (dynamic typing).
๐ฏ Samjho Hinglish Mein: Variable ek dabba (box) hai jisme tum koi bhi value rakh sakte ho. Dabbe ka ek naam hota hai (jaise "salary") aur uske andar value hoti hai (jaise 50000). salary = 50000 matlab "salary naam ke dabbe mein 50000 rakho." Baad mein tum value change kar sakte ho โ salary = 60000 โ purani value replace ho jaayegi.
๐ Variable Naming Rules:
| Rule | โ Valid | โ Invalid |
|---|---|---|
| Start with letter or underscore | name, _age, _count | 1name, 2age |
| Can contain letters, digits, underscore | name1, my_var, total_2 | my-var, total@2 |
| Case sensitive | Name โ name โ NAME | โ |
| No spaces allowed | first_name, firstName | first name |
| Cannot use Python keywords | my_class, is_true | class, True, for, if |
๐ป Examples:
# Example 1: Variable assignment & reassignment name = "Jatin" age = 25 salary = 50000.50 is_active = True
print(name, age, salary, is_active)
# Reassignment (value changes, old value lost)
age = 26
print("Updated age:", age)
Output: Jatin 25 50000.5 True Updated age: 26# Example 2: Multiple assignment a, b, c = 10, 20, 30 print(a, b, c) # Same value to multiple variables x = y = z = 0 print(x, y, z)Output: 10 20 30 0 0 0# Example 3: Swapping variables (Python magic!) a = 10 b = 20 print("Before:", a, b) a, b = b, a # One-line swap! No temp variable needed print("After:", a, b)Output: Before: 10 20 After: 20 10snake_case use karo โ words underscore se separate karo: first_name, total_salary, is_active. camelCase (JavaScript style) avoid karo. Constants ke liye ALL CAPS: MAX_RETRIES = 3. ๐ฌ Interview Q&A:
Q: Python mein variable swap kaise karte hain bina third variable ke?
Ans: a, b = b, a โ ek line mein swap ho jaata hai. Python internally tuple packing/unpacking use karta hai. Pehle right side evaluate hota hai (b, a) = (20, 10) โ yeh ek tuple ban jaata hai. Phir left side ko assign hota hai a, b = (20, 10). Other languages mein temp variable chahiye โ Python mein nahi!
5. Data Types โ int, float, str, bool
๐ Definition: Data Types define what kind of value a variable holds. Python has several built-in data types. The four fundamental types are: int (whole numbers), float (decimal numbers), str (text strings), and bool (True/False). Python automatically assigns the type based on the value โ no explicit declaration needed.
๐ฏ Samjho Hinglish Mein: Data Type batata hai ki variable mein kaunsi category ki value hai. age = 25 โ yeh int hai (poori sankhya). price = 99.99 โ yeh float hai (decimal wali). name = "Jatin" โ yeh str hai (text). is_student = True โ yeh bool hai (haan/naa). Python khud samajh jaata hai โ tumhe "yeh int hai" batane ki zaroorat nahi.
๐ Four Fundamental Data Types:
| Type | Full Name | Stores | Examples |
|---|---|---|---|
| int | Integer | Whole numbers (no decimal) | 10, -5, 0, 99999 |
| float | Floating Point | Decimal numbers | 3.14, -0.5, 99.0 |
| str | String | Text (characters) | "Hello", 'Python', "42" |
| bool | Boolean | True or False only | True, False |
๐ป Examples:
# Example 1: Each data type age = 25 # int salary = 50000.75 # float name = "Jatin Kumar" # str is_active = True # bool
print(type(age)) #
print(type(salary)) #
print(type(name)) #
print(type(is_active)) #
# Example 2: Dynamic typing โ type changes x = 10 # x is int print(type(x)) # <class 'int'> x = "Hello" # x is now str! (same variable) print(type(x)) # <class 'str'> x = 3.14 # x is now float! print(type(x)) # <class 'float'># Example 3: Tricky โ "42" vs 42 a = 42 # int โ number b = "42" # str โ text! (quotes mein hai) print(type(a)) # <class 'int'> print(type(b)) # <class 'str'> print(a + 8) # 50 (math addition) print(b + "8") # "428" (string concatenation!)"42" aur 42 bilkul alag hain! "42" ek string hai โ text. 42 ek integer hai โ number. "42" + "8" = "428" (concatenation). 42 + 8 = 50 (addition). Quotes ka hona/na hona type decide karta hai. Yeh bahut common confusion hai beginners mein! ๐ฌ Interview Q&A:
Q: Python mein int aur float mein kya difference hai?
Ans: int whole numbers store karta hai (10, -5, 0) โ koi decimal nahi. float decimal numbers store karta hai (3.14, -0.5, 99.0). Jab int aur float ko mix karte hain (10 + 3.14) โ result hamesha float aata hai (13.14). Python automatically int ko float mein promote karta hai โ isko "type coercion" kehte hain.
Q: bool True aur False internally kya hain?
Ans: True = 1 aur False = 0 internally. True + True = 2, True + False = 1, False + False = 0. bool actually int ka subclass hai Python mein. Isliye boolean values arithmetic mein directly use ho sakti hain.
6. Type Checking โ type() Function
๐ Definition: The type() function returns the data type of a variable or value. Another function isinstance() checks if a variable is of a specific type and returns True/False. Both are essential for debugging and validation.
๐ป Examples:
# Example 1: type() โ 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([1,2,3])) # <class 'list'># Example 2: isinstance() โ check specific type (True/False) x = 42 print(isinstance(x, int)) # True print(isinstance(x, float)) # False print(isinstance(x, str)) # False # Check multiple types at once print(isinstance(x, (int, float))) # True (either int OR float)# Example 3: Practical use โ conditional check value = "100" if isinstance(value, str):
print("Yeh string hai โ convert karo pehle!") value = int(value) print("Converted:", value, type(value))Output: Yeh string hai โ convert karo pehle! Converted: 100 <class 'int'>7. Type Casting โ int(), float(), str(), bool()
๐ Definition: Type Casting is converting a value from one data type to another. Python provides built-in functions: int() converts to integer, float() converts to float, str() converts to string, bool() converts to boolean. Also called Type Conversion.
๐ฏ Samjho Hinglish Mein: Type Casting = value ka type change karna. input() se value aayi "25" โ yeh string hai. Calculation karne ke liye int chahiye โ int("25") se convert karo = 25 (integer). float ko int mein convert karo โ decimal kat jaayega (3.14 โ 3). Har conversion possible nahi hai โ int("hello") error dega!
๐ Conversion Rules:
| Conversion | Example | Result | Note |
|---|---|---|---|
| str โ int | int("42") | 42 | String must contain only digits |
| str โ float | float("3.14") | 3.14 | Can have decimal point |
| float โ int | int(3.99) | 3 | Truncates decimal (no rounding!) |
| int โ str | str(42) | "42" | Number becomes text |
| int โ bool | bool(0), bool(1) | False, True | 0 = False, anything else = True |
| str โ bool | bool(""), bool("hi") | False, True | Empty string = False, non-empty = True |
๐ป Examples:
# Example 1: String to Number conversion age_str = "25" age_int = int(age_str) print(age_int + 5) # 30 (now math works!)
price_str = "99.99"
price_float = float(price_str)
print(price_float * 2) # 199.98
# Example 2: float โ int (TRUNCATES, not rounds!) print(int(3.14)) # 3 (decimal cut) print(int(3.99)) # 3 (NOT 4! โ no rounding) print(int(-2.7)) # -2 (towards zero) # For rounding, use round() print(round(3.99)) # 4 (proper rounding)# Example 3: Boolean truthy/falsy values print(bool(0)) # False print(bool(42)) # True (any non-zero = True) print(bool("")) # False (empty string) print(bool("Hello")) # True (non-empty string) print(bool([])) # False (empty list) print(bool([1,2])) # True (non-empty list) print(bool(None)) # Falseint("3.14") โ ERROR! Direct string-to-int conversion sirf pure digits ke liye kaam karti hai. Decimal wali string pehle float mein convert karo, phir int: int(float("3.14")) โ 3. int("hello") โ ValueError! ๐ฌ Interview Q&A:
Q: int(3.99) ka result 3 hai ya 4? Kyun?
Ans: Result 3 hai โ kyunki int() truncate karta hai (decimal simply kat jaata hai), round nahi karta. 3.99 โ 3, 3.1 โ 3, -2.7 โ -2. Rounding ke liye round() function use karo: round(3.99) = 4, round(3.5) = 4. Yeh bahut common interview trick question hai!
Q: Python mein kaunsi values False consider hoti hain (Falsy)?
Ans: Yeh sab Falsy hain: 0 (zero), 0.0, "" (empty string), [] (empty list), () (empty tuple), {} (empty dict), None, False. Baaki sab Truthy hain โ non-zero numbers, non-empty strings/containers. bool(value) se check kar sakte ho.
8. Input from User โ input() Function
๐ Definition: The input() function pauses the program and waits for the user to type something. Whatever the user types is returned as a string โ even if they type a number. You must convert it using int() or float() if you need numeric operations.
๐ฏ Samjho Hinglish Mein: input() user se value maangta hai. Program ruk jaata hai, user type karta hai, Enter press karta hai โ phir program aage chalta hai. Important: input() HAMESHA string return karta hai! Agar user "25" type kare โ woh string "25" hai, int 25 nahi. Math ke liye int() mein wrap karo: age = int(input("Age: ")).
๐ป Examples:
# Example 1: Basic input name = input("Enter your name: ") print("Hello,", name, "!") Enter your name: Jatin Hello, Jatin !# Example 2: input() always returns STRING! age = input("Enter age: ") print(type(age)) # <class 'str'> โ Even if user typed 25! # Fix: Convert to int age = int(input("Enter age: ")) print(type(age)) # <class 'int'> โ Now it's number print("Age after 5 years:", age + 5)# Example 3: Simple calculator num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) print("Sum:", num1 + num2) print("Difference:", num1 - num2) print("Product:", num1 * num2)age = input("Age: ") phir age + 5 likhna โ TypeError aayega! Kyunki age string hai aur 5 integer. String + int nahi ho sakta. Fix: age = int(input("Age: ")). 9. Arithmetic Operators
๐ Definition: Arithmetic operators perform mathematical calculations on numeric values. Python supports 7 arithmetic operators: Addition (+), Subtraction (-), Multiplication (*), Division (/), Floor Division (//), Modulus (%), and Exponentiation (**).
๐ All Arithmetic Operators:
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 3 | 13 |
| - | Subtraction | 10 - 3 | 7 |
| * | Multiplication | 10 * 3 | 30 |
| / | Division | 10 / 3 | 3.333... |
| // | Floor Division | 10 // 3 | 3 (decimal cut) |
| % | Modulus (Remainder) | 10 % 3 | 1 (remainder) |
| ** | Exponentiation (Power) | 2 ** 3 | 8 (2ยณ) |
๐ป Examples:
# Example 1: / vs // (Division vs Floor Division) print(10 / 3) # 3.3333 (true division โ always float) print(10 // 3) # 3 (floor โ decimal cut, integer result) print(7 / 2) # 3.5 print(7 // 2) # 3# Example 2: % Modulus โ practical uses print(10 % 3) # 1 (remainder: 10รท3 = 3 remainder 1) print(15 % 5) # 0 (perfectly divisible) # Check if number is even or odd num = 42 if num % 2 == 0:
print("Even") else:
print("Odd")# Example 3: ** Power print(2 ** 10) # 1024 (2 ki power 10) print(25 ** 0.5) # 5.0 (square root of 25) print(27 ** (1/3)) # 3.0 (cube root of 27)๐ฌ Interview Q&A:
Q: / aur // mein kya difference hai?
Ans: / true division hai โ hamesha float result deta hai (10/3 = 3.333). // floor division hai โ decimal truncate karke integer result deta hai (10//3 = 3). Floor division negative numbers mein tricky hai: -7//2 = -4 (neeche ki taraf round hota hai, -3 nahi). Yeh interviews mein puchha jaata hai!
10. Comparison Operators
๐ Definition: Comparison operators compare two values and return a Boolean result (True or False). They are used in conditions (if statements, while loops) to make decisions.
๐ All Comparison Operators:
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equal to | 10 == 10 | True |
| != | Not equal to | 10 != 5 | True |
| > | Greater than | 10 > 5 | True |
| < | Less than | 10 < 5 | False |
| >= | Greater or equal | 10 >= 10 | True |
| <= | Less or equal | 10 <= 5 | False |
๐ป Examples:
# Example 1: Basic comparisons print(10 == 10) # True print(10 == 20) # False print(10 != 20) # True print(10 > 5) # True print(10 <= 10) # True# Example 2: String comparison (alphabetical order) print("apple" == "apple") # True print("apple" == "Apple") # False (case sensitive!) print("banana" > "apple") # True (b comes after a)# Example 3: Chained comparison (Python special!) x = 15 print(10 < x < 20) # True (x between 10 and 20) print(1 < x < 10) # False # Yeh Python ka unique feature hai โ other languages mein yeh nahi hota!= aur == confuse karna! = assignment hai (value assign karo). == comparison hai (values equal hain?). x = 10 (x ko 10 value do). x == 10 (kya x ka value 10 hai? โ True/False). 11. Logical Operators โ and, or, not
๐ Definition: Logical operators combine multiple conditions and return True/False. and returns True only if ALL conditions are True. or returns True if AT LEAST ONE condition is True. not reverses the boolean value (True โ False, False โ True).
๐ Truth Table:
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
๐ป Examples:
# Example 1: and โ ALL must be True age = 25 salary = 60000 print(age > 18 and salary > 50000) # True (dono True) print(age > 30 and salary > 50000) # False (pehla False)# Example 2: or โ ANY one True = True has_degree = False has_experience = True print(has_degree or has_experience) # True (ek True hai)# Example 3: not โ reverse boolean is_raining = False print(not is_raining) # True # Practical: Eligible for loan? age = 25 credit_score = 750 has_default = False eligible = (age >= 21) and (credit_score >= 700) and (not has_default) print("Loan Eligible:", eligible) # True12. Assignment Operators
๐ Definition: Assignment operators assign values to variables. The basic assignment is =. Compound assignment operators combine an arithmetic operation with assignment โ they are shortcuts for common operations like x = x + 5 โ x += 5.
๐ All Assignment Operators:
| Operator | Shortcut For | Example | If x=10 |
|---|---|---|---|
| += | x = x + n | x += 5 | x = 15 |
| -= | x = x - n | x -= 3 | x = 7 |
| *= | x = x * n | x *= 2 | x = 20 |
| /= | x = x / n | x /= 4 | x = 2.5 |
| //= | x = x // n | x //= 3 | x = 3 |
| %= | x = x % n | x %= 3 | x = 1 |
| **= | x = x ** n | x **= 2 | x = 100 |
๐ป Examples:
# Example 1: Counter pattern count = 0 count += 1 # count = count + 1 = 1 count += 1 # count = 2 count += 1 # count = 3 print(count) # 3# Example 2: Running total total = 0 total += 100 # total = 100 total += 250 # total = 350 total -= 50 # total = 300 print("Total:", total)# Example 3: String concatenation with += message = "Hello" message += " World" # "Hello World" message += "!" # "Hello World!" print(message)13. String Basics โ Indexing & Slicing
๐ Definition: Strings are sequences of characters enclosed in single quotes ('text'), double quotes ("text"), or triple quotes ('''text''' / """text"""). Strings are immutable (cannot be changed after creation). Each character has an index โ positive (left to right: 0, 1, 2...) and negative (right to left: -1, -2, -3...). Slicing extracts a portion using [start:stop:step].
๐ฏ Samjho Hinglish Mein: String ek maala (garland) hai โ har moti (character) ka ek position number hai. "PYTHON" mein P = position 0, Y = 1, T = 2, H = 3, O = 4, N = 5. Negative se ulatne lag jaata hai โ N = -1, O = -2, H = -3. Slicing se tum maala ka koi bhi tukda kaat sakte ho โ [1:4] = "YTH" (index 1 se 3 tak, 4 excluded).
Indexing Visual: P Y T H O N (+) 0 1 2 3 4 5 (-) -6 -5 -4 -3 -2 -1 Slicing: string[start:stop:step] โข start โ inclusive (included in result) โข stop โ exclusive (NOT included) โข step โ skip count (default 1)๐ป Examples:
# Example 1: Indexing text = "PYTHON" print(text[0]) # P (first character) print(text[2]) # T (third character) print(text[-1]) # N (last character) print(text[-2]) # O (second last)# Example 2: Slicing text = "PYTHON" print(text[0:3]) # PYT (index 0,1,2 โ 3 excluded) print(text[2:5]) # THO print(text[:3]) # PYT (start se 3 tak) print(text[3:]) # HON (3 se end tak) print(text[:]) # PYTHON (full copy)# Example 3: Step & Reverse text = "PYTHON" print(text[::2]) # PTO (every 2nd character) print(text[::-1]) # NOHTYP (REVERSED string!) print(text[1::2]) # YHN (start from 1, every 2nd)text[0] = "J" โ TypeError! Value change nahi kar sakte directly. Naya string banana padta hai: text = "J" + text[1:] โ "JYTHON". ๐ฌ Interview Q&A:
Q: String reverse kaise karo ek line mein?
Ans: text[::-1] โ slicing ka step -1 dene se string ulat jaata hai. "PYTHON" โ "NOHTYP". Yeh sabse Pythonic way hai โ no loop needed. Interview mein yeh one-liner bahut impress karta hai!
Q: Strings immutable hain โ iska kya matlab?
Ans: Immutable = ek baar create hone ke baad change nahi ho sakta. text[0] = "J" โ TypeError. Naya string banana padta hai (concatenation, replace, slicing se). Lists mutable hain (change ho sakti hain), Strings nahi. Memory mein original string safe rehta hai โ Python internally optimize karta hai immutable objects ko.
14. f-Strings โ Modern String Formatting
๐ Definition: f-Strings (formatted string literals) are the modern and recommended way to embed variables and expressions inside strings in Python 3.6+. They start with f before the quote and use {variable} to insert values. They are faster, cleaner, and more readable than older methods (.format() or %).
๐ฏ Samjho Hinglish Mein: f-String = variable ko seedha string ke andar daal do. Purane tarike: "Hello " + name (concatenation โ ugly), "Hello {}".format(name) (verbose). Naya tarika: f"Hello {name}" โ seedha, clean, fast! Curly brackets {} mein variable ya expression likho โ Python khud value daal dega. 2026 mein yeh standard hai โ hamesha f-strings use karo!
๐ป Examples:
# Example 1: Basic f-string name = "Jatin" age = 25 city = "Gurugram"
print(f"My name is {name}, I'm {age} years old from {city}.")
# Output: My name is Jatin, I'm 25 years old from Gurugram.
# Without f-string (ugly comparison):
print("My name is " + name + ", I'm " + str(age) + " years old.")
# Example 2: Expressions inside f-string price = 999 qty = 3 print(f"Total: โน{price * qty}") # Output: Total: โน2997 print(f"10 + 20 = {10 + 20}") # Output: 10 + 20 = 30 print(f"{name.upper()} is {age * 12} months old") # Output: JATIN is 300 months old# Example 3: Number formatting in f-strings salary = 5843567.897 # 2 decimal places print(f"Salary: โน{salary:.2f}") # Output: Salary: โน5843567.90 # Comma separator print(f"Salary: โน{salary:,.2f}") # Output: Salary: โน58,43,567.90 # Percentage growth = 0.1567 print(f"Growth: {growth:.1%}") # Output: Growth: 15.7% # Padding / Alignment print(f"{name:<15} | {age}") # Left aligned, 15 chars print(f"{name:>15} | {age}") # Right aligned print(f"{name:^15} | {age}") # Center alignedOutput: Jatin | 25 Jatin | 25 Jatin | 25๐ f-String Formatting Cheat Sheet:
| Format | Meaning | Example | Result |
|---|---|---|---|
| :.2f | 2 decimal places | {3.14159:.2f} | 3.14 |
| :,.2f | Comma + 2 decimals | {50000:.2f} | 50,000.00 |
| :.1% | Percentage format | {0.156:.1%} | 15.6% |
| :<15 | Left align (15 width) | {"Hi":<15} | Hi |
| :>15 | Right align | {"Hi":>15} | Hi |
| :0>5 | Zero-padded | {42:0>5} | 00042 |
f"Hello {name}". .format() ya % formatting purane tarike hain. f-strings sabse fast, sabse readable, sabse Pythonic hain. Python 3.6+ mein available โ aur 2026 mein sab 3.6+ use kar rahe hain! ๐ฌ Interview Q&A:
Q: f-String mein number ko 2 decimal aur comma separator ke saath kaise format karein?
Ans: f"{value:,.2f}". Colon ke baad , comma separator lagata hai, .2f 2 decimal places fix karta hai. f"{50000.5:,.2f}" โ "50,000.50". Reporting aur dashboards mein yeh format bahut use hota hai โ readable numbers dikhane ke liye.
Q: f-String ke andar function call kar sakte hain?
Ans: Haan! Curly brackets ke andar koi bhi valid Python expression likh sakte ho โ function calls, methods, arithmetic, ternary operator. f"{name.upper()}", f"{len(name)}", f"{'Even' if x%2==0 else 'Odd'}". Bahut powerful feature hai โ lekin readability ka dhyan rakho, bahut complex expressions avoid karo.
Quick Revision โ Part 1 Summary
| # | Topic | Key Takeaway |
|---|---|---|
| 1 | Python Overview | High-level, interpreted, dynamically typed, indentation-based |
| 2 | print() | Output function, sep & end parameters |
| 3 | Comments | # single line, '''multi-line''' |
| 4 | Variables | Named containers, snake_case, no declaration needed |
| 5 | Data Types | int, float, str, bool โ auto-detected |
| 6 | type() | Check data type, isinstance() for True/False check |
| 7 | Type Casting | int(), float(), str(), bool() โ int(3.99)=3 not 4! |
| 8 | input() | Always returns string โ wrap in int()/float() |
| 9 | Arithmetic | +, -, *, /, //, %, ** โ / gives float, // gives int |
| 10 | Comparison | ==, !=, >, <, >=, <= โ returns True/False |
| 11 | Logical | and (all True), or (any True), not (reverse) |
| 12 | Assignment | +=, -=, *=, /= โ shortcuts for common operations |
| 13 | String Indexing | [0]=first, [-1]=last, [1:4]=slice, [::-1]=reverse |
| 14 | f-Strings | f"Hello {name}" โ modern, fast, readable formatting |
Next: Python Handbook โ Part 2
Agle part mein hum cover karenge: Strings Deep Dive & Numbers โ String methods (upper, lower, split, join, strip, replace, find, count), String operations, Escape characters, Number methods (abs, round, min, max), Math module, aur Random module. Part 1 ki foundation ke upar build karenge. Data Insights par sab FREE, detailed, Hinglish mein.
Happy Learning & Keep Coding! ๐
๐ฌ Comments (0)
Loading comments...