Variables


10 min.   |   Beginner  

Assignment

Variables in Python act as containers that store information the program can access and modify. They can hold:

This flexibility allows variables to store almost any kind of information, making them essential for all kinds of programming tasks.

Naming

In Python, there are some conventions when it comes to naming variables:

  • Must start with a letter or underscore.
  • Cannot start with a number.
  • Can only contain alphanumeric characters and underscores.
  • Are case-sensitive.

Reassignment

Reassignment means updating a variable’s value after it has been created. This allows the variable to hold new information that the program can use and modify.

Multiple Assignment

Multiple assignment allows you to assign values to several variables in a single line, making your code more concise and readable.

Dynamic Assignment

In Python, variables are dynamically typed, which means a variable can be reassigned to a value of a different type at runtime. This allows the same variable to hold, for example, a number one moment and text the next.

Variables: Exercises

Tip Variables: Exercise 1

A person weighs 72 kg and is 1.78 meters tall. Calculate their Body Mass Index (BMI) using:

\text{BMI} = \frac{\text{weight}}{\text{height}^2}

Tip Variables: Exercise 2

Convert 21^\circ C to Fahrenheit using:

F = C \times \frac{9}{5} + 32

Tip Variables: Exercise 3

Compute the z-score for a value of x = 87, with mean \mu = 75 and standard deviation \sigma = 8:

z = \frac{x - \mu}{\sigma}

Tip Variables: Exercise 4

A dataset has a standard deviation of \sigma = 6.5. Compute the variance:

\sigma^2 = \sigma \times \sigma

Tip Variables: Exercise 5

An event has probability P(A) = 0.34. Compute the probability of the complement:

P(A^c) = 1 - P(A)