gpt4 book ai didi

python - 为什么在 while 循环中尝试覆盖变量时会出现内存错误? (Python)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:08 27 4
gpt4 key购买 nike

你好,我是 python 新手,决定练习编写一些算法。如果有兴趣,可以在这里找到我试图解决的问题 > http://codeforces.com/problemset/problem/791/A

这是我为解决该问题而编写的代码。

a = input("Enter Limak's weight:")
b = input("Enter Bob's Weight:")
i = 0

while (a < b):
a = (a * 3)
b = (b * 2)
i= (i + 1)

print(i)

当我尝试运行代码时,我收到以下错误-

Enter Limak's weight:4
Enter Bob's Weight:7
Traceback (most recent call last):
File "s.py", line 6, in <module>
a = (a * 3)
MemoryError

有什么想法吗?

最佳答案

我无法使用 python 2.7.12 重现您的崩溃。假设您使用的是 python 3,我的猜测是您的变量 a 和 b 是 str 而不是 int 类型。从控制台读取它们后,您需要将它们转换为 int

尝试改变:

a = input("Enter Limak's weight:")

与:

a = int(input("Enter Limak's weight:"))

还有一个小技巧,在 python 中你可以写出这样的表达式:

i = i * 1

作为

i += 1

正如@Pfonks 所指出的,这种表示法适用于大多数运算符,例如 *、- 或/

关于python - 为什么在 while 循环中尝试覆盖变量时会出现内存错误? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43159238/

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