Table of Content

Python Variables and Data Types

python-data-types

Introduction

Variables and data types act as the backbone of any programming language. They play a crucial role in storing data and manipulating data, and they are fundamental building blocks for writing effective and efficient code.

Variables serve as named containers for data in the memory, while data types define the kind of data these variables can hold in the memory.

In this blog, we try to give a detailed explanation of Python variables, rules for naming variables, data types, and best practices to help you write clean and readable Python code.

Understanding Variables in Python

A variable is a representative name that refers to a memory location where data is stored. Variables help programmers manage data in an organized and reusable way.

Unlike other programming languages, Python does not require you to declare a variable’s data type explicitly. Rather, Python dynamically assigns the data type based on your assigned value.

In Python, we give descriptive comments with the # symbol.

Example:-

python variables and data types

This is known as dynamic typing which makes it convenient to work with different data types without explicit declaration as in other programming languages.

Why Do We Use Variables?

  1. Data Storage: Variables store values that can be used and manipulated throughout the program as per the requirements.
  2. Reusable: Variables can allow you to reuse values throughout your program without typing them again and again each time.
  3. Comprehensive: Descriptive variable names make code easier to read and understand the purpose of usage.
  4. Dynamic Nature: By using variables, you can write programs that handle different inputs and produce varied outputs.
  5. Flexible: Variables make it easy to change values without modifying multiple lines of code.

Rules For Naming Variables in Python

  • The variable name can start with a letter or an underscore (_).
    Example:-
    Total =10,  _win=20
  • Spaces and special characters are not allowed. It can only accept letters, numbers, and underscores.
  • Case-sensitive nature: Uppercase and lowercase names are treated differently. Name and name are considered as different variables that can hold values separately.
    Example: –
    A = 10
    a = “Alex”

Examples of Variable Names:

  • Valid Variable Name: _age, Candidate_Name, total
  • Invalid Variable Name: 1name, first-name, total amount

Naming Conventions

There are various types of naming conventions used in Python programming. However, the most widely used naming convention for variables is snake_case, wherein all the letters are in lowercase and separated by an underscore. camelCase naming convention is also used at times, it is less common though wherein the first letter is in lowercase and the subsequent word starts with an uppercase letter.

Another most commonly used naming convention is PascalCase in which each word starts with an uppercase letter. This is generally used for naming classes in Python programs.

Example:-

#snake_case
candidate_name = "Jane"
total_cost = 1000

#camelCase
firstName = “John”
totalCost = 1000

#PascalCase
class CandidateInformation:
    pass

Tip- By adhering to a consistent naming convention throughout the program, we can enhance and improve the code’s readability and maintainability significantly.

In Python, you can assign values to multiple variables in one line.

Example:-

x, y, z = “Monday”, “Tuesday”, “Wednesday”
print(x)
print(y)
print(z)

#Output-
Monday
Tuesday
Wednesday

You can also assign the same value to multiple variables in one line.

Example:-

x= y = z = “Sunday”
print(x)
print(y)
print(z)

#Output-
Sunday
Sunday
Sunday

Overview of Python Data Types

Data type labels the kind of value a variable can hold. Python provides a huge range of in-built data types, thereby making it a programmer-friendly versatile language for various applications. These data types can be classified into various categories such as the following:

Core Categories of Data Types in Python:

  • Numeric Types: Integers, floats, and complex numbers.
  • Text Types: Strings.
  • Boolean Types: True or False values.
  • Sequence Types: Lists, tuples, and ranges.
  • Set Types: Sets and frozen sets.
  • Mapping Types: Dictionaries.

Key Python Data Types Explained

  1. Numeric Types: In Python, three types of numeric type values are used:
    int: Represents whole numbers.
    Example:- age = 20
    float: Represents decimal numbers.
    Example:-
    pi = 3.14
    complex: Represents complex(imaginary) numbers.
    Example:-
    x = 2 + 3j
    These are generally used for making mathematical computations.
  2. String Type: A string is a sequence of characters enclosed in either single or double quotes.
    Example:-
    message = “Hello, World!”
    Strings in Python are versatile and come with many built-in methods for manipulation.
  3. Boolean Type: Boolean values represent logical True or False.
    Example:-
    is_active = True
    is_loggedin = False
    Boolean data type is commonly used in conditional statements and loops.
  4. Sequence Types:
    List: It is an ordered, mutable collection.
    Example:-
    fruits = [“apple”, “banana”, “mango”]
    fruits.append(“orange”)
    print(fruits)#Output: [‘apple’, ‘banana’, ‘mango’, ‘orange’]

    Tuple:
    It is an ordered, immutable collection.
    Example:-
    coordinates = (10, 20)
    print(coordinates[0])#Output: 10

    Range: It is a sequence of numbers.
    Example:-
    numbers = range(5)
    print(list(numbers))

    #Output: [0,1,2,3,4]

  5. Set Types
    Set: A set is a collection of unordered unique elements.
    Example:-
    unique_numbers = {1, 2, 3}
    unique_numbers.add(4)
    print(unique_numbers)#Output: {1,2,3,4}
    Sets are useful for the removal of duplicate data from a collection of data.
  6. Mapping Types
    Dictionary: It is a collection of key-value pairs.
    Example:-
    candidate = {“name”: “Star”, “age”: 30}
    print(person[“name”])# Output: StarDictionaries are ideal for showcasing structured data.

Type Conversion in Python

Python provides in-built functions to convert data from one type to another: int(), float(), str(), bool(), list(), etc.

Example:-

x = "42"
y = int(x) # Converts string to integer
print(y) 
#Output: 42

Tip- Type conversion is useful when working with different data types in the same program. Always ensure you are converting data types correctly to avoid runtime errors.

Mutable vs. Immutable Data Types

In Python, data types can be categorized as mutable or immutable:

  1. Mutable: In this, values can be modified after the assignment. Examples: Lists, dictionaries, and sets.
  2. Immutable: In this, values cannot be changed after the assignment. Examples: Strings, tuples, integers, floats.

Why This Matters?

It is important to understand the distinction between mutable and immutable data types for debugging and performance optimization.

For example, modifying an immutable object creates a new object in memory, whereas modifying a mutable object does not, hence optimizing memory management.

Example:-

Lists are mutable
# Mutable 
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits) 
Output: ["apple", "banana", "mango"]

Strings are immutable
# Immutable 
name = "John"
name = name + " Smith"
print(name) 
Output: "John Smith"

Common Mistakes and How to Avoid Them

  1. Reassigning variables with incorrect data types: Always make sure you use consistent data types while performing various operations.
  2. Forgetting quotes when using strings: Either a single quote or double quotes are used to represent a string data type.
    name = John # Incorrect
    name = ‘John’ or “John” # Correct
  3. Confusing mutable and immutable data types: Be careful of the data type being used and whether a data type can be modified or not.
  4. Overriding in-built keywords: Avoid using keywords as variable names such as append, str, or class for your variables.

Solutions/ Recommendations:

  • Using a descriptive variable name makes it easier to understand the functional meaning.
  • Always make sure to test and debug the program code using commands such as print() and type() to check values.
  • Usage of a consistent naming convention throughout the program.

Debugging and Testing Variable Assignments

In all programming languages, it is important to make the code error-free hence Debugging becomes an integral part of programming. In Python programming, there are basic functions like print() and type() to verify variables and what value they hold during the developmental phase.

Example:-

value = 30
print(value) 
# Output: 30
print(type(value)) 
# Output: <class 'int'>

Tip- It is always a good practice to dry run or test your code with data to ensure that the variable assignments, operations, and functions behave as expected.

Conclusion

In depth understanding of these basics not only helps in writing clean and efficient code but also sets the foundation for developing complex applications and tackling more complex computational challenges.

Mastering how to properly declare and manage variables, handle different data types, appropriate naming conventions, and debug effectively can help you become a more confident and capable Python developer.

Are you ready to master Python fundamentals? Join our Python Programming Course for beginners to deepen your skills and unlock expert insights and hands-on coding projects!

If you found this blog helpful, be sure to bookmark it and share it with others.

FAQ

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast

Don't just learn... Master it!

With expert mentors, hands-on projects, and a community of learners, we make skill-building easy and impactfull

Related Blog

6

Min Read

From colour schemes to accessibility, learn how to apply colour theory...
6

Min Read

From colour schemes to accessibility, learn how to apply colour theory...

Related Blog

Scroll to Top