Python Tutorial

Python Variables

Variables in Python are like containers that hold data. You can store different types of data in these containers, such as numbers, text, and more. Variables allow you to name and reuse data in your programs easily.

1. Creating Variables

In Python, creating a variable is simple. You just choose a name for your variable and assign a value to it using the equals sign (=). Here’s how you can do it:

# Create a variable to store a number
age = 25

# Create a variable to store a piece of text
name = "Alice"

# Create a variable to store a decimal number
height = 5.7

In these examples, age, name, and height are variables. The values 25, "Alice", and 5.7 are stored in these variables, respectively.

2. Using Variables

Once you’ve created a variable, you can use it in your program whenever you need the value it holds. For example:

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

This code will output:

Name: Alice
Age: 25
Height: 5.7

3. Changing Variable Values

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

# Change the value of the 'age' variable
age = 30
print("New Age:", age)

This will change the value of age from 25 to 30 and print the updated value.

4. Variable Naming Rules

When naming variables, you should follow these simple rules:

  • Variable names must start with a letter or an underscore (_), but not a number.
  • After the first character, you can use letters, numbers, or underscores.
  • Variable names are case-sensitive, so age and Age would be different variables.
  • Choose descriptive names to make your code easier to understand, like user_name instead of just u.

5. Example of Variables in Action

Here’s a simple example that uses variables to calculate the area of a rectangle:

# Variables for the dimensions of the rectangle
width = 10
height = 5

# Calculate the area
area = width * height

# Print the result
print("The area of the rectangle is:", area)

In this example, the variables width and height store the dimensions of the rectangle. The area variable stores the result of the calculation.

Summary

  • Variables are containers that store data in your program.
  • You create variables by assigning a value to a name using the equals sign (=).
  • Variables can be used, changed, and reused throughout your program.
  • Follow simple naming rules to ensure your variables are clear and meaningful.