【问题标题】:How do I increment a number that is located in another file in Python?如何增加位于 Python 中另一个文件中的数字?
【发布时间】: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 &lt;module&gt; exec(open("other1.py").read()) File "&lt;string&gt;", line 6, in &lt;module&gt; TypeError: unsupported operand type(s) for +=: 'module' and 'int'
  • 再次,您需要使用number.number += 1。但请记住,您将 number 设为函数,而不是整数(函数中的变量不是全局变量)。
  • 我还有很多东西要学,无论如何,再次感谢我很感激!

标签: python python-3.x


【解决方案1】:

你可以使用:

print(number.number())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2013-08-09
    相关资源
    最近更新 更多