首页 > 解决方案 > TypeError: 'str' 对象不能被解释为整数,即使我给它分配了 int(value)

问题描述

当我输入我的简单代码时:

times = input("How many times do I have to tell you? ")
times = int(times)

for i in range(times):
    print("Clean your room!")

我收到以下错误消息:

>>> times = input("How many times do I have to tell you? ")
How many times do I have to tell you? times = int(times)
>>> 
>>> for time in range(times):
...     print("Clean your room!")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> 


我正在使用 python 3.8

编辑:

_>>> times = int(input("How many times do I have to tell you? "))
How many times do I have to tell you? 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> for i in range(times):
...     print("Clean your room!")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'times' is not defined
>>> input("2")
2
''
>>> _

我认为我的 .bashrc 和 .bash_profile 存在一些问题。

标签: pythonpython-3.xint

解决方案


您好,错误告诉您:

TypeError: 'str' object cannot be interpreted as an integer

首先,您在第 1 行中分配字符串。在第 2 行中,您分配一个 int。

我再次检查了它,我可以告诉两个版本都可以 100% 工作:

times = input("How many times do I have to tell you? ")
times = int(times)

for i in range(times):
    print("Clean your room!")

times = int(input("How many times do I have to tell you? "))

for i in range(times):
    print("Clean your room!")

input("")

input("")在最后添加了,所以控制台保持打开状态

如果这仍然行不通,我们需要寻找其他地方。但我相信我们会解决这个问题的。


推荐阅读