3: A Literal Assignment
November 16, 2016 1 Comment
Book ref: page 39ff
In the previous post you learned about Python’s print feature*. In that post you used print to display the text:
You did that by putting single quotes/apostrophes/inverted commas (‘) around the text to be displayed:
This thing (inside the single quotes) is called a literal. In fact, it’s a string literal. You can create any string you like at the command line by typing it in with single quotes around it:
>>> ‘hello world!’
Try creating some of your own now. If you try to type a string at the command line without the single quotes Python gets upset:
>>> hello world! File "<stdin>", line 1 hello world! ^ SyntaxError: invalid syntax
This failed because there were no quotes around the string.
When you create a literal, Python stores it in memory. However, you can’t get to that literal, because you don’t know where Python has stored it. You can know where Python stores the literal by giving it a name. You do that by:
- Thinking of a name
- Using the = give the name to the literal.
Here’s an example:
>>> a_name = 'hello world!' >>>
In this case, the name is a_name. You can choose any name you like, subject to some constraints (see page 42 of my book). The main things to mention are that names can’t have spaces in them, and can’t start with a number:
>>> a name = 'hello world!' File "<stdin>", line 1 a name = 'hello world!' ^ SyntaxError: invalid syntax
>>> 1stname = 'hello world!' File "<stdin>", line 1 1stname = 'hello world!' ^ SyntaxError: invalid syntax
In the first case, there’s a space after the a. In the second the name starts with a number. Remember to put a single quote at the start and at the end of the string. Think up a name and assign it to ‘hello world!’ (or think up some other string!).
After you give a name to a literal then, whenever you use that name, it’s the same as retyping the literal:
>>> a_name = 'hello world!' >>> a_name 'hello world!' >>> print(a_name) hello world!
Can you see that print(a_name) gives the same output as print(‘hello world!’)? That’s because thinks if Python is happy to let you Then putting that inside some brackets ():
Then putting that on the right hand side of print:
The text with the
* Actually, “function” is the technical term. You’ll learn about functions in a later post.