- 2.1 Program Output, the print Statement, and Hello World!
- 2.2 Program Input and the raw_input()Built-in Function
- 2.3 Comments
- 2.4 Operators
- 2.5 Variables and Assignment
- 2.6 Numbers
- 2.7 Strings
- 2.8 Lists and Tuples
- 2.9 Dictionaries
- 2.10 Code Blocks Use Indentation
- 2.11 if Statement
- 2.12 while Loop
- 2.13 for Loop and the range() Built-in Function
- 2.14 List Comprehensions
- 2.15 Files and the open() and file() Built-in Functions
- 2.16 Errors and Exceptions
- 2.17 Functions
- 2.18 Classes
- 2.19 Modules
- 2.20 Useful Functions
- 2.21 Exercises
2.5 Variables and Assignment
Rules for variables in Python are the same as they are in most other high-level languages inspired by (or more likely, written in) C. They are simply identifier names with an alphabetic first character—“alphabetic” meaning upper-or lowercase letters, including the underscore ( _ ). Any additional characters may be alphanumeric or underscore. Python is case-sensitive, meaning that the identifier “cAsE” is different from “CaSe.”
Python is dynamically typed, meaning that no pre-declaration of a variable or its type is necessary. The type (and value) are initialized on assignment. Assignments are performed using the equal sign.
>>> counter = 0 >>> miles = 1000.0 >>> name = 'Bob' >>> counter = counter + 1 >>> kilometers = 1.609 * miles >>> print '%f miles is the same as %f km' % (miles, kilometers) 1000.000000 miles is the same as 1609.000000 km
We have presented five examples of variable assignment. The first is an integer assignment followed by one each for floating point numbers, one for strings, an increment statement for integers, and finally, a floating point operation and assignment.
Python also supports augmented assignment, statements that both refer to and assign values to variables. You can take the following expression ...
n = n * 10
...and use this shortcut instead:
n *= 10
Python does not support increment and decrement operators like the ones in C: n++ or --n. Because + and -- are also unary operators, Python will interpret --n as -(-n) == n, and the same is true for ++n.