Python Variables

Variables in Python

  • A variable is a symbolic name that references a value in memory.
  • In Python, variables are used to store data values.
  • They act as labels for memory locations, allowing you to access and manipulate data easily.
  • In Python, you don’t have to specify the data type of a variable because it is automatically determined based on the assigned value.


# Variable assignment
name = "Kunal"
age = 17
height = 5.6

# Variable usage
print("Name:", name)
print("Age:", age)
print("Height:", height)

Variable Naming Rules

  • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  • The rest of the variable name can consist of letters, numbers (0-9), and underscores.
  • Variable names are case-sensitive (kunAl and kunal are different variables).

Assigning Values

  • You can assign values to variables using the assignment operator (=).
  • The variable on the left of the = sign receives the value on the right.
a = 50
b = 60
total = a + b

Multiple Assignment:

You can assign multiple variables on a single line.

a, b, c = 10, 20, 30

Swapping Values:

Python allows you to swap the values of variables without using a temporary variable.

a, b = 10, 20
a, b = b, a  # Swap values: a = 20, b = 10

Global vs. Local Variables:

  • Variables declared outside functions are known as global variables. They can be accessed from anywhere within the program.
  • On the other hand, variables declared inside functions are called local variables. They are only accessible within that specific function.

global_var = 10

def my_function():
    local_var = 20
    print(global_var)  # Access global variable
    print(local_var)   # Access local variable