Why This Topic Matters

Every Python program — from a small calculator to a full machine learning model — does one basic job: it stores some information, and then does something with it. To store information we use variables. To use that information correctly, we must understand its data type.

Most beginner errors in Python come from mixing up these two ideas. In this post we will learn:

  1. What variables are, and how to use them
  2. What data types are, and the main types in Python
  3. Why "25" and 25 are different
  4. What type conversion is, and how to do it safely

Every idea comes with a small example. Type the examples yourself in Python — it is the fastest way to learn.


1. Variables

1.1 What is a Variable?

When we write a program, we need a place to keep information — like a person's age, a name, or the price of a product. That place is called a variable.

A variable is just a name that points to a value stored in the computer's memory.

Think of a variable like a name tag on a box. The box holds the value, and the name tag lets you find it again whenever you need it.

Simple Example

age = 25
name = "Satyam"
price = 499.99

print(age)     # 25
print(name)    # Satyam
print(price)   # 499.99

Here age, name and price are variables. The = sign does not mean "equal to" like in maths. It means "store this value in this name". This is called assignment.

Notice one more thing: we never told Python what kind of value each variable holds. Python looks at the value and understands it on its own. This is called dynamic typing.

1.2 Changing the Value of a Variable

A variable can be given a new value at any time. The old value is simply forgotten.

score = 10
print(score)    # 10

score = 20
print(score)    # 20

Because Python uses dynamic typing, a variable can even change its type:

data = 100        # int
data = "hello"    # now it is a str
print(data)       # hello

Python allows this, but it is a bad habit. If one name holds a number in one line and text in another, your code becomes confusing and full of type errors. Keep one variable for one kind of value.

1.3 Assigning Many Variables at Once

Python gives some short ways to assign values:

# Same value to many variables
a = b = c = 0
print(a, b, c)                # 0 0 0

# Different values in one line
name, age, city = "Satyam", 25, "Jaipur"
print(name, age, city)        # Satyam 25 Jaipur

# Swapping two variables
a, b = 1, 2
a, b = b, a
print(a, b)                   # 2 1

1.4 Rules for Naming a Variable

Python is strict about variable names. These are the rules:

NameValid?Reason
student_ageYesLetters and underscore
marks2YesNumber is not at the start
2marksNoStarts with a number
total marksNoHas a space
forNoReserved word

Good naming habits


2. Data Types

2.1 What is a Data Type?

Every value in Python has a data type. The data type tells Python what kind of value it is, and what you are allowed to do with it.

For example, you can multiply two numbers, but it makes no sense to multiply two names. The data type is how Python knows the difference.

There are 4 basic data types that you will use almost every day:

TypeMeaningExample
intWhole numbers (no decimal point)25, -3, 1000
floatDecimal numbers3.14, 499.99
strText (always inside quotes)"Satyam", "Jaipur"
boolOnly two values — Yes or NoTrue, False

2.2 Checking the Data Type

Use the built-in type() function. It tells you the type of any value or variable.

age = 25
price = 499.99
name = "Satyam"
is_active = True

print(type(age))        # <class 'int'>
print(type(price))      # <class 'float'>
print(type(name))       # <class 'str'>
print(type(is_active))  # <class 'bool'>

If you only want a quick yes/no answer, use isinstance():

print(isinstance(25, int))        # True
print(isinstance("25", int))      # False
print(isinstance(25.0, (int, float)))   # True — checks for int OR float

2.3 int — Whole Numbers

An int is a number without a decimal point. It can be positive, negative, or zero. There is no size limit in Python — you can store very big numbers.

students = 40
temperature = -5
population = 1_000_000     # underscores make big numbers easy to read

print(population)          # 1000000
print(type(10 ** 30))      # <class 'int'>

2.4 float — Decimal Numbers

A float is a number with a decimal point. Use it for prices, heights, percentages, and so on.

height = 5.9
percentage = 87.5

print(7 / 2)              # 3.5
print(type(7 / 2))        # <class 'float'>
print(type(6 / 2))        # <class 'float'> — division ALWAYS gives a float
print(7 // 2)             # 3   — floor division gives an int

A small surprise about floats: computers store decimals in a way that is not always exact.

print(0.1 + 0.2)              # 0.30000000000000004
print(round(0.1 + 0.2, 2))    # 0.3

This is normal and happens in every programming language. When you show a result to a user, use round() to keep only the digits you need.

2.5 str — Text

A str (string) is any text written inside quotes. You can use single quotes or double quotes — both are the same.

city = "Jaipur"
greeting = 'Hello'
message = "It's a nice day"     # double quotes let us use ' inside

Some useful things you can do with a string:

s = "Python"

print(len(s))          # 6       — number of characters
print(s[0])            # P       — first character
print(s[-1])           # n       — last character
print(s.upper())       # PYTHON
print("Py" + "thon")   # Python  — joining strings
print("ha" * 3)        # hahaha  — repeating a string

To put variables inside a sentence, the easiest way is an f-string (put f before the quotes, and write variables inside { }):

name = "Satyam"
age = 25
print(f"My name is {name} and I am {age} years old.")
# My name is Satyam and I am 25 years old.

Notice that the f-string did not need any conversion — it changes the number to text for us. Keep this trick in mind, we will use it again later.

2.6 bool — True or False

A bool (boolean) has only two possible values: True and False. The first letter must be a capital — true in small letters is an error.

Booleans are mostly created by comparisons:

print(10 > 5)       # True
print(10 == 5)      # False   (== means "is equal to?")
print(type(10 > 5)) # <class 'bool'>

We use booleans to make decisions, for example in if statements.

2.7 None — No Value

None is a special value that means "nothing is here". It has its own type, called NoneType.

result = None
print(result)         # None
print(type(result))   # <class 'NoneType'>

It is useful when a variable must exist, but we do not have a value for it yet.

2.8 Other Data Types (a quick look)

Apart from the 4 basic types, Python has types that hold many values together. We will study them in separate posts, but you should know their names:

TypeExampleWhat it is
list[10, 20, 30]Ordered collection, can be changed
tuple(10, 20, 30)Ordered collection, cannot be changed
set{10, 20, 30}Collection with no duplicates
dict{"name": "Satyam"}Pairs of key and value

3. The Problem: "25" is not the same as 25

Look at these two lines:

a = 25      # int  (a number)
b = "25"    # str  (text)

On the screen they look almost the same. But for Python they are completely different things. See what happens when we use the * and + signs on both:

print(25 * 3)     # 75
print("25" * 3)   # 252525

print(5 + 5)      # 10
print("5" + "5")  # 55

With numbers, Python does maths. With text, Python just joins or repeats the characters. Same look, very different result!

Also remember that they are never equal to each other:

print("3" == 3)   # False
print(3 == 3.0)   # True  — int and float with the same value are equal

3.1 The Error Every Beginner Sees

Now let's try to add a number to a piece of text:

age = "25"
print(age + 5)

Python gives an error:

TypeError: can only concatenate str (not "int") to str

Why? Python does not know what you want. Should it add the numbers (25 + 5 = 30)? Or join the texts ("25" + "5" = "255")? Since it cannot decide, it stops and shows an error.

This happens very often in real work, because data coming from a form, a file, a website, or the input() function almost always arrives as str, even when it looks like a number.

The solution is Type Conversion.


4. Type Conversion

Type Conversion (also called Type Casting) means:

Changing a value from one data type to another data type.

There are 2 kinds of type conversion:

  1. Implicit Conversion — Python does it automatically
  2. Explicit Conversion — you do it yourself

4.1 Implicit Conversion (automatic)

What is it?

Sometimes Python changes the type for you, without being asked. It does this only when it is safe and no information will be lost.

Small Example

x = 5        # int
y = 2.5      # float

result = x + y
print(result)          # 7.5
print(type(result))    # <class 'float'>

We added an int and a float. Python quietly changed 5 into 5.0 and gave us a float answer. It chose float because it can keep the decimal part. Converting to int would have thrown away the .5.

The same happens with bool: True is treated as 1 and False as 0.

print(True + 1)    # 2
print(3 + True)    # 4

So the order of "safe" conversion is: bool → int → float. Python moves towards the type that can hold more information.

Important: Python will never automatically join a number and a text. That is exactly why "25" + 5 failed above. For that, we need explicit conversion.


4.2 Explicit Conversion (manual)

What is it?

Here you tell Python which type you want. Python gives us one simple function for each type:

FunctionConverts toExample
int()Whole numberint("25") → 25
float()Decimal numberfloat("3.14") → 3.14
str()Textstr(25) → "25"
bool()True / Falsebool(0) → False

Fixing our earlier error

# Step 1: the value is text
age = "25"

# Step 2: convert text into a number
age = int(age)

# Step 3: now math works
print(age + 5)          # 30
print(type(age))        # <class 'int'>

That's it — one line of conversion fixes the problem.

4.3 int() in Detail

int() can take text, a float, or a bool:

print(int("25"))       # 25
print(int("-7"))       # -7
print(int(" 42 "))     # 42   — extra spaces around the text are ignored
print(int(25.9))       # 25   — decimal part is CUT OFF
print(int(-2.9))       # -2   — cut off, not rounded down
print(int(True))       # 1

The most important thing to remember: int() does not round. It simply removes everything after the decimal point. If you want proper rounding, use round():

print(int(25.9))          # 25
print(round(25.567, 2))   # 25.57

4.4 float() in Detail

print(float("3.14"))   # 3.14
print(float("5"))      # 5.0   — a whole-number text works too
print(float(10))       # 10.0
print(float(True))     # 1.0

4.5 str() in Detail

str() can turn almost anything into text, and it never fails:

print(str(25))        # 25
print(str(3.14))      # 3.14
print(str(True))      # True
print(str(None))      # None
print(str([1, 2]))    # [1, 2]

These all look the same as before on the screen, but now each one is a str. The same problem happens when you join a number to a sentence:

age = 25

print("Age: " + age)         # TypeError!
print("Age: " + str(age))    # Age: 25
print(f"Age: {age}")         # Age: 25  — f-string does it for us

4.6 bool() in Detail

bool() answers one question: "Is there something in this value, or is it empty?"

Gives FalseGives True
0 and 0.0Any other number, like 5 or -7
"" (empty text)Any text with at least one character
[] (empty list)A list with something inside
None—
print(bool(0))        # False
print(bool(5))        # True
print(bool(""))       # False
print(bool("hello"))  # True
print(bool([]))       # False
print(bool([0]))      # True   — the list is not empty, even though it holds a 0

4.7 Converting Collections

The same idea works for lists, tuples and sets. This is very useful in real projects:

print(list("abc"))            # ['a', 'b', 'c']
print(tuple([1, 2, 3]))       # (1, 2, 3)
print(list((1, 2)))           # [1, 2]

# Removing duplicates using set()
marks = [80, 90, 80, 70, 90]
unique_marks = list(set(marks))
print(set(marks))             # {80, 90, 70}  (order may be different)

Converting a list to a set removes all duplicate values. Then list() turns it back into a list.


5. Conversions That Confuse Beginners

5.1 Text with a decimal point → int()

int("25.5")     # ValueError: invalid literal for int() with base 10: '25.5'

int() cannot read a text that has a decimal point. First convert it to float, then to int:

int(float("25.5"))    # 25

Notice that the .5 is lost, because int() cuts off the decimal part.

5.2 Text that is not a number at all

int("abc")      # ValueError: invalid literal for int() with base 10: 'abc'
int("")         # ValueError — empty text is also not a number

Python can only convert text that actually looks like a number. Words like "abc" or "twenty" will always give a ValueError.

5.3 bool() on text

print(bool("False"))   # True   — surprise!
print(bool("0"))       # True   — also a surprise!

This surprises almost everyone. bool("False") gives True! The reason is simple: Python does not read the meaning of the word. It only checks whether the text is empty or not. The text "False" has letters in it, so it is not empty, so the answer is True. The same is true for "0" — it is a text with one character.

Simple rule: 0, empty text, and empty collections are False. Everything else is True.

5.4 Types you can be sure about

Three things that often confuse students, in one place:

CodeResultWhy
int("10") + int("5")15Both converted to numbers first
"10" + "5""105"Two texts are joined
int("10" + "5")105Join first, then convert

6. Converting Safely with try / except

What if a user types "abc" when you ask for their age? Your program will crash with a ValueError. In real programs, we handle this using try and except:

user_input = "abc"

try:
    age = int(user_input)
    print("Your age is", age)
except ValueError:
    print("Please enter a valid number.")

# Please enter a valid number.

How it works: Python first tries to run the code inside try. If a ValueError happens, it does not crash — it runs the except block instead.

You can put this in a small helper function and use it again and again:

def to_int(value, default=0):
    try:
        return int(value)
    except ValueError:
        return default

print(to_int("25"))     # 25
print(to_int("abc"))    # 0
print(to_int("25.5"))   # 0   — int() cannot read decimal text, so the default is used

7. Practical Examples

Example 1: Age Next Year

A user types their age, and we tell them their age next year. The input() function always returns text, so we must convert it.

# Step 1: take input (arrives as text)
user_input = input("Enter your age: ")     # user types 30

# Step 2: convert text to a number
age = int(user_input)

# Step 3: do the math
next_year_age = age + 1

# Step 4: show the result
print("Next year you will be " + str(next_year_age))
# Next year you will be 31

See the pattern? Convert in → Calculate → Convert out. If you remember this one pattern, most beginner type errors will disappear.

Example 2: Shop Bill

Data from a file or website usually comes as text. Here the price and quantity arrive as strings:

price = "499.99"     # text
qty = "3"            # text

total = float(price) * int(qty)
print(total)                 # 1499.97
print(f"Total bill: Rs {total}")   # Total bill: Rs 1499.97

We used float() for the price (it has decimals) and int() for the quantity (it is a whole number). Choosing the right function is part of the skill.

Example 3: Average Marks

marks = ["80", "90", "70"]      # all are text

total = 0
for m in marks:
    total = total + int(m)      # convert each one before adding

average = total / len(marks)
print(average)                  # 80.0

8. Common Mistakes

MistakeWhat happensFix
Adding text and number: "25" + 5TypeErrorConvert with int()
Joining number to sentence: "Age: " + 25TypeErrorUse str() or an f-string
Using int("25.5")ValueErrorUse int(float("25.5"))
Using int("abc")ValueErrorCheck the input, or use try / except
Thinking int(9.9) gives 10Gives 9Use round() if you want rounding
Thinking bool("False") is FalseGives TrueCompare instead: text == "False"
Writing true or falseNameErrorUse True and False

Quick Recap

SituationWhat to do
Store a valueUse a variable: age = 25
Check the type of a valueUse type() or isinstance()
Data is text, but you need to do mathConvert with int() or float()
Number needs to go inside a sentenceConvert with str(), or use an f-string
Text has a decimal point, you want a whole numberUse int(float(...))
Text is not a number at all (like "abc")It cannot be converted — you get a ValueError. Use try / except
Checking True / False of textAny non-empty text is True, only "" is False
Remove duplicates from a listlist(set(my_list))

Getting comfortable with variables and type conversion early makes everything ahead — reading files, cleaning data, working with pandas — much easier. Most "strange errors" that beginners face come from a type mismatch like the ones we saw here.


Practice Questions

Try to answer these first, without running the code. Then check with Python.

  1. What is the type of 3 + 4.0?
  2. What does "7" * 3 give?
  3. What does int(8.99) give?
  4. What does bool("0") give?
  5. Why does "Total: " + 50 fail, and how will you fix it?
  6. Which is correct for the text "12.75" — int() or float()?
Click to reveal answers
  1. float — the result is 7.0, because Python converts the int to float automatically.
  2. "777" — text is repeated, not multiplied.
  3. 8 — int() cuts off the decimal part.
  4. True — it is a non-empty text.
  5. Python cannot join text and a number. Fix: "Total: " + str(50) or f"Total: {50}".
  6. float() — because the text has a decimal point.