Variables and Assignment
Rules for variables in Python are the same as they are in most other high-level languages: 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 equals sign.
>>> counter = 0 >>> miles = 1000.0 >>> name = "angry birds" >>> 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 does not support operators such as n++ or – -n.
The print statement at the end shows off the string format operator ( % ) again. Each “%x” code matches the type of the argument to be printed. We have seen %s (for strings) and %d (for integers) earlier in earlier topics. Now we are introduced to %f (for floating point values).