Почему 008 и 009 недопустимы для ключей Python?

Слегка более короткий код с использованием insertRow и insertCell :

function tableCreate(){
    var body = document.body,
        tbl  = document.createElement('table');
    tbl.style.width  = '100px';
    tbl.style.border = '1px solid black';

    for(var i = 0; i < 3; i++){
        var tr = tbl.insertRow();
        for(var j = 0; j < 2; j++){
            if(i == 2 && j == 1){
                break;
            } else {
                var td = tr.insertCell();
                td.appendChild(document.createTextNode('Cell'));
                td.style.border = '1px solid black';
                if(i == 1 && j == 1){
                    td.setAttribute('rowSpan', '2');
                }
            }
        }
    }
    body.appendChild(tbl);
}
tableCreate();

Кроме того, это не использует некоторые «плохие практики», такие как установка атрибута border вместо использования CSS, и он обращается к body через document.body вместо document.getElementsByTagName('body')[0];

13
задан Wooble 9 October 2014 в 11:44
поделиться

5 ответов

In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this:

some_dict = { 
    1: "spam",
    2: "eggs",
    3: "foo",
    4: "bar",
    8: "anything",
    9: "nothing" }

Or if the leading zeros are really important, use strings for the keys.

28
ответ дан 1 December 2019 в 17:29
поделиться

Python принимает 008 и 009 как восьмеричные числа, поэтому ... недействительно.

Вы можете подняться только до 007, тогда следующее число будет 010 (8), затем 011 (9 ). Попробуйте использовать его в интерпретаторе Python, и вы поймете, что я имею в виду.

10
ответ дан 1 December 2019 в 17:29
поделиться

In Python (and many other languages), starting a number with a leading "0" indicates an octal number (base 8). Using this leading-zero notation is called an octal literal. Octal numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, etc. So 08 (in octal) is invalid.

If you remove the leading zeros, your code will be fine:

some_dict = 
{ 
    1: "spam",
    2: "eggs",
    3: "foo",
    4: "bar",
    8: "anything",
    9: "nothing" 
}
8
ответ дан 1 December 2019 в 17:29
поделиться

@DoxaLogos is right. It's not that they're invalid keys - they're invalid literals. If you tried to use them in any other context, you'd get the same error.

7
ответ дан 1 December 2019 в 17:29
поделиться

That is because, when you start a number with a 0, it is interpreted as an octal number. Since 008 and 009 are not octal numbers, it fails.

A 0 precedes an octal number so that you do not have to write (127)₈. From the Wikipedia page: "Sometimes octal numbers are represented by preceding a value with a 0 (e.g. in Python 2.x or JavaScript 1.x - although it is now deprecated in both)."

2
ответ дан 1 December 2019 в 17:29
поделиться
Другие вопросы по тегам:

Похожие вопросы: