Python - Variables

In Python, a variable is a name given to a piece of data that can be used later in the program. It is a way of storing data in memory that can be referred to using a symbolic name.

Variables in Python are dynamic and do not have to be declared with a specific data type. They take on the data type of the value assigned to them at runtime.

To create a variable in Python, you simply assign a value to a name using the equal sign (=) operator. For example:

In this example, age and name are variables. age is assigned an integer value of 25 and name is assigned a string value of "John".

Variables can be used in expressions and statements to perform various operations. For example:

x = 10
y = 5
sum = x + y
difference = x - y
product = x * y
quotient = x / y
print(sum, difference, product, quotient)

In this example, x and y are variables assigned integer values. The variables are then used in expressions to calculate the sum, difference, product, and quotient, which are then printed to the console.

  • The variable name must start with a letter or an underscore (_).
  • The variable name can contain letters (uppercase or lowercase), digits, and underscores.
  • Variable names are case sensitive, which means 'myvar' and 'myVar' are two different variables.
  • Variable names should not contain spaces.
  • Variable names should not start with a number.
#Here are some examples of valid variable names in Python:
x = 5
y = "hello"
my_var = 10.5
_underscore = "variable name starting with underscore"
#And here are some examples of invalid variable names:
3x = 5     # variable name cannot start with a number
my var = 10  # variable name cannot contain spaces

It's always a good practice to use meaningful and descriptive names for your variables, which can help you and others to understand your code better.