gpt4 book ai didi

python - 为什么 %r 可以工作,而 %d 在某些情况下可以工作,即使有一个数字

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:13 25 4
gpt4 key购买 nike

Python 初学者在这里。想问你一个很简单的问题。

这是第一个示例代码:-

print "I will \"Add\" any two number that you type."
x = raw_input("What is the first number?")
y = raw_input("What is the second number?")

z = x + y

print "So, %d plus %d equals to %d" % (x, y, z)

在最后一行使用 %d 会出现错误:

   TypeError: %d format: a number is required, not str

这是第二个示例代码:-

print "I will \"Add\" any two number that you type."
x = raw_input("What is the first number?")
y = raw_input("What is the second number?")

z = x + y

print "So, %r plus %r equals to %r" % (x, y, z)

这不会给出第一个代码给出的错误。

所以我的问题是为什么使用 %d 会给我带来错误,但使用 %r 不会给我带来错误?

最佳答案

当您通过 raw_input() 获取输入时,它会返回一个字符串,因此 xy 是字符串,而 zxy 的串联,而不是相加。不确定这是否是您的意图。如果您希望它们为 int ,请使用 int(raw_input(...)) 将它们转换为 int 。

您收到的错误是因为 %d 需要 xyz(用于替换 %d) > ) 为整数(但它们实际上是字符串,因此会出现错误)。

%r 表示 repr() 的输出,它接受任何类型的对象,因此它在第二种情况下工作,尽管它会返回连接(不是加法)。

关于python - 为什么 %r 可以工作,而 %d 在某些情况下可以工作,即使有一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954658/

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