Python Variables – Time to level up your coding skills

Let’s dive into the world of variables in Python! In this tutorial, we’ll explore how to name, use, and delete variables. But first, let’s start with the basics: what exactly are variables in Python?

Imagine you have a box where you can store different items. In programming, a variable is like that box. It holds data that you can use and manipulate throughout your code. Curious to learn more? Let’s get started on this journey to understand Python variables better!

What are Python Variables?Variables in Python

Python variables are containers for storing data values.

Let’s take an example.

name=‘TechVidvan’

This is a variable. We can refer to this now with the name ‘name’. We do not declare the type of variable – name is ‘TechVidvan’.

Let’s talk about that.

Python is Dynamically-Typed

In Python, you don’t need to declare the data type of a variable when assigning a value to it. The interpreter decides the data type at runtime. There’s no need to declare a variable beforehand; you can directly assign a value to it. What’s more, a single variable can hold different types of data at different times.

We will discuss this later.

name=‘TechVidvan’

Here, name holds a string.

Naming Variables

We cannot name a variable anything. A variable name is called an identifier and has to follow some rules:

  • Variables can have letters (A-Z and a-z), digits(0-9) and underscores.
  • It cannot begin with an underscore (_) or a digit.
  • It cannot have whitespace and signs like + and -, !, @, $, #, %.
  • It cannot be a reserved keyword for Python.
  • Variable names are case sensitive.

A variable’s name can be made of letters, digits, and underscores but you cannot begin it with an underscore or a digit. You can also not use whitespace or the signs + and – in a name.

Let’s take some examples of valid variable names:

  • fraud1
  • Exploit_2
  • work_of_devil

These names are invalid:

  • passive-aggressive
  • 21lies
  • fake@rs

Reserved Keywords

Python also has some reserved words:reserved words in python variables

These are 33 reserved words. They define the syntax and structure of Python. You cannot use a word from this list as a name for your variable or function.

In this list, all words except True, False, and None are in lowercase.

  • Variable names can be of any length but you should try to not exceed 79 characters.
  • Python variable names are case-sensitive. The variable ‘name’ is different than the variable ‘Name’.
  • According to PEP8, you should name long variables names like this- long_variable_name with underscores.

Assigning Variables

Like we said, we do not declare variables, we assign them.

This is how we assign a variable:

name=‘TechVidvan’

name=8

The variable name has the value ‘TechVidvan’, but later, it has the value 8. This is possible.

We cannot assign a variable to a value.

8=name

SyntaxError: can’t assign to literal

This gives us a SyntaxError as we cannot assign to a literal. You can also use foreign characters in variable names. There are many ways to assign variables.

Let’s see them.

1. Assigning Multiple Variables

You can assign different values to multiple variables in a statement.

fname, lname=‘Lucifer’, ‘Satan’

Here, fname is ‘Lucifer’ and lname is ‘Satan’. We can assign values to both fname and lname in one statement.

2. Assigning Single Value

You can also assign a single value to many variables.

fname=lname=’Satan’

In this, fname and lname both are ‘Satan’.

3. Incrementing before Assigning Value

You do not need to declare a variable in Python, you can assign to it. But you cannot increment or change its value if you have not assigned a value to it.

>>> Adolf+=2

Output:

Traceback (most recent call last):
  File “<pyshell#25>”, line 1, in <module>
    Adolf+=2
NameError: name ‘Adolf’ is not defined

First, you should assign a value to Adolf. Then you can modify it.

>>> Adolf=2
>>> Adolf+=2
>>> print(Adolf)

Output:

4

4. Reassigning the Variables

Like I said before, variables can hold different type of values any time.

>>> dementor=2
>>> dementor='DF'

The dementor variable was holding the value 2 but now it holds the ‘DF’ string.

Scope-Local, Nonlocal and Global Variables

You can declare local and global variables in Python.

Let’s start with global.

1. Global Variables

>>> count=2
>>> def func():
  count+=1
  print(count)
>>> func()

Output:

Traceback (most recent call last):
  File “<pyshell#37>”, line 1, in <module>
    func()
  File “<pyshell#36>”, line 2, in func
    count+=1
UnboundLocalError: local variable ‘count’ referenced before assignment

We cannot increment count in func because it looks for a local count. So the output is not 3, it is an UnboundLocalError.

We can use the global keyword inside func to let it work.

>>> count=2
>>> def func():
  global count
  count+=1
  print(count)


>>> func()

Output:

3

Now it works.

This func function adds 1 to global count and prints it.

2. Local Variables

In our previous example, count was defined outside the func and hence it was in global scope, now we will define count in the local scope by defining it inside the func function and then you can observe that local variable and global variables have different scopes.

>>> count=2
>>> def func():
  count = 10
  count+=1
  print(count)

>>>func()
>>>print(count)

Output:

11
2

3. Nonlocal Variables

When there are nested functions, the inner function can use variable from the outer function using the nonlocal keyword.

>>> def func1():
  achievements=9
  def func2():
    nonlocal achievements
    achievements+=2
    print(achievements)
  func2()


>>> func1()

Output:

11

Deleting Variables

If you use the del keyword, you can delete a variable in Python.

Let’s define a variable and delete it.

>>>wannabe=2
>>>del wannabe
>>>print(wannabe)

Output:

Traceback (most recent call last):
  File “<pyshell#63>”, line 1, in <module>
    print(wannabe)
NameError: name ‘wannabe’ is not defined

After you delete it, you cannot access it. It gives you a NameError exception.

The + Operator

You can join or concatenate two or more variables with the concatenation operator.

The + sign is the concatenation operator.

>>> name='Lucifer'
>>> lname='Satan'
>>> name+lname

Output:

‘LuciferSatan’

This operator performs addition on integers and on floats.

>>> 7+7.5

Output:

14.5

You cannot add an integer and a string.

>>> 7+name

Output:

Traceback (most recent call last):
  File “<pyshell#68>”, line 1, in <module>
    7+name
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Summary

This was all about Python variables.

Today, we learned about variables in Python and how to define, use and delete them. We learned about local, global and nonlocal variables and about naming and assigning.

I hope that our Python variables article was helpful to you.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.