Variables in Python

john_otienoh

John Otienoh

Posted on January 1, 2024

Variables in Python

Variables

I have a value where do i store it in my computer?
Well that's where variables come handy.
Variables refer to

  1. A location in the memory that are reserved to store the values of my code
  2. A container that holds one value and has a label on it. From our definition we can visualise a variable as a gift box with similar characteristics like a container-like, has a label, stores something etc.

Syntax for declaring a variable in python is:
'variable_name' 'assignment operator' 'value'

    name = 'john'
    age = 20
    option = True
Enter fullscreen mode Exit fullscreen mode

Variables in python have a specific naming convention.

  1. Use snake_case or CamelCase naming convention. e.g my_name, MyName.
  2. Variable name can only contain alphanumeric character and underscores [A - Z, 0 - 9 and _].
  3. Variable name starts with a letter or the underscore character. e.g _name = 'john' or name = 'john'
  4. Variable name should not be a keyword. e.g in, for, while etc.
  5. Variable names should meaningful.

If a variable is defined(assigned a value) , trying to use it will give us specifically a NameError.

Multiple assignment in a single line

Supposed we want to define numerous variables using single line of code, we can do it by separating variable names and values with commas.

    a, b, c = 1, "alphabet", True
Enter fullscreen mode Exit fullscreen mode

The line above is similar to

    a = 1
    b = "alphabet"
    c = True
Enter fullscreen mode Exit fullscreen mode

Variables are key components for any programming language.

💖 💪 🙅 🚩
john_otienoh
John Otienoh

Posted on January 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related