Creating Variables
Creating variables in Python is straightforward. Variables are containers for storing data values, and Python is a dynamically typed language, meaning you don't need to declare the type of a variable explicitly. The type is determined automatically based on the value you assign.
Here’s how you can create variables in Python:
1. Assigning a Value to a Variable
You can assign a value to a variable using the = operator.
# Integer variable
age = 25
# Float variable
price = 19.99
# String variable
name = "Alice"
# Boolean variable
is_student = True
2. Variable Naming Rules
- Must start with a letter or an underscore (_): Variable names cannot start with a number or a symbol.
- Case-sensitive: myVar and myvar are two different variables.
- Can include letters, numbers, and underscores: You can use a combination of these in your variable names.
# Valid variable names
my_var = 10
_var2 = 5.5
varName = "example"
# Invalid variable names (will raise an error)
2nd_var = 10 # Starts with a number
my-var = 5.5 # Contains a hyphen
3. Reassigning Variables
Variables in Python can be reassigned to a new value, even if it’s a different data type.
x = 10 # x is an integer
x = "Hello" # Now x is a string
4. Multiple Assignments
You can assign values to multiple variables in a single line.
a, b, c = 1, 2, "three"
# This will result in:
# a = 1
# b = 2
# c = "three"
5. Assigning the Same Value to Multiple Variables
You can also assign the same value to multiple variables at once.
x = y = z = 100
6. Dynamic Typing
Since Python is dynamically typed, the type of a variable can change during the program’s execution.
num = 5 # num is an integer
num = 5.5 # Now, num is a float
num = "Five" # Now, num is a string
Example Usage
Here’s a simple example that demonstrates variable creation and reassignment:
# Creating variables
username = "JohnDoe"
score = 95
is_logged_in = True
# Printing variables
print(username) # Output: JohnDoe
print(score) # Output: 95
print(is_logged_in) # Output: True
# Reassigning a variable
score = 100
print(score) # Output: 100
This example shows how to create and manipulate variables in Python.