Спасибо, я читаю это и работаю над пониманием этого. Все наши задания с этим профессором странные и обычно сложные, даже если мы только начали изучать язык.

ал вопрос ранее, но столкнулся со второй проблемой.

Я пишу программу, которая читает в текстовом файле и выполняет весь код в файле. Это для класса, и мы должны использоватьexec()

Я получаю эту ошибку при запуске кода, и бесчисленные поиски не привели меня к решению.

Traceback (most recent call last):
  File "doxecute.py", line 28, in <module>
    replace_code(statements, contents)
  File "doxecute.py", line 17, in replace_code
    contents = contents.replace("{%" + statement + "%}", statement)
TypeError: Can't convert 'NoneType' object to str implicitly

Код

import sys
import re



def sortecute(data): 
    funcs = re.findall(r'{%(.*?)%}',data,re.DOTALL)#find executable statements
    return funcs

def replace_code(statements, contents):
    for statement in statements:
        if not statement[5:].startswith("print("):
            exec(statement[5:]) #execute code after the (letter)
            contents = contents.replace("{%" + statement + "%}", "")
        else:
            statement = exec(statement[5:])#error is here
            contents = contents.replace("{%" + statement + "%}", statement)

    print(contents)

f = open(sys.argv[1],"r")
contents = f.read()
f.close()

statements = sortecute(contents) #get data from file
statements  = sorted(statements) #sorts by letter

replace_code(statements, contents)

это файл, который я прочитал.

The number {% (c) print(x) %} is a random number between 1 and 6
inclusive. If we multiply it by 2, we get {% (d) print(2*x) %}.

What's interesting is that the statements may appear out of order in the
document. {% (a) import random %} Thus I might generate the random
number in a location in the document well after referencing it.
{% (b) x = random.randint(1,6) %}

Я не могу узнать, как получить значение оператора для exec. Может кто-нибудь объяснить мне, как правильно использовать это в порядке, указанном ниже

You will need to use the exec function in Python. To get the output back, you will need to redirect output to your own stream. Your program should accept a filename as a command-line argument to operate on [8]

Ответы на вопрос(1)

Ваш ответ на вопрос