模块调用错误.不能循环输入功能



我想调用模块函数和循环。但当我循环时,输入窗口只打开一次,不显示任何内容。

#This is my module function. file name is calc.py
def gain1():
a = int(input("Type first number : "))
b = int(input("Type Second number : "))  

if a % 2 == 0 : 
a = a + 1
elif a % 2 == 1 :
a = a - 1
if b % 2 == 0 :
b = b + 1
elif b % 2 == 1 :
b = b - 1
print(a+b)

sum1 = gain1()

这是我的主文件

import calc #import gain1 function
d = 1
while d < 10:
print(calc.sum1)
d = d + 1

这就是的结果

Type first number : 3
Type Second number : 4
7
None
None
None
None
None
None
None
None
None

我想重复打字的东西,但它只重复一次,9次重复显示无。我只是想知道为什么。你能告诉我问题出在哪里吗?

我不建议从另一个文件获取输入,相反,您可以在函数中使用变量。你可以使用这样的东西:

def gain1(a,b):
...

您仍在获得投入,但方式更好。您的代码可能如下所示:

calc.py应该看起来像:

#This is my module function. file name is calc.py
def gain1(a,b):
# asigning variables from above
if a%2 == 0 : 
a = a + 1
elif a%2 == 1 :
a = a - 1
elif b%2 == 0 :
b = b + 1
elif b%2 == 1 :
b = b - 1
#you need to return it to not display None
return a+b

要清除None,您需要执行return a+b。通过生成def gain(a,b),您可以从调用函数中获得输入。

main.py应该看起来像:

import calc #import gain1 function
d = 1
#getting variables
input1 = int(input("enter first number: "))
input2 = int(input("enter second number: "))
while d < 10:
# adding numbers into the function in calc.py
print(calc.gain1(input1,input2))
d = d + 1

在这里,你可以输入数字,然后他们将它们分配到calc.gain(input1,input2)上。这是解决问题所需的所有代码。我希望它能有所帮助!

如果您想循环输入,只需将其放入循环中,或者您可以在calc.py中的函数gain1中循环。

最新更新