Table of contents
1.
Introduction
2.
What are Python variables?
3.
Example of Variables in Python
4.
Rules for Python Variables
4.1.
Start with a letter or underscore
4.2.
Case sensitive
4.3.
Avoid Python keywords
4.4.
Keep it readable
5.
Variables Assignment in Python
6.
Global and Local Python Variables
6.1.
Global Variables
6.2.
Local Variables
7.
Global Keyword in Python
8.
Rules of Global Keyword
8.1.
Declare Before Use
8.2.
Global Variables Must Exist
8.3.
One Global Statement
8.4.
Assignment After Declaration
9.
Variable Types in Python
9.1.
Integers
9.2.
Floats
9.3.
Strings
9.4.
Booleans
9.5.
Lists
10.
Built-in Python Data Types
10.1.
Numbers
10.2.
Strings
10.3.
Lists
10.4.
Tuples
10.5.
Dictionaries
10.6.
Booleans
11.
Object Reference in Python
12.
Maximum Possible Value of an Integer in Python
13.
Frequently Asked Questions
13.1.
How to Define Variables in Python?
13.2.
What are the 3 Variables in Python?
13.3.
What are the 3 Components of a Variable in Python?
13.4.
What Type is a Variable in Python?
14.
Conclusion
Last Updated: Dec 17, 2024
Easy

Python Variables

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python variables are used to store data values that can be referenced and manipulated within a program. A variable in Python does not require explicit declaration of its type, as Python is dynamically typed. You can assign values to a variable by simply using the assignment operator (=), and the variable will automatically hold the assigned value of the corresponding type.

Python Variable

What are Python variables?

In Python, variables are used to store data values that can be referenced, modified, and manipulated throughout a program. A variable in Python does not require an explicit declaration of its type, as Python is a dynamically typed language. This means you can assign a value to a variable without specifying its type, and Python will automatically determine the type based on the value.

Example of Variables in Python

Let's start with how to create a variable in Python. It's like giving a name to something so you can call it later. For example, if you have a number 10 and you want to remember it for later, you can create a variable named my_number and store 10 in it. Here's how you do it:

my_number = 10


Now, my_number is a variable that holds the value 10. You can use this variable in your code instead of writing 10 every time. Let's say you want to add 5 to this number and print the result. You can do it like this:

my_number = 10
new_number = my_number + 5
print(new_number)


This will show 15 when you run the code. We created a variable my_number, gave it a value of 10, and then made a new variable new_number to hold the result of my_number + 5. Finally, we printed new_number to see the result.

Rules for Python Variables

When naming variables in Python, there are a few simple rules to follow. These rules help make sure your code is easy to read and doesn't cause errors.

Start with a letter or underscore

Variable names must start with a letter (a-z, A-Z) or an underscore (_). For example, username or _username are valid, but 1username is not.

Only letters, numbers, and underscores: After the first character, you can use letters, numbers, and underscores. So, user_name1 is okay, but user-name (with a hyphen) is not because Python thinks you want to subtract name from user.

Case sensitive

In Python, uppercase and lowercase letters are different. So, Book and book would be two different variables.

Avoid Python keywords

Python has some reserved words that you can't use as variable names because Python uses them for other things. For example, print or if cannot be used as variable names.

Keep it readable

Choose names that make sense and describe what the variable holds. For example, user_age is better than just ua, because it's clear what it means.

Here's an example to show you right and wrong variable names:

# Good variable names
my_variable = 10
_variable2 = "Hello"
var3 = 3.14
# Bad variable names (These will give errors)
2var = 10          # Starts with a number
my-variable = 20   # Has a dash instead of an underscore
for = "Python"     # Uses a Python keyword

Variables Assignment in Python

Assigning a variable in Python is like putting a label on a box. This label helps you remember what's inside the box without opening it. In Python, you give a value to a variable using the equal sign =. Here's how it works:

x = 5


In this example, x is a variable, and we've assigned it the value 5. Now, whenever you use x in your code, Python knows you're talking about the number 5.

You can also change the value of a variable later on. It's like replacing the contents of your labeled box. For example:

x = 5
x = x + 2


After this, x doesn't hold 5 anymore. It now holds 7 because we added 2 to the original value of x.

You can even assign the same value to multiple variables in one line, like this:

a = b = c = 10


Now, a, b, and c all have the value 10. It's like having three boxes, all labeled with the same content.

Remember, the variable name goes on the left side of the =, and the value you want to store goes on the right side.

Global and Local Python Variables

In Python, where you create a variable can affect where it can be used. This is about whether a variable is "global" or "local". Let's break it down:

Global Variables

These are created outside of functions and can be used both inside and outside of functions. It's like a public announcement that everyone can hear, both inside and outside a room.

Local Variables

These are created inside functions and can only be used inside those functions. It's like a secret you share in a small group; only the people in the group know the secret, and it doesn't leave the room.

Here's an example to show you how it works:

# Global variable
x = "I am outside the function"
def myFunction():
    # Local variable
    y = "I am inside the function"
    print(y)
myFunction()
# This will print the local variable y
# But if we try to print y outside the function, it will give an error
# print(y)  # This line would give an error because y is not known here
# However, we can print x anywhere because it's global
print(x)

In this example, x is a global variable, so we can use it to print its value both inside and outside the function. But y is a local variable created inside myFunction(), so it only works inside that function. Trying to print y outside the function would not work and give an error because outside the function, y is unknown.

Global Keyword in Python

In Python, if you want to change a global variable inside a function, you need to use the global keyword. It's like telling the function, "Hey, I'm going to use the global variable, not a local one." Without global, Python would think you're making a new local variable inside your function.

Here's how you do it:

# Global variable
x = 10
def myFunction():
    global x  # Tell Python we want to use the global x
    x = 20    # Change the value of the global x
myFunction()
print(x)  # This will print 20, not 10


In this example, we have a global variable x with a value of 10. Inside myFunction(), we use global x to tell Python that we want to use the global x, not create a new local one. Then, we change x to 20. When we print x outside the function, it shows 20 because we changed the global x, not a local one.

Remember, use global carefully. Changing global variables can make your code hard to understand and lead to mistakes if you're not careful.

Rules of Global Keyword

When you use the global keyword in Python, there are some simple rules to keep in mind. It's like when you're playing a game, and there are specific rules on how to move your pieces. Here are the rules for using global:

Declare Before Use

You need to declare a variable as global inside a function before you use it. This tells the function to use the variable defined outside the function.

Global Variables Must Exist

When you declare a variable as global inside a function, that variable should already exist outside the function. It's like you can't talk about a friend in a story if you haven't introduced them yet.

One Global Statement

You can declare multiple global variables in a single global statement. Just separate them with commas, like this:

global x, y, z

Assignment After Declaration

After declaring a variable as global, you can change its value. This change will affect the variable outside the function.

Here's a simple example to show these rules in action:

x = 10  # Global variable
def myFunction():
    global x  # Declare x as global
    x = 20    # Now, this changes the global x
myFunction()
print(x)  # This will print 20 because the global x was changed in the function


In this example, x is a global variable. Inside myFunction(), we declare x as global and then change its value to 20. This changes the x outside the function, so when we print x, it shows 20.

Variable Types in Python

In Python, variables can store different types of data. It's like having different kinds of containers for different items. Here are some common types:

Integers

These are whole numbers, without decimals. For example, 5, -3, and 42 are integers. You can use them for counting or doing math.

Floats

These are numbers with decimals. They're used when you need more precision, like 3.14, -0.001, and 2.0.

Strings

These are sequences of characters, like words or sentences. You put them in quotes. For example, "hello", 'Python is fun', and "123" are all strings.

Booleans

These represent truth values and can be either True or False. They're often used in making decisions in code.

Lists

A list is a collection of items. It's like a shopping list where you can keep adding items. For example, [1, 2, 3] or ['apple', 'banana', 'cherry'].

Here's a quick example to show these types:

my_integer = 10         # Integer
my_float = 3.14         # Float
my_string = "Hello"     # String
my_boolean = True       # Boolean
my_list = [1, 2, 3]     # List


Each variable holds a different type of data, and you can use them in various ways depending on what you need to do in your code.

Built-in Python Data Types

Python comes with a set of ready-to-use data types that help you work with different kinds of information in your code. It's like having a toolbox where each tool serves a different purpose. Here's a look at some of the most common built-in data types in Python:

Numbers

This type includes both integers (whole numbers) and floats (numbers with decimals). You use them for calculations and storing numerical values.

Strings

These are sequences of characters, used for storing text. You can create a string by putting characters between single or double quotes.

Lists

Lists are used to store multiple items in a single variable. They are created using square brackets, and you can mix different types of items in one list.

Tuples

Similar to lists, but you can't change them once they're created. They're useful for fixed collections of items.

Dictionaries

These store data as key-value pairs. It's like a real dictionary where you look up a word (the key) to get its definition (the value).

Booleans

This type has only two values: True and False. Booleans are often used in conditions to help decide what your code should do next.

Here's an example showing how to use these data types:

my_number = 5                 # Number (integer)
my_float = 3.14               # Number (float)
my_string = "Hello, world!"   # String
my_list = [1, "apple", 3.14]  # List
my_tuple = (1, 2, 3)          # Tuple
my_dict = {"name": "John", "age": 30}  # Dictionary
is_sunny = True               # Boolean


Each of these data types helps you handle different kinds of data in your programs, making Python a flexible and powerful language for coding.

Object Reference in Python

In Python, when you make a variable, you're actually creating a reference to an object. Imagine a variable as a name tag stuck to a box. The box is the object, and the name tag is the variable that refers to it. This is important because in Python, different variables can refer to the same object, which can be handy but also surprising if you're not expecting it.

Here's a simple way to see this in action:

a = [1, 2, 3]  # 'a' refers to a list object [1, 2, 3]
b = a          # Now 'b' also refers to the same list object as 'a'
b.append(4)    # We add a new element to the list 'b' refers to
print(a)       # When we print 'a', it shows [1, 2, 3, 4]


In this example, a and b both refer to the same list. So, when we change the list through b, the change also shows up when we look at a. This happens because a and b are just two name tags for the same box.

Maximum Possible Value of an Integer in Python

In Python, there is no fixed maximum value for integers. Python's int type is arbitrary-precision, meaning it can grow as large as the available memory allows. Unlike other programming languages, where integers are typically bound by fixed bit sizes (e.g., 32-bit or 64-bit limits), Python can handle very large integers without overflow.

For example:

large_number = 10**100  # A number with 101 digits
print(large_number)

 

Python will automatically adjust the storage size to accommodate large numbers, and the sys.maxsize in Python can give the maximum value for integers used in some contexts, but there is no strict limit for int.

Frequently Asked Questions

How to Define Variables in Python?

To define a variable in Python, simply assign a value to a name using the assignment operator (=), without specifying its type.

What are the 3 Variables in Python?

Python uses local, global, and nonlocal variables. Local variables are defined within a function, global variables are defined outside, and nonlocal variables are used in nested functions.

What are the 3 Components of a Variable in Python?

A variable in Python consists of the name, the value it holds, and the type of data it stores, which is dynamically determined by the value.

What Type is a Variable in Python?

In Python, a variable's type is dynamically assigned based on its value, meaning its type can change during runtime based on the assigned data.

Conclusion

In this article we got to know variables in Python and why it is a big step if you're starting to code. We talked about how to make them, name them, and some special rules about using them. It's like learning to keep track of your stuff by labeling it. The more you practice with variables, trying out different things, the easier it gets. Just keep using them in your code, see how they work, and you'll get better at it. Keep coding and having fun with it!

Live masterclass