Python 什么';这个节目的意义是什么?
我知道这个程序将十进制转换成二进制,事实上我只是一个编程初学者,python是我的起始语言 回答这些问题对我有很大帮助Python 什么';这个节目的意义是什么?,python,Python,我知道这个程序将十进制转换成二进制,事实上我只是一个编程初学者,python是我的起始语言 回答这些问题对我有很大帮助 def bin(i): s = "" # what do we mean by s="" ? does it mean s=0? while i: # where is the condition ? if i & 1: # what is the equivalent for '&'? when I put 'and' ins
def bin(i):
s = "" # what do we mean by s="" ? does it mean s=0?
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
s = "1" + s # ?
else:
s = "0" + s
i = i//2 # why?
return s
问题是我想弄清楚输入和输出之间发生了什么?
还有一件事,我们可以把这个代码扩展到浮点数吗?让我试着一次回答一个问题;然后,您应该能够将它们全部拼接在一起:
s = "" # what do we mean by s="" ? does it mean s=0?
s
现在是一个空字符串。您可以向其中添加其他字符串来连接它们。事实上,这就是后面在s=“1”+s
行中所做的。看一看:
In [21]: "1" + ""
Out[21]: '1'
In [22]: "1" + "2"
Out[22]: '12'
In [23]: s = ""
In [24]: "1" + s
Out[24]: '1'
看看字符串连接是如何工作的
下一步:
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
i = i//2
啊!!在许多编程语言(包括python)中,当在条件语句(如if
或while
)中使用时,值为0
的整数计算为布尔值False
)。所有非零值的计算结果均为True
因此,这个while循环表示,而我不取0的值。请注意,由于稍后对i
进行除法,i
将永远不会出现负值,因此此循环将终止
下一步:
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
i = i//2
i&1
是一个位智能和运算符。假设i
的值为5
。然后,i
的二进制表示是101
。1
的二进制表示形式只是1
或001
(因为我们将其与101
进行比较)。现在,我们执行逐位AND,它基本上比较每对对应位,如果它们都是1
s(0
),则输出1
)。因此,比较101
和001
的结果是001
,它转换为1
的值。这意味着当你用i
除以2
时,你会得到1
的余数。由于唯一的可能性是1
(在if语句中计算为True
)或0
(在if语句中计算为False
),因此它很容易以这种二分法的方式使用(在s
中添加“0”或“1”
)
下一步:
while i: # where is the condition ?
if i & 1: # what is the equivalent for '&'? when I put 'and' instead of '&' I get differnt results?why?
i = i//2
这是带整数强制转换的截断除法。观察:
In [27]: i = 4
In [28]: i/2
Out[28]: 2.0
In [29]: i//2
Out[29]: 2
In [30]: i = 5
In [31]: i/2
Out[31]: 2.5
In [32]: i//2
Out[32]: 2
明白了吗?“s=”“”是什么意思?它的意思是s=0“否。它的意思是s=”“
,即为s
分配一个空字符串。如果有,您在理解这一点上付出了什么努力?是否添加了任何print
s?试过翻译吗?阅读文档或教程?#当我使用“and”而不是“and”时,“&”的等价物是什么?我得到了不同的结果?为什么?”,因为&
是二进制的,和是逻辑的,
和“我不同意这个问题过于宽泛”。这是非常基本的,没错,但有5个子问题都很容易回答(见答案…),很好!你赢了我:)