[英]Python code to convert Integer into Binary
I need a code in Python 3.3 to convert an integer into binary. 我需要Python 3.3中的代码将整数转换为二进制。 This is my first try:
这是我的第一次尝试:
a = input(str("Please Enter a Number")
if a == float:
print (1)
else print(0)
b = a/2
while True:
if b == float:
print(1)
else print(0)
I don't know why I keep getting errors with the if a == float:
. 我不知道为什么我继续得到
if a == float:
错误if a == float:
。 And I know that the rest of the code is wrong too, but this :
makes me crazy. 而且我知道其余的代码也是错的,但是这个
:
让我发疯。
Your code has a lot of issues: 您的代码有很多问题:
isinstance
to see if an object is a float. isinstance
来查看对象是否为浮点数。 I assume this is what you are trying to do with a == float
. a == float
。 But, that doesn't make sense because, in Python 3.x., input
always returns a string object. input
总是返回一个字符串对象。 So, a
is a string. a
是一个字符串。 However, if float
is actually a variable, then you should change its name. float
实际上是一个变量,那么您应该更改其名称。 Naming a variable float
is a bad practice since it overrides the built-in. float
是一种不好的做法,因为它会覆盖内置函数。 else
. else
的末尾错过了一个冒号。 str
in the first line is unnecessary (not an error, but I just thought I'd mention it). str
是不必要的(不是错误,但我只是想我会提到它)。 However, instead of fixing all this, I'm going to introduce you to the bin
built-in: 但是,我不是要修复所有这些,而是要向你介绍内置的
bin
:
>>> n = 127
>>> bin(n)
>>> # The "0b" at the start means "binary".
'0b1111111'
>>> # This gets rid of the "0b"
>>> bin(n)[2:]
'1111111'
>>>
It was built explicitly to do what you are trying to do. 它是明确构建的,用于执行您要执行的操作。
Also, here are some references on Python you might enjoy: 另外,以下是您可能喜欢的Python的一些参考:
http://www.tutorialspoint.com/python/python_overview.htm http://www.tutorialspoint.com/python/python_overview.htm
http://wiki.python.org/moin/BeginnersGuide/Programmers http://wiki.python.org/moin/BeginnersGuide/Programmers
You can just use the bin
function: 你可以使用
bin
函数:
>>> bin(100)
'0b1100100'
Ignore the 0b
infront of the string. 忽略字符串前面的
0b
。 You can always get the raw binary numbers using using bin(your_numer)[2:]
. 您始终可以使用
bin(your_numer)[2:]
获取原始二进制数。
Also, you can get this using the format
function: 此外,您可以使用
format
函数来获取此信息:
>>> format(100, 'b')
'1100100'
如果你需要用二进制打印它你可以这样做:print(bin(a))
This is what i made 这就是我所做的
while True:
print("FIND OUT WHAT BINARY THIS IS")
space = " "
num1 = int(input())
while num1 > 0:
if num1 % 2 == 0:
space = space + "0"
else:
space = space + "1"
num1 = int(num1 / 2)
else:
space = space[::-1]
print(space)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.