Skip to main content

Variables and Statements | Core Python 3.8

Variables 

Another concept that might be familiar to you is variables. If algebra is but a distant memory, don’t worry: variables in Python are easy to understand. A variable is a name that represents (or refers to) some value. For example, you might want the name x to represent 3. To make it so, simply execute the following:

>>> x = 3

This is called an assignment. We assign the value 3 to the variable x. Another way of putting this is to say that we bind the variable x to the value (or object) 3. After you’ve assigned a value to a variable, you can use the variable in expressions.

>>> x * 2 

6

Unlike some other languages, you can’t use a variable before you bind it to something. There is no “default value.”

■ Note  the simple story is that names, or identifiers, in python consist of letters, digits, and underscore characters (_). they can’t begin with a digit, so Plan9 is a valid variable name, whereas Plan is not.

Statements 

Until now we’ve been working (almost) exclusively with expressions, the ingredients of the recipe. But what about statements—the instructions?
    In fact, I’ve cheated. I’ve introduced two types of statements already: the print statement and assignments. What’s the difference between a statement and an expression? You could think of it like this: an expression is something, while a statement does something. For example, 2 * 2 is 4, whereas print(2 * 2) prints 4. The two behave quite similarly, so the difference between them might not be all that clear.

>>> 2 * 2 

4

 >>> print(2 * 2) 

4

As long as you execute this in the interactive interpreter, there’s no difference, but that is only because the interpreter always prints out the values of all expressions (using the same representation as repr—see the section “String Representations, str and repr” later in this chapter). That is not true of Python in general. Later in this chapter, you’ll see how to make programs that run without this interactive prompt; simply putting an expression such as 2 * 2 in your program won’t do anything interesting.4 Putting print(2 * 2) in there, however, will still print out 4.

 ■ Note  actually, print is a function (more on those later in the chapter), so what I’m referring to as a print statement is simply a function call. In python 2.x, print had a statement type of its own and didn’t use parentheses around its arguments.

    The difference between statements and expressions is more obvious when dealing with assignments. Because they are not expressions, they have no values that can be printed out by the interactive interpreter.

>>> x = 3 

>>>

You simply get a new prompt immediately. Something has changed, however. We now have a new variable x, which is now bound to the value 3. To some extent, this is a defining quality of statements in general: they change things. For example, assignments change variables, and print statements change how your screen looks.

 Assignments are probably the most important type of statement in any programming language, although it may be difficult to grasp their importance right now. Variables may just seem like temporary “storage” (like the pots and pans of a cooking recipe), but the real power of variables is that you don’t need to know what values they hold in order to manipulate them.5
    For example, you know that x * y evaluates to the product of x and y, even though you may have no knowledge of what x and y are. So, you may write programs that use variables in various ways without knowing the values they will eventually hold (or refer to) when the program is run.

Getting Input from the User 

You’ve seen that you can write programs with variables without knowing their values. Of course, the interpreter must know the values eventually. So how can it be that we don’t? The interpreter knows only what we tell it, right? Not necessarily. You may have written a program, and someone else may use it. You cannot predict what values users will supply to the program. Let’s take a look at the useful function input. (I’ll have more to say about functions in a minute.)

>>> input("The meaning of life: ") The meaning of life: 42 '42'

What happens here is that the first line (input(...)) is executed in the interactive interpreter. It prints out the string "The meaning of life: " as a new prompt. I type 42 and press Enter. The resulting value of input is that very number (as a piece of text, or string), which is automatically printed out in the last line. Converting the strings to integers using int, we can construct a slightly more interesting example:

>>> x = input("x: ") 

x: 34

 >>> y = input("y: ") 

y: 42 

>>> print(int(x) * int(y)) 

1428

Here, the statements at the Python prompts (>>>) could be part of a finished program, and the values entered (34 and 42) would be supplied by some user. Your program would then print out the value 1428, which is the product of the two. And you didn’t have to know these values when you wrote the program, right?

 ■Note  getting input like this is much more useful when you save your programs in a separate file so other users can execute them. You learn how to do that later in this chapter, in the section “saving and executing Your programs.”
   
Note the quotes around storage. Values aren’t stored in variables—they’re stored in some murky depths of computer memory and are referred to by variables. As will become abundantly clear as you read on, more than one variable can refer to the same value.

The slightly less simple story is that the rules for identifier names are in part based on the Unicode standard, as documented in the Python Language Reference at https://docs.python.org/3/reference/lexical_analysis.html. 4In case you’re wondering—yes, it does do something. It calculates the product of 2 and 2. However, the result isn’t kept anywhere or shown to the user; it has no side effects, beyond the calculation itself.

Comments

Popular posts from this blog

Strings | Core Python 3.8

Strings  Now what was all that "Hello, " + name + "!" stuff about? The first program in this chapter was simply print("Hello, world!") It is customary to begin with a program like this in programming tutorials. The problem is that I haven’t really explained how it works yet. You know the basics of the print statement (I’ll have more to say about that later), but what is "Hello, world!"? It’s called a string (as in “a string of characters”). Strings are found in almost every useful, real-world Python program and have many uses. Their main use is to represent bits of text, such as the exclamation “Hello, world!” Single-Quoted Strings and Escaping Quotes Strings are values, just as numbers are: >>> "Hello, world!"  'Hello, world!' There is one thing that may be a bit surprising about this example, though: when Python printed out our string, it used single quotes, whereas we used double quotes. What’s the differ...

Execution the Program | Core Python 3.8

Saving and Executing Your Programs  The interactive interpreter is one of Python’s great strengths. It makes it possible to test solutions and to experiment with the language in real time. If you want to know how something works, just try it! However, everything you write in the interactive interpreter is lost when you quit. What you really want to do is write programs that both you and other people can run. In this section, you learn how to do just that.     First of all, you need a text editor, preferably one intended for programming. (If you use something like Microsoft Word, which I really don’t really recommend, be sure to save your code as plain text.) If you are already using IDLE, you’re in luck. With IDLE, you can simply create a new editor window with File › New File. Another window appears, without an interactive prompt. Whew! Start by entering the following: print("Hello, world!") Now select File › Save to save your program (which is, in fact, a pl...

Dictionaries: When Indices Won’t Do | Core Python 3.8

You’ve seen that lists are useful when you want to group values into a structure and refer to each value by number. In this chapter, you learn about a data structure in which you can refer to each value by name. This type of structure is called a mapping. The only built-in mapping type in Python is the dictionary. The values in a dictionary don’t have any particular order but are stored under a key, which may be a number, a string, or even a tuple. Dictionary Uses The name dictionary should give you a clue about the purpose of this structure. An ordinary book is made for reading from start to finish. If you like, you can quickly open it to any given page. This is a bit like a Python list. On the other hand, dictionaries—both real ones and their Python equivalent—are constructed so that you can look up a specific word (key) easily to find its definition (value).     A dictionary is more appropriate than a list in many situations. Here are some examples of uses of Pyth...

Lists and Tuples | Core Python 3.8

This chapter introduces a new concept: data structures. A data structure is a collection of data elements (such as numbers or characters, or even other data structures) that is structured in some way, such as by numbering the elements. The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number—its position, or index. The first index is zero, the second index is one, and so forth. Some programming languages number their sequence elements starting with one, but the zeroindexing convention has a natural interpretation of an offset from the beginning of the sequence, with negative indexes wrapping around to the end. If you find the numbering a bit odd, I can assure you that you’ll most likely get used to it pretty fast.     This chapter begins with an overview of sequences and then covers some operations that are common to all sequences, including lists and tuples. These operations will also work with strings, which will be use...