python - 添加二进制数 Python

标签 python

我正在尝试使用简单的代码在 python 中添加两个二进制数。有人能告诉我为什么这不起作用吗?非常感谢!我尝试分解代码,但当我分解它时,它们都单独工作。但当然,当我把它放在一起时,它不起作用。

我是 Python 的初学者,因此非常感谢您的解释。感谢您的帮助!

#Enter numbers and define variables
number1=input("Enter 1st Binary Number:")
number2=input("Enter 2nd Binary Number:")
x1 = number1[0]
x2 = number1[1]
y1 = number2[0]
y2 = number2[1]

#Convert to integers from strings
int(x1)
int(x2)
int(y1)
int(y2)



#Digit 1 of answer and digit to be carried
if x1+y1==0:
  a1 = 0
  c1 = 0
if x1+y1==1:
  a1 = 1
  c1 = 0
if x1+y1==2:
  a1 = 0
  c1 = 1




#Digit 2 of answer and digit to be carried
if x2+y2+c1==0:
  a2=0
  c2=0
if x2+y2+c1==1:
  a2=1
  c2=0
if x2+y2+c1==2:
  a2=0
  c2=1
if x2+y2+c1==3:
  a2=1
  c2=1

#Digit 3 of answer
c2=a3

if a3==1:
  print ("a3" + "a2" + "a1")

if a3==0:
  print ("a2" + "a1")

它给出的错误是未定义 c1 和 a1。

再次感谢!

最佳答案

我将建议使用简单的代码来添加两个二进制数。

number1 = str(input("Enter 1st Binary Number"))
number2 = str(input("Enter 2nd Binary Number"))
intSum = int(number1, 2) + int(number2, 2)  #int() takes first argument as string
result = bin(intSum)[2:]  #remove 0b
print result

输出

Enter 1st Binary Number1111
Enter 2nd Binary Number1010
11001

关于python - 添加二进制数 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44793549/

相关文章:

python - 如何为 python 类定义 "in"

python - 如何在DataFrame中查找具有指定值的行

python - 计算数组列表的计数百分比

python - 从 C 代码序列化数组数据,在 Python 中反序列化

python - 我想捕获两个正则表达式匹配之间出现的文本

python - 从 Python 中的数据帧创建正则表达式匹配列表,然后计算匹配数

python - 如何通过 ftp 在 python 中下载大文件(带监控和重新连接)?

python - 如何在 Apache Beam 中计算标准偏差

python - 如何在我的 WSGI apache 上为 Django 执行多个进程?

python - 在 IPython 中检测哪个 CMD/终端调用用于启动 IPython