Python Variables and Data Types

In Python, variables serve as essential components that enable programmers to efficiently store, handle, and manipulate data. A variable in Python can be understood as a symbolic identifier linked to a memory address where data resides. In contrast to statically typed languages like C or Java, Python employs dynamic typing, which means that variables do not need explicit type annotations; instead, their type is determined during runtime according to the value assigned.

Let’s examine a straightforward example of how to declare a variable in Python.

Example

Example

# Variable 'a' stores the integer value 17

a = 17

# Variable 'name' stores the string "Daisy"

name = "Daisy"

print(a)

print(name)

Output:

Output

17

Daisy

Explanation:

In this illustration, we have established a variable named 'a' that holds an integer value of 17. Additionally, we have created another variable called 'name' and assigned it the string 'Daisy'. It is noteworthy that we did not explicitly specify their types; nonetheless, Python has automatically determined their data types at runtime.

Rules and Naming Conventions for Python Variables

Python follows certain rules for naming variables:

  • We can define a variable name using alphabets (A-Z or a-z), numbers (0-9), and underscore (). (Example: varone, var1)
  • The names of the variables can start with an alphabet or underscore, but not with a number. Valid: var1 Invalid: 1var
  • No Spacing is allowed. Valid: var_one Invalid: var one
  • Variable names are case-sensitive. (fruit, Fruit, and FRUIT are three different variables)
  • We cannot use reserved Python keywords as variable names (Example: class, def, return, etc.)
  • Valid: var1
  • Invalid: 1var
  • Valid: var_one
  • Invalid: var one
  • Assigning Values to Variables

There are multiple methods for assigning values to a variable.

Basic Assignment

In Python, we can assign a value to a variable using the "=" operator.

Let’s consider a straightforward illustration that demonstrates how to allocate a value to a variable in Python.

Example

Example

# assigning 82 to var_one

var_one = 82

print(var_one)

Output:

Explanation:

In the preceding illustration, we established a variable named var_one and allocated an integer value of 82 to it through the use of the "=" assignment operator.

Dynamic Typing

In Python, variables are dynamically typed, which indicates that a single variable can hold values of various types.

This is an illustration demonstrating the functionality of dynamic typing in Python.

Example

Example

# dynamic typing

var_one = 21    # integer

print(var_one)

var_one = 'logicpractice'  # string

print(var_one)

Output:

Output

21

logicpractice

Explanation:

In this illustration, we have set up a variable named varone by assigning it an integer value of 21. Given that Python employs dynamic typing for its variables, we have subsequently assigned a new value, 'logicpractice' (a string), to varone.

Multiple Assignments

In Python, it is possible to assign values to several variables simultaneously within a single line of code.

Assigning Same Value to Multiple Variables

In Python, it is permissible to assign identical values to several variables simultaneously within a single line of code.

Example

Example

# assigning same value to multiple variables

var_1 = var_2 = var_3 = 182

print("Variable 1:", var_1)

print("Variable 2:", var_2)

print("Variable 3:", var_3)

Output:

Output

Variable 1: 182

Variable 2: 182

Variable 3: 182

Explanation:

In the example presented above, we have allocated the integer value of 182 to several variables, including var1, var2, and var_3, by utilizing the "=" operator.

Assigning Different Values to Multiple Variables

Python additionally enables us to assign various values to several variables at the same time. This approach makes the code more succinct and enhances its readability.

Example

Example

# assigning different values to multiple variables

var_1, var_2, var_3 = 182, 'ExampleTech', '19.5'

print("Variable 1:", var_1)

print("Variable 2:", var_2)

print("Variable 3:", var_3)

Output:

Output

Variable 1: 182

Variable 2: ExampleTech

Variable 3: 19.5

Explanation:

In the preceding illustration, we have established several variables such as var1, var2, and var_3, assigning distinct values to each within a single line of code.

Type Casting a Variable

Type casting refers to the method of transforming a value from one data type to another. Python often performs these conversions automatically in certain situations. Nevertheless, there are several built-in functions available, such as int, float, str, among others, that facilitate the process of type casting.

Let’s explore an illustration that demonstrates the functioning of type casting in Python.

Example

Example

# type casting

var_1 = 9     # int

# implicit type casting

var_2 = var_1 / 4

print(var_2)  # int -> float

# explicit type casting

var_2 = int(var_2)

print(var_2)  # float -> int

Output:

Output

2.25

2

Explanation:

In the example provided, we initialized a variable of type 'int' and executed a straightforward mathematical division, which resulted in a floating-point number that was subsequently stored in another variable. Here, Python has automatically designated this new variable as a 'float' type.

In the following example, we have utilized the int function to explicitly transform the 'float' variable into an 'int' variable.

Getting the Type of Variable

In Python, we have the capability to ascertain the data type of a variable. The language offers a built-in function known as type that delivers the type of the object provided to it.

Below is an illustration demonstrating how to utilize the type function in Python.

Example

Example

# determining the type of the variables

# initializing variables of different data types

var_w = 18            # int

var_v = 82.6          # float

var_x = 'Example' # string

var_y = True          # boolean

var_z = [4, 1, 8, -5] # list

# printing their types using type() function

print(var_w, '->', type(var_w))

print(var_v, '->', type(var_v))

print(var_x, '->', type(var_x))

print(var_y, '->', type(var_y))

print(var_z, '->', type(var_z))

Output:

Output

18 -> <class 'int'>

82.6 -> <class 'float'>

C# Tutorial -> <class 'str'>

True -> <class 'bool'>

[4, 1, 8, -5] -> <class 'list'>

Explanation:

In the preceding example, we introduced several variables that encompass a variety of data types. Subsequently, we utilized the type function to obtain the type of each variable that was provided to it.

Scope of a Variable

In Python, the term "scope" refers to the context in which a variable can be accessed within the code. Variables that are defined outside of any function possess a global scope, meaning they can be accessed from anywhere in the program. Conversely, variables that are defined within the confines of a function have a local scope, which restricts their accessibility to that particular function alone.

Let's examine an illustration that demonstrates the various scopes of variables in Python.

Example

Example

# different scopes of variables

# global variable

var_x = 15

# defining a function to add numbers

def add_num():

  # local variable

  var_y = 12

  print(f'{var_x} + {var_y} = {var_x + var_y}')

# calling the add_num() fuction

add_num()

# printing details

print("var_x =", var_x)

# print("var_y =", var_y)   # accessing local variable outside the scope will raise error

Output:

Output

15 + 12 = 27

var_x = 15

Explanation:

In the preceding example, a variable named varx has been initialized with an integer value of 15. Subsequently, a straightforward function called addnum has been created to display the sum of two numbers. Within this function, an additional variable, vary, has been initialized with an integer value of 12. Because this variable is declared within the function, its scope is confined to that function. In contrast, the variable varx, which is defined outside of the function, is accessible throughout the entirety of this program.

Attempting to access a variable that resides within a local scope from outside its defining function will result in a NameError being raised.

Object Reference in Python

In Python, variables act as references to objects located in memory. This indicates that they do not hold the actual data directly; rather, they contain a reference to that specific object.

When we allocate a value to a variable, we are effectively linking the name of that variable to a specific object stored in memory.

To grasp the concept of object referencing, let's consider an illustrative example.

We will begin by assigning the integer 9 to a variable named p, as illustrated in the following example:

In this instance, Python generates an object to encapsulate the value 9 and assigns the variable p to reference that object.

We will proceed to create an additional variable named q and set its value to that of p, as demonstrated in the following example:

In this instance, we have allocated the variable q to share the same reference as the variable p. Consequently, both variables, p and q, now point to the identical object.

We will proceed to assign a new value, 'Example', to the variable p, as illustrated below:

Example

p = 'Example'

In this case, we have allocated the string value 'Example' to the variable p. Upon executing this assignment, Python generates a new object that encapsulates 'Example' and directs the variable p to point to this newly instantiated object. On the other hand, the variable q continues to point to the integer 9.

At this point, we will allocate a value to the variable, q, as demonstrated in the syntax below:

Example

q = 'Hello'

The statement provided enables Python to generate a new object that contains the string value 'Hello', with the variable q now pointing to this object. Consequently, the object that held the value 9 is left without any references, rendering it eligible for garbage collection.

Deleting a Variable

Python includes a keyword called del, which enables us to eliminate a variable from the namespace.

Let’s examine a straightforward illustration that demonstrates the functionality of the del keyword in Python.

Example

Example

# deleting a variable

# initializing a variable

var_x = 15

print(var_x)

# using the del keyword to delete the variable

del var_x

# print(var_x)  # this line will raise Error as the variable we are trying to access is deleted

Output:

Explanation:

In the preceding illustration, the del statement has effectively removed the variable varx from memory. Consequently, if we attempt to reference varx, a NameError will be triggered, as the variable is no longer present within the program.

Conclusion

In this instructional guide, we have explored the fundamental concepts surrounding variables in Python. Grasping the role of variables in Python is crucial, as they serve as the cornerstone for data storage and manipulation. Thanks to Python's attributes such as dynamic typing, adaptable assignment, and straightforward syntax, managing variables is both effective and efficient. Gaining proficiency in topics such as variable scope, type conversion, and object references will enable us to craft cleaner and more robust code in Python.

Python Variables - MCQs

  1. Which of the following is a Python variables feature?
  • Variables require explicit type declaration
  • Python is statically typed
  • Variables are memory inefficient
  • Python is dynamically typed

Response: d) Python utilizes dynamic typing

  1. What will be the result produced by the following code?
  2. Example
    
    a, b, c = 10, 20, 30
    
    print(a, b, c)
    
  • 10 20
  • 10 20 30
  • a b c
  • Error
  1. A variable is accessible only within the function; how can it be defined?
  • Global variable
  • Local variable
  • Static variable
  • Instance variable
  1. What does the global keyword do in Python?
  • It defines a variable globally
  • It modifies a global variable inside a function
  • It makes a variable available only inside a function
  • It deletes a variable from memory

Response: b) It alters a global variable from within a function

  1. What outcome does the following code produce?
  2. Example
    
    x = "10"
    
    y = int(x)
    
    print(y, type(y))
    
  • 10 <class 'str'>
  • 10 <class 'int'>
  • Error
  • None <class 'int'>

Input Required

This code uses input(). Please provide values below: