Search code examples
pythonpython-3.xcommentsjupyter

Same Line Commenting on Python with ls


I am a student taking my first Python class and am using Anaconda & Jupyter for Python 3. I have read up on commenting and understand they begin with a hash mark ( # ) and whitespace character and continue to the end of the line. It is my understanding that they should not affect the execution of the code.

When I run "ls" in order to display my working directory it runs perfectly fine. However, when I add a comment just above it, it does not run. Can someone please help me understand why this might be? Pictures attached.

This is the error I receive with a comment:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-96a2904231e9> in <module>()
      1 # show working directory
----> 2 ls
NameError: name 'ls' is not defined

run 1 run 2


Solution

  • Simply, your working on Jupyter with Python kernel and so the bash command cannot be used. However, you can use a magic for bash such that

    %%bash
    ls
    

    or for windows

    %%cmd
    dir
    

    One more thing is that I mentioned as a comment, such as:

    !ls
    !dir