Chapter 2: Variables & Data Types in Python

Variables banana, data types samajhna, aur input-output karna – sab kuch with rules aur examples!

1. Variables in Python

Variable ek container jaisa hota hai jisme hum koi value store karte hain.

Rules of Writing Variables:

✅ Right Way:

name = "Amit"
age = 25

❌ Wrong Way:

2name = "Amit" # ❌ Invalid: number se start nahi ho sakta
my name = "Amit" # ❌ Invalid: spaces not allowed
class = "ABC" # ❌ Invalid: 'class' is a keyword

Output:

Amit
25

2. Input from User

input() function user se data lene ke liye use hota hai. By default yeh string deta hai.

name = input("Enter your name: ")
print("Welcome", name)
Enter your name: Ravi
Welcome Ravi

Common Mistake:

age = input("Enter age: ")
print(age + 5) # ❌ Error: string + int not allowed

Correct Way:

age = int(input("Enter age: "))
print(age + 5)
Enter age: 20
25

3. Data Types in Python

a = 5
b = 3.14
c = "Hi"
d = True
e = 4 + 2j
print(type(a), type(b), type(c), type(d), type(e))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'complex'>

4. Type Casting

Type casting matlab ek data type ko dusre me badalna.

✅ Right Example:

num = "10"
num = int(num)
print(num + 5)
15

❌ Wrong Example:

num = "ten"
num = int(num) # ❌ Error: 'ten' string ko int me convert nahi kar sakte

5. print() Function

print() ka use output dikhane ke liye hota hai. Kuch bhi show karna ho screen pe, print ka use hota hai.

print("Learning Python is fun!")
Learning Python is fun!