How to make Python interpreter a little more strict?

Chris Warrick kwpolska at gmail.com
Sat Mar 26 06:40:55 EDT 2016


On 25 March 2016 at 13:06, Aleksander Alekseev <afiskon at devzen.ru> wrote:
> Hello
>
> Recently I spend half an hour looking for a bug in code like this:
>
> eax at fujitsu:~/temp$ cat ./t.py
> #!/usr/bin/env python3
>
> for x in range(0,5):
>     if x % 2 == 0:
>         next
>     print(str(x))
>
> eax at fujitsu:~/temp$ ./t.py
> 0
> 1
> 2
> 3
> 4
>
> Is it possible to make python complain in this case? Or maybe solve
> such an issue somehow else?
>
> --
> Best regards,
> Aleksander Alekseev
> http://eax.me/
> --
> https://mail.python.org/mailman/listinfo/python-list

You were probably looking for `continue`. This is just bad memory on
your part, and Python can’t help. In the REPL, typing an object name
is legal and helpful. Other languages might crash, sure — but they
usually don’t have a REPL like Python does.

That said, this code is designed badly. Here’s a better idea (also,
note the fixed print statement):

for x in range(0, 5):
    if x % 2 != 0:
        print(x)

Or even with a more suitable range() that adds 2 instead of 1 in each step:

for x in range(1, 5, 2):
    print(x)

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16



More information about the Python-list mailing list