是壮壮啊 发表于 2020-4-6 21:51:15

Python 除2取余 for循环和 while循环的问题

def binbin(x):
    temp = []
    result1 = ""
    result2 = ""
    while x:
      y = x%2
      temp.append(y)
      x = x//2

    for each in temp:
      
      result2 += str(temp.pop())
    return result2
这个运行之后结果一直是不完整的,请教一下为什么

qiuyouzhi 发表于 2020-4-6 21:53:50

改成while temp:
def binbin(x):
    temp = []
    result1 = ""
    result2 = ""
    while x:
      y = x%2
      temp.append(y)
      x = x//2

    while temp:
      result2 += str(temp.pop())
    return result2

print(binbin(9))

8178919 发表于 2020-4-6 21:57:03

def binbin(x):
    temp = []
    result1 = ""
    result2 = ""
    while x:
      y = x%2
      temp.append(y)
      x = x//2

    while temp:
      result2 += str(temp.pop())
    return result2

print(binbin(9))

是壮壮啊 发表于 2020-4-6 21:58:21

qiuyouzhi 发表于 2020-4-6 21:53
改成while temp:

for 的话为什么会少呢?? 我拿6 实验 只会出现“11”,这一块搞不明白

qiuyouzhi 发表于 2020-4-6 22:03:45

是壮壮啊 发表于 2020-4-6 21:58
for 的话为什么会少呢?? 我拿6 实验 只会出现“11”,这一块搞不明白

假设输入9:
你删除掉一个,for循环遍历到下一个
你又删除掉一个,for循环又遍历到下一个
这时后原来二进制的1001已经被耗完了,
所以只会打印2个

是壮壮啊 发表于 2020-4-6 22:14:12

qiuyouzhi 发表于 2020-4-6 22:03
假设输入9:
你删除掉一个,for循环遍历到下一个
你又删除掉一个,for循环又遍历到下一个


打印的10 1是第一个1,0是第三个0吗? 每次循环跑了两位??
还是没搞清楚这个逻辑temp.pop()第一次弹出1,result 变成1,temp剩下100,之后每次不是一位一位的减少吗?四次之后temp变成空的?

qiuyouzhi 发表于 2020-4-7 07:49:01

是壮壮啊 发表于 2020-4-6 22:14
打印的10 1是第一个1,0是第三个0吗? 每次循环跑了两位??
还是没搞清楚这个逻辑temp.pop()第一次弹出1 ...

while是一位一位的减少,而for不是。
for是依次遍历,如果你删掉一个,就会少一个
举个例子:
>>> a =
>>> for each in a:
        a.append(each)
你会发现,它进入了死循环,
证明for是实时在变换的。

是壮壮啊 发表于 2020-4-7 22:30:13

qiuyouzhi 发表于 2020-4-7 07:49
while是一位一位的减少,而for不是。
for是依次遍历,如果你删掉一个,就会少一个
举个例子:


谢谢
页: [1]
查看完整版本: Python 除2取余 for循环和 while循环的问题