我的Python程序无法调用while循环中导入的源代码

xsuvu9jc  于 2023-05-19  发布在  Python
关注(0)|答案(2)|浏览(165)

我是一个新的程序员,我写的代码为main.py,以确定最大值和最小值,如果值是相等的:

def compare():

    x,y,z = 0,0,0
    x = input("Enter the First Number: ")
    y = input("Enter the Second Number: ")
    z = input("Enter the Third Number: ")
    numbers = [x,y,z]

    if numbers[0] == numbers[1]:

        if numbers[0] == numbers[2]:

            print("Numbers are Equal which is = ",numbers[0])

        else:

            print("The Maximum number is = ",max(numbers))
            print("The Minimum number is = ",min(numbers))
            
    else:

        print("The Maximum number is = ",max(numbers))
        print("The Minimum number is = ",min(numbers))

compare()

run.py中:

import main

i = 1

while i >= 1: # I did infinite loop to make program runs repeatedly
    main
    i = i + 1

我本想不停地跑,但它只跑了一次,就停下来了。

ljo96ir5

ljo96ir51#

欢迎来到StackOverflow!您已经导入了主模块,但需要从其中调用compare函数。
你已经在注解中得到了一些很好的解释,但这里是如何在www.example.com中修复代码run.py:

import main

i = 1

while i >= 1:
    main.compare()
    i = i + 1

由于你是一个新的程序员,我推荐这篇关于在Python中导入的文章:https://realpython.com/python-modules-packages/#the-import-statement

mwkjh3gx

mwkjh3gx2#

不应该将对compare()的调用放在模块本身中,除非模块作为顶级脚本运行。
而是调用模块在循环中定义的函数。

def compare():

    x,y,z = 0,0,0
    x = input("Enter the First Number: ")
    y = input("Enter the Second Number: ")
    z = input("Enter the Third Number: ")
    numbers = [x,y,z]

    if numbers[0] == numbers[1]:

        if numbers[0] == numbers[2]:

            print("Numbers are Equal which is = ",numbers[0])

        else:

            print("The Maximum number is = ",max(numbers))
            print("The Minimum number is = ",min(numbers))
            
    else:

        print("The Maximum number is = ",max(numbers))
        print("The Minimum number is = ",min(numbers))

if __name__ == '__main__':
    compare()
import main

while True:
    main.compare()

相关问题