
PYTHON — Define Variables in Python
Computer science is no more about computers than astronomy is about telescopes. — Edsger W. Dijkstra
In Python, variables are used to store data values. These variables can be of different types such as integers, floats, strings, and so on. Let’s take a look at how to define and use variables in Python.
Defining Variables
To define a variable in Python, you simply assign a value to a name using the equal sign =. Here are a few examples:
# Integer variable
age = 25
# Float variable
pi = 3.14
# String variable
name = "Alice"
# Boolean variable
is_student = TrueIn the code above, age, pi, name, and is_student are the names of the variables, and 25, 3.14, "Alice", and True are the values assigned to them.
You can also assign the same value to multiple variables at once:
x = y = z = 10Here, all three variables x, y, and z are assigned the value 10.
Using Variables
Once a variable is defined, you can use it throughout your code. For example:
# Using variables
print(name)
circle_area = pi * (radius ** 2)In the code above, the variable name is printed to the console, and the area of a circle is calculated using the variables pi and radius.
Variable Naming Rules
When naming variables in Python, there are a few rules to keep in mind:
- Variable names can only contain letters, numbers, and underscores.
- Variable names cannot start with a number.
- Variable names are case-sensitive.
# Valid variable names
my_var = 10
myVar = "Hello"
var_2 = True
# Invalid variable names
2var = 5 # Cannot start with a number
my-var = 7 # Cannot contain hyphensIt’s good practice to use descriptive names for your variables to make your code more readable and understandable.
And there you have it! That’s how you define and use variables in Python. Happy coding!






