techmore.in

Python - Variables

In Python, a variable is a name that refers to a value stored in memory. It's like a label you attach to a box so you can identify what's inside it later.

Key Points

  • Variables are containers for storing data values.
  • Python is dynamically typed, so you don’t need to declare the type.
  • Type is inferred from the value assigned.
sh
name = "Alice" # string age = 25 # integer height = 5.7 # float is_student = True # boolean

Why are Variables Important?

  • They make your code readable and manageable.
  • Allow you to store, reuse, and modify values.

Example

sh
radius = 5 pi = 3.14159 area = pi * radius ** 2 print("Area of the circle is:", area)

Rules for Naming Variables

  • Must start with a letter or an underscore (_).
  • Can contain numbers after the first character (e.g., x1, value_2).
  • Case-sensitive: score and Score are different.
  • Cannot use Python keywords (e.g., class, for).

Valid vs Invalid Examples

sh
# Valid x = 10 _name = "Raj" temperature_celsius = 36.6 # Invalid # 2cool = "no" # starts with number # my-var = "dash" # hyphens not allowed # class = "error" # 'class' is a keyword

1. Declaring Variables

python
# This is how you declare variables in Python x = 5 # Integer y = 3.14 # Float name = "Alice" # String status = True # Boolean

2. Variable Naming Rules

  • Must start with a letter or underscore (_)
  • Cannot start with a number
  • Can only contain alpha-numeric characters and underscores
  • Case-sensitive (e.g., age, Age, and AGE are different)

3. Multiple Assignments

python
a, b, c = 1, 2, 3 # Assigning multiple variables in one line x = y = z = 0 # Assigning same value to multiple variables

4. Variable Types and Type Casting

python
x = int(1) # 1 y = float("3.5") # 3.5 z = str(10) # "10" b = bool(0) # False

5. Variable Scope

python
def example(): local_var = "I'm local" print(local_var) global_var = "I'm global" example() print(global_var)

6. Constants

Python doesn't have true constants, but you can indicate a constant by using uppercase letters:

python
PI = 3.14159 GRAVITY = 9.8

7. Deleting Variables

python
x = 10 del x # x is now deleted