gpt4 book ai didi

c - 为什么 Python 3 和 C 中的 if 语句会产生不同的结果?

转载 作者:太空狗 更新时间:2023-10-29 15:57:37 25 4
gpt4 key购买 nike

我希望打印的值是“200!”和“404!”在 Python3.4 中。但我得到的结果是“200!”和“其他!”。

我做了个怪脸——在C里又试了一遍,C里的结果和Python3里的不一样。为什么?

Python3.4代码

def chk(s): 
if s is 200:
print('200!')
elif s is 404:
print('404!')
else:
print('else!')

chk(200)
chk(404)

Python3.4代码结果

200!
else!

C代码

#include <stdio.h>

void chk(int s) {
if (s == 200)
printf("200!");
else if (s == 404)
printf("404!");
else
printf("else!");
}

int main(void) {
chk(200);
chk(404);
return 0;
}

C代码结果

200!404!

最佳答案

is 本身并不意味着“相等”。它实际上意味着“在内存中占据相同的位置”。此外,根据您使用的 python 版本,对数字使用 is 会有奇怪的行为。 (这里,我的意思是 Cpython vs Jpython vs pypy vs....)所以不要使用它,使用 == 作为数字。

def chk(s): 
if s == 200:
print('200!')
elif s == 404:
print('404!')
else:
print('else!')

chk(200)
chk(404)

(如果您想了解为什么 200 是 200 产生 True404 是 404 产生 False 的更多细节: 基本上,从 -5256 的数字都缓存在 CPython 中。他们每个人都有自己的小内存槽,如果他们被分配给一个变量,CPython 只是排序指向预先分配的内存槽的点数。对于超出该范围的数字,情况并非如此。如果需要这些,CPython 将找到一个空的内存槽,将数字放在那里,并将变量指向它。如果你将 404 分配给两个单独的变量,你有两个单独的 404 整数卡在内存中。)

更多:

When to use is, when to use ==.

CPython, is, and why you should never use it with numbers

关于c - 为什么 Python 3 和 C 中的 if 语句会产生不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com