Python Basics
(Learn Python Programming in 20 Minutes)
3 Python commands
3.5 Variables and assignment
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.
>>> x = 10
>>> x = x + 1
>>> print x
11
>>> x = x + 1
>>> print x
12
Variable names may be any contiguous sequence of letters, numbers, and the underscore (_) character. 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.
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.