Geek Slack

Introduction to Python
About Lesson



Python Variables


Python Variables

A variable in Python is a named storage location used to store data. Variables are used to store information that can be referenced and manipulated in a program. Unlike some other programming languages, Python is dynamically typed, meaning you do not need to declare the type of a variable when you create one.

1. Variable Assignment

To assign a value to a variable in Python, you simply use the assignment operator (=).

Example:

x = 5
y = "Hello, World!"
z = 3.14

2. Variable Names

Variable names in Python can contain letters, digits, and underscores. They must start with a letter or an underscore. Variable names are case-sensitive.

Example:

my_variable = 10
myVariable = "Hello"
_my_variable = 3.14

3. Variable Types

Python has several built-in data types, including integers, floats, strings, lists, tuples, dictionaries, and more. Variables can store values of any of these data types.

Example:

x = 5              # int
y = 5.5            # float
z = "Hello"       # string
a = [1, 2, 3]     # list
b = (1, 2, 3)     # tuple
c = {"name": "Alice", "age": 25}  # dictionary

4. Variable Reassignment

You can change the value of a variable by assigning a new value to it.

Example:

x = 5
print(x)    # Output: 5

x = 10
print(x)    # Output: 10

5. Variable Scope

The scope of a variable determines where in a program the variable can be accessed. In Python, variables have function scope by default, meaning they are accessible only within the function in which they are defined.

6. Constants

While Python does not have built-in support for constants, variables whose values should not change during the execution of a program are typically named using uppercase letters to indicate that they are intended to be constants.

Example:

PI = 3.14159
GRAVITY = 9.8

Conclusion

Variables are a fundamental concept in Python programming. They are used to store and manipulate data in a program. Understanding how to declare and use variables is essential for writing Python programs.

Join the conversation