while循环中的字符串连接不起作用

时间:2019-02-25 04:58:02

标签: python

我正在尝试创建一个将十进制转换为二进制的Python程序。

目前我有

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)

如果我在那之后打印,则while靠自己工作,但是if / else不能。我正在尝试创建一个字符串,该字符串将添加到每个连续的除法中。当前,如果我的起始int为76,则输出为

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

我正在尝试将输出改为

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

这是我第一次尝试进行字符串连接,并且我尝试了上述代码的一些变体以达到相似的结果。

4 个答案:

答案 0 :(得分:1)

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

要执行您想做的事情,您需要将login_user = User.objects.get(email=request.POST['email']) 视为字符串,并在其后附加字符串文字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时将其视为字符串串联而不是加法。

答案 1 :(得分:1)

您提供的代码存在一些问题:

  1. x()开头,在任何情况下,您都无需在其上串联字符串,而是在循环中添加数字。
  2. 您尝试添加数字而不是添加数字,因此如果可行,结果将被颠倒。
  3. 您的第二个print不在条件内,因此输出是重复的。

您需要做的是使用空字符串初始化x,然后在字符串前添加字符串:

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

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

    if remainder == 0:
        x = "0" + x
    else:
        x = "1" + x

    print (working, x)

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

输出:

λ python convert-to-binary.py
Please enter a non-negative decimal number to convert to binary: 76
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
I believe your binary number is 1001100

答案 2 :(得分:0)

应该是

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 = x + str(remainder)
      print (working, x)

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

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

答案 3 :(得分:0)

将代码更改为以下代码:

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

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

在您的代码中,python解释为int,您必须将其强制转换为字符串。

另一种方法是使用内置函数bin(working),将数字直接转换为二进制值。