Micropython interpreter differences between cmd line and program



  • When writing code I sometimes try out syntax I'm unsure of at the command line & if it works I put it in the program I'm working on. My observation is that the interpreter parsing is somewhat forgiving, if unpredictably so, at the command line but less so with programs, particularly if the syntax is not strictly legal.

    For example

    >>> for i in range (2): print('i is 1') if i else 'i is zero'
    ... 
    'i is zero'
    i is 1
    

    or

    >>> for i in range (2): print('i is 1') if i else ('i is zero')
    ... 
    'i is zero'
    i is 1
    

    I have no idea why this instruction runs or why the quotes are displayed for the first print not the other. If I try the same instruction as a one line program

    >>> Running test.py
    
    >>> 
    >>> 
    i is 1
    

    the results are different. If it's the same interpreter doing the parsing, why the different response to a command line instruction & the same instruction in a program?



  • @robert-hh said in Micropython interpreter differences between cmd line and program:

    for i in range (2): print('i is 1' if i else 'i is zero')

    The if else inside (the print brackets) I should have known, to much time inside python 2.7, that's my problem. Tnx Rob.



  • @kjm REPL always prints the result of the expression which it gets as input. In this case, it's the string. Since it executes code, it also prints the result from the code execution. When you import that code snippet, the expression results are not printed.
    For instance, if you just take the statement:
    1
    If you enter that in REPL, it will evalute that and respond with the result:
    1
    If you put that single statement into a script an run it, nothing is printed.
    That explains the difference. So if you look at your code, for i=0 the expression 'i is zero' is executed, for i=1 the expression print('i is 1'). That results in different text being shown. Besides that, didn't you intend to have a different statement:

    for i in range (2): print('i is 1' if i else 'i is zero')
    

    which will print:

    i is zero
    i is 1
    

    after the second enter closing the for loop.


Log in to reply
 

Pycom on Twitter