在python中使用If/elif语句后,如何使while循环终止?

在python中使用If/elif语句后,如何使while循环终止?,python,while-loop,Python,While Loop,我试图在python中创建一个while循环,但该循环一直无限循环 以下是我目前掌握的情况: def pvalue(num): ans = '' while num > 0: if 1 <= num <= 9: ans += 'B' num -= 1 if num >= 10: ans += 'A' num -= 10 r

我试图在python中创建一个while循环,但该循环一直无限循环

以下是我目前掌握的情况:

def pvalue(num):
    ans = ''
    while num > 0:
        if 1 <= num <= 9:
            ans += 'B'
            num -= 1
        if num >= 10:
            ans += 'A'
            num -= 10
    return ans
def pvalue(num):
ans=“”
当num>0时:

如果1,您可能想了解以下内容

至于你的代码:

def pvalue(num):
    ans = ''
    while num > 0:
        if num >= 10:
            ans += 'A'
            num -= 10
        else:
            ans += 'B'
            num -= 1
    return ans

更好的是,当
num==9
的情况现在得到正确处理

使用break语句退出循环

def pvalue(num):
    ans = ''
    while num > 0:
        if 1 <= num <= 9:
            ans += 'B'
            num -= 1
        if num >= 10:
            ans += 'A'
            num -= 10
        if num<=0:
            break
    return ans
def pvalue(num):
ans=“”
当num>0时:

如果有一个break语句,我应该把它放在哪里?同样按照你的逻辑,它应该是
你希望你的代码做什么?正如Walle所说,您可以在if条件中使用中断,但是,我相信您的代码可以更干净、更符合python。。。但是我还需要知道你想做什么你想让代码做什么?你在期待什么?这是一个很好的基础设计练习。指定num可以接受的不同值的预期行为。除了使用else而不是第二个if语句之外,我看不出这与我的代码有什么不同。@Miraj50循环仍然是无限的。@我复制并粘贴了编辑过的代码,并对0到29之间的数字运行了它。我现在无法重现无限循环。在您的第一个版本中,您在第一个if语句
1中编写了