3
# [ ] 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

Karen Jiang
  • 175
  • 1
  • 3
  • 12

3 Answers3

16

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()
Justin
  • 707
  • 7
  • 13
1

%%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

Andrew_Lvov
  • 4,621
  • 2
  • 25
  • 31
0

You have to write

%%writefile

in the first line.

Anton Zubochenko
  • 153
  • 1
  • 11