当条件满足时,While循环不终止

2024-09-30 14:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在用Python编程时,我遇到了这样一种情况:while循环即使在满足条件之后也没有终止

代码如下:

print('--- Alex\'s Calculator ---')
print('1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT')
x = int(input())

command = ' Enter Your Two numbers To Perform The Operation : '
def ini():
    a = int(input())
    b = int(input())
    return a, b
def resultoo():
    result = ' Your Result after Performing The Operation from {} and {} is {}'
    print(result.format(a,b,c))
    print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
    x = int(input())

while x < 5:
    if x == 1:
        print(command)
        a, b = ini()
        c = a + b
        resultoo()
    elif x < 5:
        break

Tags: thetoinputyourdef编程resultoperation
3条回答

您可以使用globalvar来实现此目的,更改this:

def resultoo():
    result = ' Your Result after Performing The Operation from {} and {} is {}'
    print(result.format(a,b,c))
    print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
    x = int(input())

分为:

def resultoo():
    global x
    result = ' Your Result after Performing The Operation from {} and {} is {}'
    print(result.format(a,b,c))
    print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
    x = int(input())

解释:

x是一个全局参数,它在函数闭包外是相同的,但在闭包内是不同的,函数有自己的参数,因此如果要更改在函数外初始化的全局参数,则需要在前面调用global语句,这将使x成为全局x

当输入选项5时,您希望退出。你知道吗


我补充道

import sys

改变了

elif x < 5:

elif x == 5:

并补充道

sys.exit(0)

我还添加了getMenu()函数

以下是在我的编辑器中运行的完整代码:

import sys


def ini():
    command = ' Enter Your Two numbers To Perform The Operation : '
    print(command)
    a = int(input())
    b = int(input())
    return a, b


def resultoo(a, b, c):
    result = ' Your Result after Performing The Operation from {} and {} is {}'
    print(result.format(a, b, c))


def getMenu(x):
    if x == 0:
        print("Choose menu item")
        x = int(input())
    elif x != 0:
        print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
        x = int(input())

    return x


def main():
    x = 0
    while x < 5:
        print('\n\n1. ADDition')
        print('2. SUBstraction')
        print('3. MULtiply')
        print('4. DIVide')
        print('5. EXIT\n')

        x = getMenu(x)

        if x == 1:
            a, b = ini()
            c = a + b
            resultoo(a, b, c)

        elif x == 5:
            sys.exit(0)

        else:
            print("No valid menu item")


if __name__ == '__main__':
    print('                                                     ')
    print('                       Alex\'s Calculator                      -')
    main()

我还格式化了您的代码(alt+Enter-in-Pycharm)以符合PEP8标准;)

正如kuro在注释中指定的那样,x不能被while循环看到,因为它是resulttoo()的本地对象。你知道吗

要轻松解决此问题,只需添加:

return x

在resultoo()的末尾

以及

x = resultoo()

在你的while循环中

相关问题 更多 >