Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account