If you are facing any issue, then join our Whatsapp and let us know. Join Now!

Python Variables Explained With Examples

Learn Python variables with clear examples! This guide explains naming rules, data types, scope, assignment, and best practices for beginners.
Python Variables Explained With Examples

Programming language basics mostly revolve around **variables**. So if you are new to Python, you must learn about Python variables because they are the basic concepts of any program. Here is a detailed tutorial on **Python Variables Explained** which will cover the basics and the advanced usage along with working examples.

What is a Variable in Python?

A variable in Python is a name that you give to a location in memory where you store a value. You can imagine it as a box with a label in which you can put your data. Then, you can get or change the data using the label (variable name).

Python variables, unlike C or Java variables, are **dynamically typed**. It means that you are not obliged to declare a variable's type; Python detects it automatically by the value you assign.

Creating a Variable in Python

To create a variable, just assign a value using the `=` operator.

name = "Alice"
age = 25
height = 5.8
is_student = True
print(name) # Output: Alice
print(age) # Output: 25
print(height) # Output: 5.8
print(is_student) # Output: True

The value `name` is a string `"Alice"`;

`age` is an integer `25`;

`height` is a floating point number `5.8`;

`is_student` is a boolean value `True`.

The Python interpreter figures out the data type of each variable by itself.

Variable Naming Rules in Python

You must not break these rules if you want to have error-free variable names:

Variable names may include alphabets (a-z, A-Z), numbers (0-9), and underscore (_).The first letter of the variable name is to be either an alphabet or underscore (not a digit).Variable names are case-sensitive (`Age` and `age` are different).Do not use Python reserved keywords (such as `for`, `if`, `while`, `class`, etc.).

Best Practices for Variable Names (PEP 8 Style Guide)

Use **snake_case** for variable names: `user_name`, `total_price`

Be descriptive: `customer_age` is better than `ca`

Avoid single-letter names except in loops (like `i`, `j`)

Use meaningful names to improve code readability

Good examples:

name = "Alice"
first_name = "John"
last_name = "Doe"
email_address = "john.doe@example.com"
total_score = 95.5

Bad examples:

1name = "John" # Starts with number → Error
class = "Python" # Reserved keyword → Error
my-var = "test" # Hyphen not allowed → Error

Data Types in Python Variables

Python has lots of built-in data types. Here are the most commonly used ones with examples:

1. Integer (`int`)

Integers are whole numbers without a decimal point including negative numbers.
count = 100temperature = -15population = 7800000000

2. Float (`float`)

Floats represent real numbers: numbers that have a decimal point.
price = 19.99pi = 3.14159gravity = 9.8

3. String (`str`)

String is a data type used to represent text.
greeting = "Hello, World!"city = 'New York'message = """This is amulti-line string"""

4. Boolean (`bool`)

This data type has only two values: True and False.

is_active = Truehas_permission = False

5. NoneType (`None`)

Used to indicate that a variable has no value.
result = Nonemiddle_name = None # Person has no middle ​‍​‌‍​‍‌​‍​‌‍​‍‌name

​‍​‌‍​‍‌​‍​‌‍​‍‌6. List, Tuple, Dictionary, Set (Complex Types)

A list is a collection that is ordered and changeable. It allows duplicate members.
fruits = ["apple", "banana", "orange"]
A tuple is a collection which is ordered and unchangeable. It allows duplicate members.
coordinates = (10.5, 20.3)
A dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
student = {
 "name": "Emma",
 "age": 20,
 "grade": "A"
}

A set is a collection which is unordered and unindexed. No duplicate members.

unique_numbers = {1, 2, 3, 3, 4} # Output: {1, 2, 3, 4}

Type Checking and Conversion

If you want to know what data type a variable is, you can do type(var). To change the type, use conversion functions like int(), float(), str().

x = 10
print(type(x)) # <class 'int'
y = "50"
y = int(y) # Convert string to integer
print(type(y)) # <class 'int'
z = 3.14
z = str(z) # Convert float to string
print(z) # "3.14"

**Warning**: Moreover, not every conversion is possible. Example: `int("hello")` will give an error.

Reassigning and Dynamic Typing

One of Python's features is dynamic typing, meaning you can reassign variables to different types.

score = 85 # int
print(score)
score = "Eighty Five" # now a string
print(score)
score = 92.5 # now a float
print(score)

The variable score changed types three times!

Variable Scope in Python

Every variable has a scope, which means the regions of the program where they are accessible.

Local Variables

Local variables are those defined within a function and can only be used in that function.

def greet():
message = "Hello!" # Local variable
print(message)
greet()
# print(message) # Error: NameError

Global Variables

Global variables are declared outside of functions and thus are accessible everywhere in the program.

global_greeting = "Hi there!"
def say_hello():
print(global_greeting)
say_hello() # Output: Hi there!
print(global_greeting) # Also works

Use the `global` keyword to alter global variables within a function.

Constants in Python

There is no real constant in Python, but as a rule of thumb, we name in **UPPERCASE** the values/variables that are not supposed to be changed.

I = 3.14159
MAX_USERS = 100
API_KEY = "abc123xyz"
Multiple Assignment

Python gives you the option to assign multiple variables at once.

a = 10
b = 20
c = 30
x, y, z = 100, 200, 300
p = q = r = 0

Besides that, swapping values is very straightforward:

a = 5
b = 10
a, b = b, a # Swap!
print(a) # 10
print(b) # 5
Deleting​‍​‌‍​‍‌​‍​‌‍​‍‌ Variables

One can use the command del to free a variable from memory.

temp = 42
del temp
# print(temp) # NameError: name 'temp' is not defined

Conclusion

Grasping Python variables is the stepping stone for carrying out any programming task using Python. They are the means through which you can keep, handle, and organize the data.

Thanks to features like dynamic typing, easy naming, and multiple assignments, working with variables is as natural and as easy as breathing for newcomers.

Summary:

  • Variables come into being when you use `=`
  • You don't have to announce types
  • Use naming conventions to have a neat code
  • Always be aware of the scope and reassignment

Get in a habit of writing short scripts that involve all types of variables. Use them so often that it will all become second nature to ​‍​‌‍​‍‌​‍​‌‍​‍‌you!

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.