【发布时间】:2022-06-13 22:58:17
【问题描述】:
我试图让我的代码在每次有人转到另一个文件时将一个数字增加 1,并在该文件中使相同的数字再次增加 1,但我很难这样做。
number.py中的代码:
def number():
number=0
print(number)
other1.py中的代码:
import number
ask = input("Do you want to load another file? ")
if ask == "yes":
number
print(number)
else:
print("Okay")
我并没有真正得到错误。我只是没有得到我想看到的号码。我想看到 1,但我得到了
<module 'number' from '/home/runner/Idek/number.py'>
【问题讨论】:
-
为什么不将所有代码保存在一个文件中?无论如何,错误是因为你应该使用
print(number.number()) -
是的,我知道我可以轻松做到这一点。我真的很懒,我不想再写 4 行代码,但确实有效,非常感谢!
-
另一个问题,@QWERTYL 确实解决了我的一个问题,但是当我尝试将 other1.py 中的代码更改为
number+=1时,我也无法让它加 1@ 我收到另一个错误Traceback (most recent call last): File "main.py", line 1, in <module> exec(open("other1.py").read()) File "<string>", line 6, in <module> TypeError: unsupported operand type(s) for +=: 'module' and 'int' -
再次,您需要使用
number.number += 1。但请记住,您将number设为函数,而不是整数(函数中的变量不是全局变量)。 -
我还有很多东西要学,无论如何,再次感谢我很感激!
标签: python python-3.x