python - 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.
解决方案
问题是您没有使用字符串。您首先为 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 附加到它时,它被视为字符串连接而不是加法。
推荐阅读
- javascript - 从列表中过滤掉作为数组中另一个字符串的子字符串的所有字符串
- javascript - file-saver.js,调用 saveAs 时出现错误?
- javascript - 使用切换手风琴切换切换图像,wordpress avada
- amazon-web-services - 如何使用/不使用 Glue Crawler 自动化 ALTER TABLE ADD PARTITIONS
- html - 在 flexbox 中每行放置 2 个项目
- javascript - Safari 上的正则表达式错误。? 前面的token是不可量化的
- r - R - 动态变量名称和嵌套循环
- python - 用于基于多个条件的迭代的 Python 程序
- c# - C# GCP auth2.0 403 不匹配重定向
- keras - HSV图像可以用于CNN训练吗