Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python jupyter magic %%writefile returns SyntaxError: invalid syntax

# [ ] The following program asks the user for a circle radius then display the area and circumference
# Modify the program so it only displays the information when executed directly
# The program should not display anything if it is imported as a module 


%%writefile main_script.py

def main(): 
    from math import pi

    def circle_area(r):
        return pi * (r ** 2)

    def circle_circumference(r):
        return  2 * pi * r

    radius = float(input("Enter radius: "))
    print("Area =", circle_area(radius))
    print("Circumference =", circle_circumference(radius))

if __name__="__main__":
    main()


----------
  File "<ipython-input-3-70ba6a5d5e98>", line 6
    %%writefile main_script.py
    ^
SyntaxError: invalid syntax

How do I fix this??

Its an exercise, but I just dont get how this system command works,can you explain?

ignore:for word requirements ignore:for word requirements

like image 476
Karen Jiang Avatar asked May 11 '26 06:05

Karen Jiang


2 Answers

This is not working for you because you have a comment in the first line(s) of your code in the notebook cell. If you move your comments underneath the magic command it will write the file.

%%writefile main_script.py

# Add all of your comments here after the magic command

def main(): 
    def add_my_code(here):
        return here

if __name__="__main__":
    main()
like image 95
Justin Avatar answered May 13 '26 20:05

Justin


%%writefile main_script.py

writefile is a command of Jupyter notebook, it's not part of a source code.

So it will give you a syntax error as a part of Python code. However, executed in Jupyter Notebook will tell it to write contents following this command to a file specified after writefile, i.e. to main_script.py

Look at how-to-append-a-file-with-a-newline-using-writefile-a-command-in-jupyter for more info

like image 44
Andrew_Lvov Avatar answered May 13 '26 20:05

Andrew_Lvov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!