top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python Variables

Introduction

Variables aid in data storage and manipulation. Specifically, in the context of Python, one of the most popular and versatile languages, Python variables play an integral role in  shaping efficient code structures. They allow developers to interact with data dynamically, making programs both robust and adaptable. In this tutorial, we'll explore the intricacies of Python variables, their types, rules, and their significance in writing superior Python scripts.

Overview

Python variables act as symbolic names that represent values stored in memory. Their dynamic nature, combined with Python's unique characteristics, offers a seamless coding experience. Unlike other programming languages, Python simplifies variable declaration and assignment, making it more accessible for beginners and a favorite for experts. The subsequent sections will delve into the core aspects of Python variables, unveiling their crucial contribution to data abstraction, memory optimization, and the overall flow of Python programs.

Define Variable in Python 

Python variables are fundamental to any program. So much so, that their role is not confined to mere data storage; they serve as dynamic labels and greatly influence how a program operates, its efficiency, and its readability. Let's delve deeper into understanding these essential components.

A Python variable can be imagined as a container or a storage box in a computer's memory. When we declare a variable, we reserve a space in the system's memory. Every time we reference this variable, we're essentially pointing to this memory location. Depending on the data we store, the size and the type of this container might vary. It could hold simple data like numbers and strings or more complex data structures like lists and dictionaries.

One of the standout features of Python variables is their role in memory optimization and program performance. They dynamically determine the memory space a program requires. By efficiently allocating and deallocating memory, they ensure the smooth and efficient operation of Python scripts, making the most out of the available resources.

Moreover, Python offers different types of variables to cater to varied programming needs. The three primary types are local, global, and instance variables. Local variables are confined to the function they are defined in. Global variables, on the other hand, are available throughout the program. Instance variables are tied to object instances and define attributes specific to them.

Lastly, the beauty of Python variables lies in their contribution to code readability and modular design. They allow for descriptive naming, making code more intuitive and understandable. Instead of dealing with raw memory locations, developers can use meaningful names, simplifying debugging and collaborative work. Plus, they foster data sharing across functions or modules, facilitating modular programming.

Example of Variables in Python  

Code:

# Assigning values to variables
name = "Alice"
age = 30
is_student = False
height = 1.75

# Printing the values of variables
print("Name:", name)
print("Age:", age)
print("Is Student:", is_student)
print("Height:", height)

# Modifying the value of a variable
age = age + 1
print("Updated Age:", age)

# Using variables in calculations
birth_year = 2023 - age
print("Birth Year:", birth_year)

# Concatenating variables in a string
greeting = "Hello, " + name + "!"
print(greeting)

Rules for Python Variables  

In Python, one of the significant advantages is its simplicity and efficiency when working with variables. Unlike many other languages, Python refrains from tedious processes or extensive rules. Instead, it offers an intuitive, user-friendly approach to declaration, naming, and assignment. This ease helps both beginners and seasoned professionals to write clean, effective, and efficient code. Let's dissect the fundamental rules governing Python variables.

  • Declaration and Assignment: One of Python's hallmark features is the absence of explicit variable declaration. A variable springs to life the moment it is assigned a value. This trait reduces redundancy and speeds up the coding process. Python looks at the value provided and automatically determines the variable's data type. This feature is in sharp contrast to many languages that require a distinct declaration phase.

  • Naming conventions: Every programming language has some naming conventions, and Python is no exception. A variable name in Python should start either with a letter or an underscore, ensuring it doesn’t begin with a number. This convention aids in avoiding confusion with values. Furthermore, the variable names can contain alpha-numeric characters and underscores (A-Z, a-z, 0-9, _). These conventions ensure readability and prevent syntactical errors.

  • Assignment: Python's commitment to streamlined coding is further witnessed in its assignment capabilities. Python enables developers to assign multiple variables simultaneously in a single line. This feature not only conserves time but also makes code more readable. An example to illustrate this is: a, b, c = 5, 3.2, “Hello”. Here, three variables are initialized in one swift line.

  • Keywords: To maintain the language's integrity and prevent unforeseen errors, Python has a list of reserved words known as "keywords". These keywords have special significance and are used to define the language's syntax and structure. As a best practice, variables should never adopt any of these reserved words as their names to avoid conflicts and unpredictable behavior.

Rule

Description

Naming

Initiate with a letter or underscore; use alpha-numeric characters.

Assignment

One-liners for multiple assignments.

Keywords

Bypass Python's reserved words.

Another Example of Assigning Variables in Python  

Code:

# Assigning values to variables
name = "John"
age = 25
height = 1.82
is_student = True

# Printing the values of variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)

# Modifying variables
age = age + 1
height = height - 0.1
is_student = False

# Printing the updated values of variables
print("Updated Age:", age)
print("Updated Height:", height)
print("Updated Is Student:", is_student)

# Assigning variables using other variables
year_of_birth = 2023 - age
greeting = "Hello, " + name + "!"
body_mass_index = 75 / (height ** 2)

# Printing the derived values of variables
print("Year of Birth:", year_of_birth)
print("Greeting:", greeting)
print("Body Mass Index:", body_mass_index)

Basic Example of Declaring and Initializing Variables  

Code:

# Variable initialization
name = "Alice"
age = 30
height = 1.75
is_student = False

# Printing initialized variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)

Example of Redeclaring Variables in Python  

Code:

# Variable initialization
name = "Alice"
age = 30

# Printing initial values
print("Name:", name)
print("Age:", age)

# Redefining variables
name = "Bob"
age = 25

# Printing updated values
print("Updated Name:", name)
print("Updated Age:", age)

# Changing variable types
age = "Twenty-five"
print("Changed Age Type:", age)

Example of Assigning Values to Multiple Variables

Code:

# Assigning values to multiple variables
name, age, height = "Alice", 30, 1.75

# Printing the values of variables
print("Name:", name)
print("Age:", age)
print("Height:", height)

Example of Assigning Various Values to Multiple Variables  

Code:

# Assigning different values to multiple variables
name, age, height = "Alice", 30, 1.75
city, country = "New York", "USA"

# Printing the values of variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("City:", city)
print("Country:", country)

Example of + Operator With Variables

Code:

num1 = 5
num2 = 3
sum_result = num1 + num2
print("Sum:", sum_result)  # Output: Sum: 8

The + operator is versatile in Python and adapts its behavior based on the types of operands involved. It performs addition for numerical values, concatenation for strings and sequences, and can be customized for user-defined types. Understanding the behavior of the + operator is important for writing clean and effective code.

Is it Possible to Use + for Different Data Types?  

Yes, the + operator can be used for different data types in Python, but the behavior of the operator depends on the specific data types involved. 

Code:

num_sum = 5 + 3.5  # Result: 8.5 (float)
print("Sum:", num_sum)

Working With Global and Local Variables  

Code:

# Global variable
global_var = 10

def function_with_local_variable():
    # Local variable
    local_var = 5
    print("Inside the function - Local Variable:", local_var)
    print("Inside the function - Global Variable:", global_var)

# Calling the function
function_with_local_variable()

# Accessing global variable outside the function
print("Outside the function - Global Variable:", global_var)

# Attempting to access local variable outside the function (will raise an error)
# print("Outside the function - Local Variable:", local_var)  # Uncommenting this line will raise an error

Global Keyword in Python  

Rules of global keyword  

  • To modify a global variable from within a function, you need to use the global keyword to declare the variable as global within the function's scope.

  • Without using the global keyword, if you assign a value to a variable inside a function, Python treats it as a local variable, even if a global variable with the same name exists.

Code:

global_var = 10  # This is a global variable

def modify_global_variable():
    global global_var  # Declare global_var as global inside the function
    global_var = 20    # Modify the global variable

modify_global_variable()
print("Global Variable:", global_var)  # Output: Global Variable: 20

Variable Types in Python  

In Python, variables are used to store data values. Each variable has a type that determines the kind of data it can hold. Here's a theoretical overview of some common variable types in Python:

  • Integer (int): Represents whole numbers without decimals. Example: age = 25

  • Floating-Point (float): Represents numbers with decimal points. Example: height = 1.75

  • String (str): Represents sequences of characters enclosed in single, double, or triple quotes. Example: name = "Alice"

  • Boolean (bool): Represents either True or False. Used for logical operations and conditional statements. Example: is_student = True

  • List: Represents an ordered collection of elements. Lists are mutable, meaning you can add, remove, or modify elements. Example: numbers = [1, 2, 3, 4, 5]

  • Tuple: Similar to a list, but immutable. Once created, elements cannot be changed. Example: point = (3, 5)

  • Dictionary: Represents a collection of key-value pairs. Keys are unique and used to access values. Example: person = {"name": "John", "age": 30}

  • Set: Represents an unordered collection of unique elements. Sets are useful for testing membership and performing set operations. Example: unique_numbers = {1, 2, 3, 4, 5}

  • NoneType (None): Represents the absence of a value or a null value. Often used as a default value. Example: result = None

  • Complex: Represents complex numbers with real and imaginary parts. Example: complex_number = 3 + 2j

  • Bytes and Bytearray: Represents sequences of bytes. Bytes are immutable, while byte array can be modified. Example: byte_data = b"hello"

Python's dynamic typing allows variables to change types as needed, and you don't need to declare the type explicitly. The interpreter determines the type based on the assigned value. This flexibility makes Python code concise and adaptable to various data types.

Here is an example of using different data types in Python:

Code:

# numberic variable
v = 123
print("Numeric data : ", v)

# Sequence Type variable
S1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(S1)

# Boolean variable
print(type(True))
print(type(False))

# Creating a Set with
# the use of a String variable
ss1 = set("upGradTutorial!")
print("\nSet with the use of String: ")
print(ss1)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'up', 2: 'Grad', 3: 'Tutorial!'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

Conclusion

Mastering Python variables isn't just about understanding a fundamental concept; it’s about ensuring optimal data manipulation and program efficiency. As technology keeps evolving, it’s vital to remain updated and always be on the learning path. While this tutorial provides a robust foundation on Python variables, diving deeper into the vast realm of Python will undoubtedly open up more doors.

For those passionate about upskilling, upGrad offers a multitude of advanced courses tailored for professionals. Embrace continuous learning and take a step towards a brighter future with upGrad.

FAQs

1. How to declare variable in Python without value? 

Utilize the None keyword. Example: var = None.

2, Can you give a variable name in Python example? 

Absolutely! Examples include myVariable123 and _tempVar.

3. How do you specifically Python declare variable type? 

Python typically infers types dynamically. However, for clarity, you can use type hints, such as x: int.

4. Is it true that keywords in Python can't be used as variable names? 

Correct! Python keywords are reserved and shouldn't be repurposed as variable names.

5. How is a variable in Python example different from other programming languages? 

Python is dynamically typed, deducing variable type at runtime, unlike statically-typed languages which require explicit type declaration.

Leave a Reply

Your email address will not be published. Required fields are marked *