Variables in Python

by Alex
Variables in Python

Variables are an important part of any programming language. They allow you to store, use and pass data. Variables allow you not only to easily manipulate data, but also allow you to classify data into types that can be handled according to certain rules. In Python, they obey the concepts used in other programming languages, but they also have features, for example, the type is not explicitly declared.

Creating and Assigning Values

Creating a variable in Python 3 is different from other programming languages. It does not need to be declared beforehand or specify its type; it is created at the moment the value is assigned. To create a variable, the equals symbol “=” is used. To the left of which you write the name and to the right the value of the desired type. Example:

name = "Alexander" # Of type str (string)
age = 15 # of the int type (integer)

Dynamic typing

This way of creating variables is possible thanks to dynamic typing.

The variable does not have to be declared beforehand, because the type is determined by the value assigned, and if a value of a different type is assigned again, there is no need to redefine the type.

Multiple Assignment and Value Exchange

Python allows the programmer to assign the same value to multiple variables:

a = b = c = 5 # All (a, b, and c) store the value 5

In addition, unlike other programming languages, Python allows you to swap values of two variables –

a = 5, b = 3, c = 7
a, b = b, a # Now a = 3 and b = 5
a, b, c = c, a, b # You can swap values for more than just two

This operation is possible because Python uses a tuple, in which it puts values, so you can swap them around.

If you use the classical way used in other languages, you need to introduce an additional variable, which is essentially a buffer for temporarily storing values.

Names

Only letters, numbers and underscores can be used in variable names in Python 3. Numbers can be used in any part of the name except the beginning. And while syntax imposes few restrictions on the programmer, the IT community demands “good” names for variables:

  • The name must describe the purpose. Since the code can be re-read and changed many times, variable names should be such that you can tell what it stores and what it is used for.
  • There is no need to use transliteration. If a programmer wants to create a variable storing the programmer’s age, he should write “age” instead of “vozrast”. This is due to the fact that English is the most used language in IT, the name in English will be understood by everyone, in any case you can use a translator.
  • Acceptable length. The name should not only reflect the essence, but also be short, too long names increase the volume of code and worsen its perception.

The following methods are used to create good names:

  • CamelCase: the first word starts with a small letter, followed by a capital letter. In Python CamelCase is commonly used for class names. For example: WorkersOfFactory.
  • Snake Case: the name consists of words separated by the underscore character “_”, each word is written with a lowercase letter, for example: hello_world. In Python Snake Case is used for function, module and variable names. This style of writing is better understood than CamelCase. It also has some variations that are not used in Python, such as hyphenating “-” (kind-of-animals) and capitalizing each word (Sorted-Array-Of-Names).

Reserved names (keywords)

You cannot name a variable with a name that is already reserved as a keyword. There are about 33 reserved names in Python: def, True, False, break, and so on.

You can see a complete list of keywords by typing help("keywords") in the Python interpreter.

Console output

The function print() is used to print a variable to the screen. This will print one or more variables in a formatted output. There are several variants of the output syntax:

  • print(“{} is a number, {} is a word”.format(number, word)). For example, the variable number stores the value 5 and word stores “five”, then it will print: “5 is a number, five is a word”.
  • You can get by without using .format, just write the components of the output separated by commas: print(number, ” – number”, word, ” – word”).
The output of both methods will be the same, except you don’t need to specify the type of the variable; the interpreter will determine it itself.

Empty Variable

A variable is a reference to some object; it cannot contain nothing at all. If the programmer wants to make it empty (conditionally empty), he assigns it the value None. None is used in cases where the value is undefined, does not exist. Although it is not equivalent to any bool type value, string or number, it is also an object. If necessary, you can check the contents of a variable as follows:

a = None
if a is None:
    print('value is None')
else:
    print('another value')

It can be used, for example, when we store a pointer to an open file in a variable. And when we close this file, we assign value None to the pointer. Later on, before writing or reading data, you can check if the variable is empty.

Scopes

Python has a global scope and a local scope. Declaring variables in different scopes helps avoid naming conflicts, introduces new levels of interaction between variables, and makes code more secure by preventing unauthorized access to function mechanisms. The global scope is the body of the executable script. Any variable declared within it can be accessed from any part of the program, even from another module. To access a global variable from a function, you must use the keyword global; it tells the interpreter to use the global scope. In addition, if the function can’t find the right variable in its body, it automatically looks for it in the global scope of the script and uses it. The local scope is not editable from the outside, any variable declared within a function will be in the local scope, this allows you to use the same name many times in the same program, protect the function from unnecessary changes and simplify your code writing. In version 3 of Python, the nonlocal keyword was added. It allows a variable to be accessed from the local scope of a function, as long as the programmer is trying to access it from another nested function. Example:

def count():
    n = 0
    def inc():
        n += 1 # An error will be called, the function cannot access
        nonlocal n
        n += 1 # Add 1 to n from external function
        return n
    inc()
    return n # will be equal to 1 (if the line with the error is commented out)

Deleting

To remove a variable in Python 3 you can use the del() function, passing its name as argument. Example:

a = 5
del(a)
print(a) # Exception thrown

Conclusion

Python gives you everything you need to manipulate variables and provides tools that other programming languages don’t, such as value exchange. Python makes working with variables very easy, it allows you to avoid declaring their types, assigning a value of a different type to an existing one, and supporting scope handling.

Related Posts

LEAVE A COMMENT