CS Engineering Gyan

Variables & Data Types in Python

In the previous chapter, we covered the basic syntax rules that every Python program has to follow, including indentation, comments, and how statements are structured. Now that those foundational rules are clear, it is time to look at how Python actually stores and works with the values a program needs, starting with variables and the way Python handles converting values between different data types.

A variable is simply a name that refers to a value stored in a computer's memory, allowing a program to store, retrieve, and manipulate that value throughout its execution. Python's approach to variables is notably flexible compared to many other languages, since a single variable name can refer to a completely different type of value at different points in the same program, without ever needing to be explicitly declared with a fixed type in advance.

In this tutorial, you will learn how variables are created and assigned in Python, understand Python's dynamic typing model, briefly revisit the core data types Python provides, and explore type conversion in depth, covering both implicit type conversion, which Python performs automatically, and explicit type conversion, which a programmer requests directly.


What is a Variable in Python?

A variable in Python is created the moment a value is assigned to a name, using the equals sign. Unlike many other programming languages, Python does not require a variable's type to be stated up front, since the interpreter automatically figures out what type of value is being stored based on the value itself.

Example

channel = "CS Engineering Gyan"

subscribers = 60000

average_rating = 4.8

print(channel)

print(subscribers)

print(average_rating)

Output

CS Engineering Gyan

60000

4.8

In this example, three separate variables are created in a single program, each holding a different kind of value, a piece of text, a whole number, and a decimal number, without any of them needing to be declared with a specific type beforehand.


Multiple Assignment

Python allows several variables to be assigned values in a single line, which can make programs shorter and, in the right situations, easier to read. This can be done by assigning the same value to multiple variables at once, or by assigning several different values to several different variables in one statement.

Example

title1, title2, title3 = "Arrays", "Pointers", "Functions"

print(title1)

print(title2)

print(title3)

Output

Arrays

Pointers

Functions

Dynamic Typing in Python

Python is described as a dynamically typed language, which means a variable's type is determined automatically based on the value currently assigned to it, and that same variable is free to hold a completely different type of value later in the program. This is different from statically typed languages, where a variable's type is fixed once it is declared and cannot change afterward.

Example

data = 100

print(data, type(data))

data = "one hundred"

print(data, type(data))

Output

100 <class 'int'>

one hundred <class 'str'>

Here, the variable data first holds an integer value, and the built-in type() function confirms this. The exact same variable is then reassigned to hold a string instead, and Python allows this without complaint, automatically updating what type of value that variable currently represents.


A Quick Recap of Python's Core Data Types

Python provides several built-in data types for representing different kinds of information, which were covered in full detail in the earlier data types chapter of this series. As a quick reminder before moving into type conversion, the table below summarizes the most commonly used ones.

Data Type Example Value
int 5200
float 4.8
str "CS Engineering Gyan"
bool True
list ["Arrays", "Pointers"]
tuple (1, 2, 3)

What is Type Conversion?

Type conversion refers to changing a value from one data type into another, which becomes necessary in many everyday programming situations, such as when a number typed by a user arrives as text and needs to be used in a mathematical calculation, or when two values of different types need to be combined together. Python supports two distinct approaches to type conversion, based on whether Python performs the conversion automatically on its own, or whether a programmer explicitly requests it.

Type Conversion Implicit Type Conversion Explicit Type Conversion

Implicit Type Conversion

Implicit type conversion happens when Python automatically converts one data type into another on its own, without the programmer needing to request it directly. Python performs this kind of conversion when it can do so safely, without any risk of losing information, such as automatically converting a whole number into a decimal number when the two are combined in a calculation.

Example

videos = 12

average_length = 8.5

total_minutes = videos * average_length

print(total_minutes)

print(type(total_minutes))

Output

102.0

<class 'float'>

Here, videos is an integer and average_length is a float. When they are multiplied together, Python automatically converts the integer into a float before performing the calculation, since combining these two types safely requires the more general float type, and the result is a float rather than an integer. This entire conversion happens automatically, without any explicit instruction from the programmer.


Explicit Type Conversion

Explicit type conversion, sometimes called type casting, happens when a programmer directly requests that a value be converted from one type into another, using one of Python's built-in conversion functions, such as int(), float(), or str(). Unlike implicit conversion, explicit conversion is necessary whenever Python cannot or should not guess the intended conversion automatically.

Example

views_text = "5200"

views_number = int(views_text)

print(views_number + 800)

print(type(views_number))

Output

6000

<class 'int'>

Here, views_text is a string containing digits, which cannot be used directly in a mathematical calculation. The int() function explicitly converts it into an actual integer, after which it can be added to another number normally.

Example: Converting a Number to a String

subscribers = 60000

message = "CS Engineering Gyan has " + str(subscribers) + " subscribers"

print(message)

Output

CS Engineering Gyan has 60000 subscribers

In this example, the str() function explicitly converts the integer subscribers into a string, since Python does not allow a number to be directly combined with text using the plus operator without first converting it into a compatible type.


Comparing Implicit and Explicit Type Conversion

Aspect Implicit Type Conversion Explicit Type Conversion
Who Performs It Python automatically, on its own The programmer, using a conversion function
When It Happens When the conversion can be done safely without data loss Whenever the programmer needs a specific, deliberate conversion
Example Functions Used None; handled internally by Python int(), float(), str(), list(), and similar

Why Type Conversion Matters

Type conversion becomes especially important because Python, unlike some other languages, generally does not allow operations between incompatible types without an explicit conversion first. Attempting to directly add a number to a string, for example, results in an error rather than Python silently guessing what the programmer probably intended. Understanding when Python will convert values automatically, and when a conversion must be requested explicitly, helps avoid a very common category of beginner errors involving mismatched data types.


Advantages and Limitations of Python's Typing Approach

Advantages Limitations
Dynamic typing makes variables flexible and reduces boilerplate code. Type-related errors are only discovered while the program is actually running.
Implicit conversion handles common, safe situations automatically. Relying too heavily on implicit conversion can hide subtle bugs.
Explicit conversion gives programmers precise control when it is genuinely needed. Forgetting a required explicit conversion is a very common source of beginner errors.

Best Practices While Working With Variables and Type Conversion


Common Mistakes Beginners Make

Mistake Correct Practice
Trying to directly combine a number and a string using the plus operator. Explicitly convert the number to a string using str() before combining it with text.
Assuming input() returns a number when a user types digits. Remember that input() always returns a string, which must be explicitly converted if a number is needed.
Confusing dynamic typing with having no data types at all. Understand that every value in Python still has a definite type; only the variable name is flexible about which type it refers to.
Assuming int() and float() can convert any string successfully. Remember that converting a non-numeric string, like "hello", into a number will cause an error.

Frequently Asked Interview Questions

  1. What is a variable in Python?
    A variable is a name that refers to a value stored in memory, created automatically the moment a value is assigned to it.
  2. What does it mean that Python is dynamically typed?
    It means a variable's type is determined by its current value and can change if the variable is later reassigned to a different type of value.
  3. What is type conversion?
    Type conversion is the process of changing a value from one data type into another.
  4. What is implicit type conversion?
    Implicit type conversion is when Python automatically converts one data type into another without the programmer explicitly requesting it.
  5. What is explicit type conversion?
    Explicit type conversion is when a programmer directly converts a value from one type to another using a function like int(), float(), or str().
  6. Why does Python not allow adding a number and a string directly?
    Python does not allow this because combining incompatible types without a clear, deliberate conversion could easily hide programming mistakes.
  7. What type of value does Python's input() function always return?
    The input() function always returns a string, even if the user types numeric digits.
  8. How can you check a variable's current data type in Python?
    The built-in type() function returns the current data type of any variable or value passed to it.

Summary

Variables in Python are created simply by assigning a value to a name, and Python's dynamic typing model allows that same variable to hold different types of values at different points in a program, without ever needing an upfront type declaration. This flexibility is balanced by Python's strict handling of type conversion, which distinguishes between implicit conversion, performed automatically when it is safe to do so, and explicit conversion, requested deliberately by the programmer using functions like int(), float(), and str().

Understanding exactly when Python will convert a value automatically, and when a conversion must be requested directly, is one of the most practical skills for avoiding common beginner errors, especially when working with user input, which always arrives as text regardless of what the user actually types.

With variables and type conversion covered, you are now ready to explore operators in Python, learning how arithmetic, relational, logical, and assignment operators let you actually work with the values stored in your variables.


← Previous: Python Syntax Next: Operators in Python →

Home Visit Our YouTube Channel