Python - Variable

> Procedural Languages > Python > Python - Grammar (Package | Module)

1 - About

Language - (Variable|Field|Scalar) in Python.

A variable name must start with a letter and must exclude certain special symbols such as the dot (period). The underscore is allowed in a variable name.

mynum = 4 + 1

The variable being assigned to is called the left-hand side of an assignment, and the expression whose value is assigned is called the right-hand side.

A variable can be bound to a value of any type. You can rebind mynum to a string:

>>> mynum = 'Brown'

An assignment statement binds a variable to the value of an expression, not to the expression itself. Python fi rst evaluates the right-hand side and only then assigns the resulting value to the left-hand side.

The binding lasts until you assign some other value to the variable or until you end your Python session. It is called a top-level binding.

Advertising

3 - Name resolution

Name resolution of free variables occurs at runtime, not at compile time. This means that the following code will print 42:

i = 10
def f():
    print(i)
i = 42
f()

4 - Management

4.1 - Assignment

4.1.1 - Conditional

expression if condition else expression
>>> x=1
>>> x if x<0 else -x
-1
>>> x if x>0 else -x
1

4.1.2 - Unpacking

Initialization and extraction of variables via Python - (Un)Packing

4.2 - List

Function Description
dir() list of variables in scope
globals() a dictionary of global variables
locals() a dictionary of local variables
Advertising

4.3 - Delete

del variableName