Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 什么';这个节目的意义是什么?_Python - Fatal编程技术网

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

我知道这个程序将十进制转换成二进制,事实上我只是一个编程初学者,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' 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个子问题都很容易回答(见答案…),很好!你赢了我:)