🐍 Python Variables and Data Types: A Beginner-Friendly Guide

📌 What is a Variable?

A variable in Python is like a label or a name you give to a piece of data so you can use it later in your program. Think of a variable as a container that holds something—like numbers, text, or lists of items.

pythonCopyEditname = "Alice"
age = 25

In the example above:

  • name is a variable that stores a piece of text ("Alice").
  • age is a variable that stores a number (25).

🆚 Python vs. Other Languages

In some programming languages like Java or C++, you have to declare the type of the variable before using it. That’s called static typing:

javaCopyEditint age = 25;  // Java

But in Python, you don’t need to declare the type. Python figures it out for you. This is called dynamic typing:

pythonCopyEditage = 25  # Python figures out it's an integer

✍️ Declaring and Assigning Variables

✅ Syntax

In Python, you assign a value to a variable using the = sign:

pythonCopyEditcity = "New York"
temperature = 75.5

🧠 Naming Rules and Conventions

  • Variable names can include letters, numbers, and underscores (_).
  • Variable names must start with a letter or underscore.
  • Names are case-sensitive: Name and name are different variables.
  • Use snake_case for readability (e.g., user_name, not username or UserName).

✅ Good Variable Names:

pythonCopyEditfirst_name = "Jane"
user_age = 30

❌ Bad Variable Names:

pythonCopyEdit1name = "Jane"     # starts with a number
user-age = 30      # contains a dash, which is not allowed

🔄 Python’s Dynamic Typing

Because Python is dynamically typed, you can change a variable’s type just by assigning it a new value:

pythonCopyEditx = 10        # x is an integer
x = "hello"   # now x is a string!

This flexibility is powerful but can also lead to bugs if you’re not careful.


🧬 Python’s Core Data Types

1. Numeric Types

int – Whole numbers

pythonCopyEditage = 30

float – Decimal numbers

pythonCopyEditprice = 19.99

complex – Numbers with real and imaginary parts

pythonCopyEditz = 3 + 4j

Common Operations:

pythonCopyEditx = 5 + 2     # 7
y = 3.5 * 2   # 7.0

2. Text Type

str – Strings (text)

pythonCopyEditgreeting = "Hello, world!"

Operations:

pythonCopyEditlen(greeting)       # 13
greeting.upper()    # "HELLO, WORLD!"

3. Sequence Types

list – A changeable list of items

pythonCopyEditfruits = ["apple", "banana", "cherry"]
fruits.append("orange")

tuple – An unchangeable list of items

pythonCopyEditcoordinates = (10, 20)

range – A sequence of numbers

pythonCopyEditnumbers = range(5)  # 0 to 4

4. Mapping Type

dict – A set of key-value pairs

pythonCopyEditperson = {"name": "Alice", "age": 25}
print(person["name"])  # "Alice"

5. Set Types

set – Unordered, no duplicates

pythonCopyEditcolors = {"red", "green", "blue"}

frozenset – Like set, but unchangeable

pythonCopyEditfrozen = frozenset(["a", "b", "c"])

6. Boolean Type

bool – True or False

pythonCopyEditis_raining = True

Used often in conditions:

pythonCopyEditif is_raining:
    print("Take an umbrella!")

7. Binary Types

Used for handling binary data (e.g., images, files).

  • bytes – Immutable binary
pythonCopyEditb = b"hello"
  • bytearray – Mutable binary
pythonCopyEditba = bytearray(b"hello")
  • memoryview – Memory-efficient view of binary data
pythonCopyEditmv = memoryview(b)

🔍 Checking Data Types

Use type() to find out a variable’s type:

pythonCopyEditx = 42
print(type(x))  # <class 'int'>

Use isinstance() to check if a variable is a specific type:

pythonCopyEditisinstance(x, int)  # True

🔄 Type Conversion (Casting)

🧠 Implicit Conversion

Python will automatically convert types when needed:

pythonCopyEditresult = 10 + 2.5  # int + float = float
print(result)      # 12.5

✋ Explicit Conversion

You can manually change types:

pythonCopyEditage_str = "25"
age = int(age_str)

pi = 3.14
rounded = int(pi)  # 3

💡 Best Practices

  • Use clear, descriptive variable names (score, not s).
  • Stick to one type per variable when possible.
  • Use type() and isinstance() for type checking in complex code.
  • Avoid reusing variable names for different types.

⚠️ Common Beginner Mistakes

  • Using undeclared variables:
pythonCopyEditprint(name)  # NameError if name wasn't defined earlier
  • Unexpected type changes:
pythonCopyEditx = "10"
y = x + 5  # TypeError – can't add string and int
  • Wrong data type in functions:
pythonCopyEditlen(25)  # TypeError – int has no length

✅ Recap

  • Variables store data and can change types in Python.
  • Python has many data types: numbers, text, lists, dictionaries, etc.
  • You can check types with type() and isinstance().
  • Be clear with names and consistent with types.

🧪 Quiz Time!

1. What is the correct way to assign a string to a variable?
A. name: "Alice"
B. string name = "Alice"
C. name = "Alice"
D. name == "Alice"


2. Which function returns the type of a variable?
A. typeof()
B. type()
C. get_type()
D. checktype()


3. What is the output of type(3.14)?
A. <class 'int'>
B. <class 'decimal'>
C. <class 'number'>
D. <class 'float'>


4. Which of the following is a valid variable name?
A. 2name
B. user-name
C. user_name
D. user name


5. What happens when you try to add a string and an integer?
A. Python converts the int to string and adds them
B. Nothing happens
C. You get a TypeError ✅
D. Python skips the line


🧩 Bonus Practice Challenge

Write a short Python program that:

  1. Stores your name and age in variables.
  2. Converts your age to a string and combines it with your name in a sentence.
  3. Prints the sentence.
pythonCopyEdit# Your code here:
name = "YourName"
age = 20
message = name + " is " + str(age) + " years old."
print(message)
Posted in ai