Variables in Python

john charlesjohn charles
2 min read

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

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.

e.g my_name will definitely mean that the variable stores a name as a value.

If a variable is not 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

The line above is similar to

a = 1

b = "alphabet"

c = True

Variables are key components for any programming language.

1
Subscribe to my newsletter

Read articles from john charles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

john charles
john charles

Learning software development at ALX Passionate about using technology to provide solutions.