basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    Chapter 2PythonBasics

    Variables and types: a name, a value, and what you can do with it

    A variable is a name you gave a value: size_gb = 4.7. The type belongs to the value, not the name: a number adds, a string concatenates, and "4.7" * 2 is 4.74.7. Work out how long a disk image takes to download, and see why keyboard input is always a string.

    New hereVariablesValue types: type()

    What you’ll get

    Work out how long a 4.7 GB disk image takes to download on a 100 Mbit/s plan. Give the values names, and the formula reads in words:

    # download.py
    size_gb = 4.7        # disk image, GB
    speed_mbit = 100     # plan, Mbit/s
    seconds = size_gb * 1000 * 8 / speed_mbit
    print("Downloads in", seconds / 60, "min")
    python download.py
    # Downloads in 6.266666666666667 min

    The gigabytes here are the ISP’s, decimal: 1 GB is 1000 MB, a byte is 8 bits. The plan changed to 500 Mbit/s — change one line, speed_mbit = 500, and the formula stays. The extra decimal places go away in the Strings chapter.

    What will it print?
    speed = "100"
    print(speed * 2)
    What will it print?
    Answer:
    100100

    In quotes it’s a string, not a number. A string multiplied by an integer repeats: "100" * 2 is the same string twice in a row. A number would have no quotes: speed = 100.

    How it works: a name is a label on a value

    = in Python isn’t equality but “name it”: compute the value on the right, write on the left the name you’ll use to get it later. That’s why x = x + 1 isn’t a contradiction: take the value of x, add 1, and move the name onto the result.

    size_gb     ──►  4.7     float
    speed_mbit  ──►  100     int
    seconds     ──►  376.0   float

    The value lives in memory on its own, and the type is its. A name has no type: you can move it onto a value of a different type, and Python won’t object.

    value = 100
    print(type(value))   # <class 'int'>
    value = "one hundred"
    print(type(value))   # <class 'str'>

    In a short script that saves lines; in a long one it hides a bug: a name that was a number three screens up is now a string, and you find out only at run time, on the line that does something with it.

    The type decides what a value can do

    + adds numbers and joins strings, and Python won’t add a number to a string at all — it doesn’t guess what you meant.

    Type Example What it is
    int 100, -3, 2 ** 64 an integer of any length
    float 4.7, 6.0, 1e-3 a fraction; computed with rounding error — the Numbers chapter
    str "100", 'Downloads' a string: text in quotes, single or double
    bool True, False yes or no; a comparison answers this way: speed_mbit > 50 is True
    NoneType None “no value”: a function without return returns it

    type() shows a value’s type:

    >>> type(4.7)
    <class 'float'>
    >>> type("4.7")
    <class 'str'>
    >>> 4.7 * 2
    9.4
    >>> "4.7" * 2
    '4.74.7'

    A function named after a type converts to it:

    Code Result What it does
    int("100") 100 a string of digits into an integer
    float("4.7") 4.7 a string into a fraction
    str(100) "100" a number into a string
    int(4.7) 4 a fraction into an integer: drops the tail rather than rounding; int(-4.7) is -4
    int("4.7") ValueError int doesn’t read a fraction in a string: use float first

    Keyboard input is always a string

    input() prints a question, waits for what’s typed, and returns it as a string — even if it’s digits. Without converting to a number, the script crashes:

    size_gb = input("Size, GB: ")
    seconds = size_gb * 1000 * 8 / 100
    # TypeError: unsupported operand type(s) for /: 'str' and 'int'

    The error is on the division, though the multiplication came first: "4.7" * 1000 is the string 4.7 a thousand times in a row, and Python can repeat a string. It can’t divide one. Convert right at input:

    size_gb = float(input("Size, GB: "))
    speed_mbit = float(input("Speed, Mbit/s: "))
    print("Downloads in", size_gb * 1000 * 8 / speed_mbit / 60, "min")
    python download.py
    # Size, GB: 4.7
    # Speed, Mbit/s: 100
    # Downloads in 6.266666666666667 min

    Which names are allowed

    • Latin letters, digits and _, not starting with a digit: speed_mbit, size2. 2size = 5 gives SyntaxError: invalid decimal literal.
    • Case matters: Speed and speed are two different names.
    • Lowercase with _ between words — that’s the Python convention (PEP 8): speed_mbit, not speedMbit.
    • The unit in the name, if there is one: size_gb is clearer a week later than size or s.
    • Non-ASCII letters work: größe = 5 is a valid line. But you won’t meet them in other people’s code, and others may not be able to type them, so stick to ASCII.
    • Language keywords are taken: class, for, if, def give SyntaxError. Built-in function names — print, input, type — are taken implicitly: Python accepts print = 5, and the next print(…) breaks.

    Take it further

    The plan’s speed in megabytes per second — what the browser shows while downloading

    A byte is 8 bits: divide megabits by 8.

    speed_mbit = 100
    print(speed_mbit / 8, "MB/s")
    # 12.5 MB/s
    How many gigabytes download in an hour on this plan

    The example’s task reversed: speed × seconds gives megabits; divide by 8 for megabytes, by 1000 for gigabytes.

    speed_mbit = 100
    seconds = 60 * 60
    print(speed_mbit * seconds / 8 / 1000, "GB")
    # 45.0 GB
    Fix print("Speed: " + speed_mbit) two ways

    You can only join a string with a string. Or don’t join at all: print puts a space between parts itself.

    speed_mbit = 100
    print("Speed:", speed_mbit)
    print("Speed: " + str(speed_mbit))

    If it doesn’t work

    NameError: name 'speed' is not defined

    Cause
    A typo in the name, or the name was used before it was assigned. In interactive mode, a variable from a previous session: after exit() everything is forgotten.
    Fix
    The name letter for letter, with the same case; the assignment higher up the file than the first use.

    TypeError: can only concatenate str (not "int") to str

    Cause
    Concatenating a string with a number: "Speed: " + 100.
    Fix
    Pass the parts to print separated by commas — print("Speed:", 100) — or turn the number into a string: "Speed: " + str(100).

    TypeError: unsupported operand type(s) for /: 'str' and 'int'

    Cause
    The value from input() stayed a string: multiplication repeated the string, and Python can’t divide a string.
    Fix
    Convert right at input: float(input("Size, GB: ")).

    ValueError: could not convert string to float: '4,7'

    Cause
    The decimal was typed with a comma, as many locales write it, and Python expects a point.
    Fix
    Type 4.7. In a script for others, replace the comma before converting: float(text.replace(",", ".")); string methods are in the Strings chapter.

    TypeError: 'int' object is not callable

    Cause
    A variable was named after a built-in function — print = 5 or input = … — and the name now leads to a number.
    Fix
    Rename the variable. In interactive mode, del print brings back the built-in print.