Literals

A literal is a value written out. Its form sets its type.

4inta whole numberno point, no quotes4.0floata number with a fractionthe point makes it a float'4'strtextthe quotes make it textTrueboolyes or noTrue or False, capital firstA literal is a value written out, and its form sets its type.Python does not ask you to declare a type. It reads it from how the value is written.4, 4.0 and '4' are three different objects of three different types, and only the first twoare numbers. type(4.0) tells you: it gives float.

int, float, str, bool.

Literals · Going deeper

Ways to write a number

LiteralValueNote1_000_0001000000Underscores are allowed between digits, for reading0b1015Binary: prefix 0b0o1715Octal: prefix 0o0x1F31Hexadecimal: prefix 0x4. and .54.0 and 0.5A point alone is enough to make a float3e2300.0e means "times ten to the power of"; always a float017SyntaxErrorA leading zero is not allowed in a decimal integerWhatever base you write it in, an integer is stored as the same number.print(0x1F) shows 31. The prefix is only a way of writing; it is not kept.

0b, 0o, 0x. 3e2 is a float.

Floats

A float is an approximation, and sometimes it shows

0.1 + 0.20.30000000000000004not exactly 0.30.1 + 0.2 == 0.3Falseso the comparison fails10 / 52.0division always gives a float1 == 1.0Trueequal in value, different in typeA float is an approximation, and sometimes it shows.A float is stored in binary with a fixed number of digits, and 0.1 has no exact binary form,just as one third has no exact decimal form. The tiny error is usually hidden. It appearswhen you compare two floats with ==, so do not.

0.1 + 0.2 is not 0.3. Do not compare floats with ==.

Floats · Going deeper

String and Boolean literals

LiteralValueNote'hello'helloSingle quotes"hello"helloDouble quotes: exactly the same string"It's"It'sAn apostrophe inside double quotes'It\'s'It'sOr escape it with a backslash''(empty)A string with no characters; still a str'hello"SyntaxErrorThe closing quote must match the opening oneBooleanValueNoteTrue, FalseTrue, FalseThe only two; true and TRUE are just namesTrue + True2A bool is a kind of int: True is 1, False is 0

Single or double quotes. True is 1.

Check yourself

x = 0.1 + 0.2print(x == 0.3)

What does this print?

Variables

Assignment makes a name refer to a value

a = 5b = aa = 9print(a, b)abprinted55595959 5Assignment makes a name refer to a value.Read = as "now refers to", not as "equals". b = a gives b the value that a has at thatmoment. It does not tie b to a, so when a moves on to 9, b still refers to 5.

= means "now refers to". b = a copies the value, not the link.

Variables · Going deeper

Forms of assignment

CodeWhat happensx = 3The name x is created and refers to 3x = x + 1The right side is worked out first, then x is moved to the resultx = y = 3Both names refer to 3x = 'three'Allowed: a name has no type, its value doesprint(z)NameError if z was never assigned3 = xSyntaxError: the name goes on the leftA name exists from the moment it is first assigned, and not before.= assigns. == compares. Mixing them up is the commonest slip in a first program.

Right side first. Unassigned name: NameError.

Identifiers

Letters, digits and underscores, and no digit first

ValidNot validtotalletterstotal_2letters, digits, underscore_totalmay start with an underscoreTotalvalid, but a different name from total2ndstarts with a digitmy-namea hyphen is the minus operatormy namea space ends the nameclassa keywordA name is letters, digits and underscores, and never starts with a digit.Upper and lower case are different letters, so Total and total are two names. A keywordcannot be a name. An invalid name is a SyntaxError, found before the program runs.

Valid: total_2, _total. Not: 2nd, my-name, class.

Identifiers · Going deeper

Case, keywords and built-in names

Case mattersTotal = 10print(total)NameError: total was never assignedA keyword cannot be a namefor = 10SyntaxError, and nothing runsA built-in name can, sadlyprint = 10print('hi')TypeError: print is now the number 10Three different mistakes, three different errors.A misspelt name is found only when its line runs. A keyword used as a name is found beforeanything runs. Reusing print, input, int, str, list or len is legal, and breaks theoriginal for the rest of the program.

NameError, SyntaxError, TypeError.

Check yourself

_____ = 10print(_____)

Which name can go in the gap?

Naming conventions

Python accepts any valid name. PEP 8 is for the reader.

Valida = 7.5b = 40c = a * bprint(c)Valid, and readablehourly_rate = 7.5hours_worked = 40weekly_pay = hourly_rate * hours_workedprint(weekly_pay)Both print 300.0Python accepts any valid name. PEP 8 is for the reader.PEP 8 is the style guide that Python programmers follow. For variables it says: lower case,words joined by underscores, and a name that says what the value is.

lower_case_with_underscores, and a name that says what it is.

Naming conventions · Going deeper

PEP 8 in seven rules

ForWriteThe ruleVariables, functionsweekly_paylower case, words joined by underscoresConstantsMAX_HOURSupper case, by agreement; Python does not enforce itMeaningfuldays_left, not dthe name says what the value isAvoidl, O, I as namesthey look like 1 and 0Around =x = 5, not x=5one space each sideIndentation4 spacesnever tabs mixed with spacesLine length79 charactersthe longest a line should beNone of this changes what the program does. All of it changes how fast it is read.

snake_case, UPPER_CASE constants, 4 spaces.

Check yourself

count = 3Count = count + 1print(count)

What does this print?

Lesson complete

You finished “Literals, variables and names”

Answer the questions along the way to see your score here.

Open in a new tab