search

Home  >  Q&A  >  body text

python - while if else循环判断值的顺序

def showMaxFactor(num):

count=num//2
while count>1:
    if num % count==0:
        print('%d最大的约数是%d'%(num,count))
        break
    count-=1
else:
    print('%d是素数!'%num)

num=int(input('请输入一个数:'))
showMaxFactor(num)
请输入一个数:9
9最大的约数是3

运行过程:count=9//2=4>1,判断9%4=1!=0. 所以count=4-1 在循环while吗

是这样的吗

PHP中文网PHP中文网2813 days ago783

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:20:52

    The understanding of the running process is correct, but there is something wrong with the code.
    Match based on python代码的缩进规则,最后一个else不能和if. You can write it like this:

    while count>1:
        if num % count==0:
            print('%d最大的约数是%d'%(num,count))
            break
        count-=1
    if count == 1:
        print('%d是素数!'%num)

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:20:52

    Yes, unless you break above or count>1, it must still be in the while loop, and the syntax mentioned above hahaha

    reply
    0
  • Cancelreply