Literals
A literal is a value written out. Its form sets its type.
int, float, str, bool.
A literal is a value typed directly into the code. How you write it decides what type it is. Four, with no point and no quotes, is an int. Four point zero is a float: the point alone does that. Four inside quotes is a string: text, not a number. And True, with a capital T, is a bool. The exam asks for the type of a literal more often than you would think.
Literals · Going deeper
Ways to write a number
0b, 0o, 0x. 3e2 is a float.
Floats
A float is an approximation, and sometimes it shows
0.1 + 0.2 is not 0.3. Do not compare floats with ==.
Integers in Python are exact. Floats are not. Add nought point one and nought point two, and you get a number a hair above nought point three. So asking whether the sum equals nought point three gives False. Division always gives a float, even ten over five. And an int can equal a float in value: one equals one point nought is True.
Floats · Going deeper
String and Boolean literals
Single or double quotes. True is 1.
Check yourself
What does this print?
Variables
Assignment makes a name refer to a value
= means "now refers to". b = a copies the value, not the link.
A variable is a name that refers to a value. Trace these four lines. a refers to five. b is given the value that a has now: five. a is moved to nine. b is not affected. So this prints nine, then five. The trap answer is nine nine, from thinking b follows a.
Variables · Going deeper
Forms of assignment
Right side first. Unassigned name: NameError.
Identifiers
Letters, digits and underscores, and no digit first
Valid: total_2, _total. Not: 2nd, my-name, class.
Python has four rules for a name, and the exam tests each. Letters are fine. So are digits and underscores, after the first character. An underscore may come first. Capital and small letters are different, so this is another name entirely. Now the invalid ones. A digit cannot come first. A hyphen is a minus sign. A space ends the name. And a keyword is taken.
Identifiers · Going deeper
Case, keywords and built-in names
NameError, SyntaxError, TypeError.
Check yourself
Which name can go in the gap?
Naming conventions
Python accepts any valid name. PEP 8 is for the reader.
lower_case_with_underscores, and a name that says what it is.
Being valid is the least a name can be. This program is correct, and tells you nothing. This is the same program with names that say what each value is: hourly rate, hours worked, weekly pay. They print the same result. The second follows P E P eight, Python's style guide: lower case, with underscores between words.
Naming conventions · Going deeper
PEP 8 in seven rules
snake_case, UPPER_CASE constants, 4 spaces.
Check yourself
What does this print?
Lesson complete
You finished “Literals, variables and names”
Answer the questions along the way to see your score here.