当我学习 python 时,我只是想想出我可以编写的程序的想法。然后我想是否有可能编写一个程序,从用户那里获取输入,然后将其作为代码写入 .py 文件。
如果我们要运行那个 .py 文件,我们应该得到我们输入的输出,就像 print("Hello World")
的工作方式一样。
有什么想法可以写成这样吗?
编辑:我还在学习,所以请解释一下,我只知道基本的打印代码和一些数学运算:)
答案 0 :(得分:0)
您可以使用:
file = open("test.py", "w") # Open a file for writing(overwrites previous files) and puts it in the file variable
file.write("print('Hello world')") # .write() adds content of print('Hello world')
file.close() # Close the file
您可以使用:
file = open("test.py", "w")
file.write("print('Hello world')\n")
file.write("print('Hello world2')\n")
file.close()
对于多行代码