python类型转换错误异常_[Python的]类型错误:无法格式化字符串转换期间,所有参数...

1586010002-jmsa.png

I have a program that's supposed to calculate Hamming Code for even parity with a 7-bit integer, here is the program:

data=list(input("Enter a 7-bit binary integer:"))

if (data[0]+data[1]+data[3]+data[4]+data[6])%2 == 0:

data.insert(8, "0")

else:

data.insert(8, "1")

if (data[0]+data[2]+data[3]+data[5]+data[6])%2 == 0:

data.insert(7, "0")

else:

data.insert(7, "1")

if (data[1]+data[2]+data[3])%2 == 0:

data.insert(6, "0")

else:

data.insert(6, "1")

if (data[4]+data[5]+data[6])%2 == 0:

data.insert(3, "0")

else:

data.insert(3, "1")

print("Your 7-bit binary integer with Hamming Code parity bits:",data)

However, when I run this program I get this error:

Traceback (most recent call last):

File "C:\Python34\hamcode.py", line 3, in

if (data[0]+data[1]+data[3]+data[4]+data[6])%2 == 0:

TypeError: not all arguments converted during string formatting

I'm not sure what this means and how to fix it, any responses would be greatly appreciated.

Thanks!

解决方案

The type of data is a list with strings, not a list of integers:

>>> data=list(input("Enter a 7-bit binary integer:"))

Enter a 7-bit binary integer:123456

>>> data

['1', '2', '3', '4', '5', '6']

As such, you're trying to concatenate strings and you're not summing numbers as expected:

if (data[0]+data[1]+data[3]+data[4]+data[6])%2 == 0:

To fix it, you'll need to change all the strings into numbers first:

data = [int(x) for x in data]

At the moment this line is adding the strings in the list back together to a single string and you're trying to use string formatting on that string (with % 2 which the syntax for string formatting). The operator % is the modulo operator when applied to a number but it's the string formatting operator when applied to a string.

In other words, you're doing:

'123456' % 2

which means Python is trying to insert that 2 into the string 123456 at the appropriate place (which isn't possible because there is no place designated for it).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值