python - while if else循环判断值的顺序
PHP中文网
PHP中文网 2017-04-18 10:18:52
0
2
730

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中文网

认证高级PHP讲师

reply all(2)
洪涛

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)
Ty80

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!