Python Variable

A Python variable is a name bound to an object. The assignment max_age = 34 evaluates the right-hand side to the integer object 34 and binds the name max_age to it. The single equals sign means “bind this name,” not “these are equal”; equality is tested with ==.

The name has no fixed type; the object does. After max_age = "34", the same name refers to a string. This is dynamic typing: Python checks types when an operation runs rather than requiring a type declaration for the variable. Reassignment changes what the name refers to. After resetting max_age = 34, max_age + 1 produces 35 without rebinding the name. max_age = max_age + 1 rebinds it to that result. If the name still referred to "34", adding 1 would instead raise TypeError.

The “labeled box” picture helps at first but misleads for shared objects. After a = [1, 2] and b = a, both names refer to one list, so b.append(3) makes a show [1, 2, 3] too. Integers and strings cannot be modified in place; operations do not alter the existing integer or string object. A result need not always be a newly allocated object.

A valid name starts with a letter or underscore and continues with letters, digits, or underscores; it cannot contain spaces or symbols such as & or -. Names are case-sensitive, so age and Age are different. Keywords such as if, for, and class cannot be names. Built-in names such as print, list, and str are allowed, but assigning to one hides the built-in in that scope and causes confusing errors later. Python 3 accepts many non-ASCII letters, yet ASCII names in snake_case are the usual convention for shared code.

References: Python Reference: Naming and binding, Identifiers and keywords, PEP 8 naming conventions. See it in use in Python Foundations: Variables, Types, and the Notebook.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.