Lesson 2: Python Basics: Variables se Strings tak

Lesson 2: Python Basics: Variables se Strings tak

Arre waah bro, welcome back to my blog! Main hoon aapka bhaiya, ek senior Python developer jo ab blogging kar raha hai. Aaj hum baat karenge Python ke fundamentals pe – variables, data types, operators, aur phir input-output with strings. Kyun? Kyunki ye sab basics hain yaar, bina inke aage badh nahi sakte. Imagine karo tu ek naya developer hai, code likh raha hai aur suddenly error aa jaata hai kyunki variable ka type galat hai. Been there done that! Mujhe yaad hai jab main college mein tha pehla Python script likha, socha sab easy hai... lekin phir operators mix up kar diye aur program infinite loop mein phas gaya. Has has ke pet dukha tha us din!

Bro ye article tere jaise juniors ke liye hai – casual, fun, thoda hinglish mein taaki lage jaise main personally baat kar raha hoon. Hum step by step jayenge stories sunayenge jokes marenge aur end mein ek mini project bhi karenge. Ready ho? Chalo shuru karte hain. Coffee le lo long read hai ye!

Variables, Constants aur Naming Rules – Foundation Hai Ye

Variables? Ek box jisme tu data rakhta hai, jaise dabba mein biryani. Python mein bas likh: naam = value. No need to declare type, Python khud samajh leta hai.

Constants? Fixed values, jaise math ka PI. Python mein true constant nahi, lekin uppercase naam rakho (convention), taaki sabko pata chale change nahi karna.

Naming rules zaroori hain, warna errors! Yahaan quick table:

RuleValid ExampleInvalid Example
Start with letter or _score, _count1score
Only letters, numbers, _user_age2user@name
Case sensitiveAge != ageN/A
No reserved wordsmy_loopfor
Use snake_casetotal_markstotalMarks

Code dekho:

PI = 3.14159  # Constant
user_age = 25  # Variable

Story: Ek baar maine variable 'x' rakha, project bada hua, aur bhool gaya x kya tha. Debugging mein dimag kharab! Hamesha descriptive naam rakh, bro!

Common galti: Invalid names ya reserved words. Fix: Naam badlo, snake_case use karo.

Data Types – Kya Kya Store Kar Sakte Ho?

Data types batate hain variable mein kya hai. Python ke main types:

TypeDescriptionExample
intWhole numbers42, -100
floatDecimals3.14, 2.5e3
strText"Hello", 'Bro'
boolTrue/FalseTrue, False
complexComplex numbers2+3j

Type check karne ka tareeka:

print(type(42))  # <class 'int'>
print(type("Bro"))  # <class 'str'>

Python dynamic typed hai – type change ho sakta hai, jaise user_age = 25; user_age = "twenty five". Flexible, lekin bugs se bacho!

Type Conversion & Casting – Data Ko Transform Karo

Kabhi string ko number chahiye? Use int(), float(), str(), bool().

Misal:

str_num = "123"
int_num = int(str_num)  # 123
float_num = float("3.14")  # 3.14

Implicit conversion: 1 + 2.0 = 3.0 (float). Explicit safe hai.

Galti: int("abc") – ValueError. Fix: Try-except (baad mein sikhenge).

Kyun zaroori? User input, APIs – sab mixed data dete hain.

Operators – Code Ka Masala

Operators ka full breakdown with tables. Categories: Arithmetic, Comparison, Logical, Assignment, Bitwise.

Arithmetic Operators

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 22.5
//Floor Division5 // 22
%Modulo5 % 21
**Exponent5 ** 225

Comparison Operators

OperatorDescriptionExampleResult
==Equal5 == 5True
!=Not Equal5 != 3True
>Greater Than5 > 3True
<Less Than5 < 3False
>=Greater or Equal5 >= 5True
<=Less or Equal5 <= 3False

Logical Operators

OperatorDescriptionExampleResult
andBoth TrueTrue and FalseFalse
orAny TrueTrue or FalseTrue
notInvertnot TrueFalse

Assignment Operators

OperatorExampleEquivalent
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3

Bitwise Operators

Binary level pe: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right Shift).

a = 5  # 101
b = 3  # 011
print(a & b)  # 1 (001)

Operator Precedence Chart

Kaun pehle? Yahaan table:

Precedence (High to Low)Operators
1**
2~ + - (unary)
3* / // %
4+ -
5<< >>
6&
7^ |
8== != > < >= <=
9not
10and
11or

Joke: Precedence na samjha to code jaise traffic jam! Parentheses () use karo clarity ke liye.

Galti: 2 + 3 * 4 = 14 (not 20). Precedence yaad rakh!

Mini Practice Exercises – Ab Tu Try Kar

Practice se perfect banoge:

  • Constant GRAVITY = 9.8, print karo.
  • Check type of 3.14 aur "3.14".
  • "45.67" ko float, +10 karo.
  • Calculate 10 ** 2 % 3, precedence dhyan se.
  • Logical: If (age > 18 and score >= 80), print "Pass".

Run karo, galti se seekho. Pehli baar modulo samajh nahi aaya, game score mein use kiya tab clear hua!

Taking Input from Users – Program Ko Interactive Banao

input() string deta hai. Numbers ke liye convert.

age = int(input("Age bata bro: "))

Galti: Convert bhoolna ya invalid input. Fix: Validate karo, spaces ke liye strip().

Formatting Output – Output Ko Cool Banao

f-strings sabse best (Python 3.6+).

name = "Raj"
age = 22
print(f"Yo {name}, tu {age} ka hai!")

Alternative: .format(), lekin f-strings fast. Old % ab mat use.

Strings in Depth – Text Ka Khel

Indexing: s[0] first char. Slicing: s[start:end:step].

s = "PythonBro"
print(s[0:6])  # Python
print(s[::-1])  # orByhtyp

ASCII chart for clarity:

P y t h o n B r o
0 1 2 3 4 5 6 7 8
-9-8-7-6-5-4-3-2-1

Concat: s1 + s2. Strings immutable – change ke liye new string.

String Methods – Super Toolkit

MethodDescriptionExampleResult
upper()Uppercase"bro".upper()"BRO"
lower()Lowercase"BRO".lower()"bro"
replace(old, new)Replace"hi bro".replace("bro", "dude")"hi dude"
split(sep)Split to list"a b c".split()['a', 'b', 'c']
join(list)Join list" ".join(['a', 'b'])"a b"
strip()Remove spaces" bro ".strip()"bro"
find(sub)Find index"bro".find("r")1
count(sub)Count"bro bro".count("bro")2

Story: Ek app mein usernames clean kiye strip() aur lower() se, duplicates gone!

Hands-on Project: Basic Username Formatter

Chalo, ek project: User se naam lo, lowercase karo, spaces hatao, aur end mein "007" add karo.

  1. Input full name
  2. Lowercase
  3. Remove spaces
  4. Add "007"
  5. Print username
full_name = input("Naam daal bro: ")
clean_name = full_name.lower().replace(" ", "")
username = clean_name + "007"
print(f"Tera username: {username}")

Extend: Check if name empty, print "Kuch daal!"

Conclusion – Tu Ab Pro Hai!

Bro, full lesson khatam! Variables se strings, tables, charts, sab cover kiya. Practice kar, galtiyan kar, seekh. Next: Loops aur if-else. Comment mein bata kaisa laga, subscribe kar! Coding masti hai, stress mat le! 😎

Post a Comment

0 Comments