首页 > 解决方案 > String concatenation in while loop not working

问题描述

I'm trying to create a Python program that converts a decimal to binary.

Currently I have

working = int(input("Please select a non-negative decimal number to convert to binary.  "))
x = ()

while working !=0:
    remainder = working % 2
    working = working // 2

    if remainder == 0:
      x = remainder + 0
      print (working, x)

    else:
     x = remainder + 1
    print (working, x)

print ("I believe your binary number is " ,x)

The while works on it's own if I print after that, but the if/else doesn't. I am trying to create a string that is added to with each successive division. Currently, if my starting int is 76, my output is

38 0
38 0
19 0
19 0
9 2
4 2
2 0
2 0
1 0
1 0
0 2

I am trying to get my output to instead be

38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100

This is my first attempt at string concatenation and I've tried a few variations of the above code to similar results.

标签: python

解决方案


问题是您没有使用字符串。您首先为 x 创建一个空元组,然后用整数值覆盖它。

要执行您正在尝试的操作,您需要将x其视为字符串,并将字符串文字附加'0''1'它上面。

试试这个:

working = int(input("Please select a non-negative decimal number to convert to binary.  "))
x = ''

while working !=0:
    remainder = working % 2
    working = working // 2

    if remainder == 0:
        x += '0'
        print (working, x)

    else:
        x += '1'
        print (working, x)

print ("I believe your binary number is " , x[::-1])

请注意x最初如何声明为空字符串''而不是空元组()。这使得当您+=稍后使用运算符将​​ 0 或 1 附加到它时,它被视为字符串连接而不是加法。


推荐阅读