Skip to main content

Variables and assignment in python

Variables and assignment in python



An assignment statement in Python has the form variable = expression. This has the following
effect. First the expression on the right hand side is evaluated, then the result is assigned to the
variable. After the assignment, the variable becomes a name for the result. The variable retains
the same value until another value is assigned, in which case the previous value is lost. Executing
the assignment produces no output; its purpose it to make the association between the variable
and its value.
>>> x = 2+2
>>> print x
4
In the example above, the assignment statement sets x to 4, producing no output. If we want to
see the value of x, we must print it. If we execute another assignment to x, then the previous value
is lost.
>>> x = 380.5
>>> print x
380.5
>>> y = 2* x
>>> print y
761.0
Remember: A single = is used for assignment, the double == is used to test for equality.
In mathematics the equation x = x + 1 is nonsense; it has no solution. In computer science, the
statement x = x + 1 is useful. Its purpose is to add 1 to x, and reassign the result to x. In short,
x is incremented by 1.
>>>
>>>
>>>
11
>>>
>>>
12
x = 10
x = x + 1
print x
x = x + 1
print x
Variable names may be any contiguous sequence of letters, numbers, and the underscore (_) char-
acter. The first character must not be a number, and you may not use a reserved word as a variable
name. Case is important; for instance Sum is a different name than sum. Other examples of legal
variable names are: a, v1, v_1, abc, Bucket, monthly_total, __pi__, TotalAssets.



Comments