VARIABLE

In Python, a variable is a named location in memory used to store data. You can think of it as a container that holds a value. Variables are fundamental to programming because they allow you to manipulate and store data in your programs. Here's how you declare and use variables in Python:

Variable Declaration and Assignment

You can create a variable by choosing a name for it and assigning a value using the assignment operator (=).

# Variable assignment

my_variable = 42

In this example, my_variable is the name of the variable, and 42 is the assigned value. Python is dynamically typed, so you don't need to explicitly declare the data type of the variable; Python infers it based on the assigned value.

Variable Naming Rules:

  • Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores (_).
  • They cannot start with a number.
  • Variable names are case-sensitive (my_variable and My_Variable are different variables).
  • Avoid using reserved words (keywords) as variable names. For example, you can't name a variable if or else.

Common Data Types:

Python supports various data types, and the type of a variable is determined by the value it holds. Common data types include:

  • int: Integer (e.g., x = 5)
  • float: Floating-point number (e.g., y = 3.14)
  • str: String (e.g., name = "John")
  • bool: Boolean (e.g., is_true = True)

Variable Reassignment:

You can change the value of a variable by reassigning it.

my_variable = 42

print(my_variable)  # Output: 42

 

my_variable = "Hello, World!"

print(my_variable)  # Output: Hello, World!

Multiple Assignment:

You can assign values to multiple variables in a single line.

a, b, c = 1, 2, 3

This assigns 1 to a, 2 to b, and 3 to c.