Variables and Objects

In most programming languages, including C++ and Java, we must declare each variable, specifying its type, before it can be used. This is called static typing, because the compiler knows at compile time what type each variable is. Python, like most very high level languages, uses a different approach: Variables have no type restrictions (dynamic typing), and they don't need to be declared.

We could learn about Python's variables and identifiers by creating and executing a file, as we did with hello.py in the preceding section. But for trying out small code snippets we don't need to create a file at all. We can just enter the lines directly in the IDLE Python Shell window at the >>> prompt:

>>> x = 71 >>> y = "Dove"

The whitespace around the assignment operator = is optional but is included because it makes the code easier to read. As a matter of style we will always put one space before and after binary operators. On the other hand, it is important that each statement occupies its own line and has no extraneous leading whitespace. This is because Python uses indentation and line breaks to signify its block structure, rather than the braces and semicolons used by many other programming languages.

Now we are ready to review what the two lines actually do. The first line creates an object of type int and binds the name x to it.* The second line creates an object of type str (an 8-bit string type) and binds the name y to it.

Some Python programmers refer to names (such as the x and y used earlier), as object references since they refer to objects rather than being objects in their own right. For basic data types like int and str it makes no difference whether we see their variables as "objects" or as "object references"; they behave in the same way as they do in other programming languages:

>>> x = 82 >>> x += 7 >>> x 89

Later on we will see cases where the fact that Python variables are object Lists references makes a difference. ^ 31

* This is similar to the Java assignment, Integer x = new Integer(71); for C++ a near-equivalent would be int xd = 71; int &x = xd;.

Was this article helpful?

0 0
Video Marketing Traffic Tactics

Video Marketing Traffic Tactics

Within this guide you will be learning some of the following tactcis Demonstrate how to use your products, Give a complete and accurate picture of what you are selling, Convey how important the customer is to you, Demonstrate the unique qualities of your product, Put testimonials in your video, Back up your printed information with the video, Use every aspect of video, Make it compelling, Think hard about how your video is presented, Reuse old video to make something new, Keep your video professional, Do not overwhelm the consumer, Tailor the video to your target market, Get creative, Place it wisely and much more.

Get My Free Ebook


Post a comment