[英]Why does Python believe return_value is a string?
What is wrong with the following bit of code?以下代码有什么问题?
class Dice:
def roll_dice(x):
import random
return_value = '('
try:
y = int(x)
except ValueError:
return None
for char in range(y):
return_value += f'{random.randint(1, 6)}, '
return_value = list(return_value).remove[-1 and -2]
return_value = ''.join(str(e) for e in return_value)
return return_value + ')'
parameter = input('Number of dice rolls: ')
print(Dice.roll_dice(parameter))
The error is错误是
Traceback (most recent call last):
File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 17, in <module>
print(Dice.roll_dice(parameter))
File "C:/Users/MyName/PycharmProjects/ProjectName/filename.py", line 11, in roll_dice
return_value = list(return_value).remove[-1 and -2]
TypeError: 'builtin_function_or_method' object is not subscriptable
If I understand Python correctly, it thinks return_value
is a string.如果我正确理解 Python,它认为
return_value
是一个字符串。 But didn't I take the list of return_value
on line 11 where the problem is?但是我不是在第 11 行获取了问题所在的
return_value
列表吗? How does that work?这是如何运作的?
The problem is remove[-1 and -2]
.问题是
remove[-1 and -2]
。 remove
is a method, so it must be followed by parentheses, not brackets. remove
是一个方法,所以它后面必须跟括号,而不是括号。 That's what not subscriptable means.这就是不可下标的意思。
Also, -1 and -2
does not do what you think it does, apply remove(-1)
and remove(-2)
separately.此外,
-1 and -2
不会按照您的想法执行,分别应用remove(-1)
和remove(-2)
。
The first argument of a class method should be named self
, but the class is not a real class, because this missing self
is never used.类方法的第一个参数应命名为
self
,但该类不是真正的类,因为从未使用过缺少的self
。 Write it as a normal function.把它写成一个普通的函数。
import
belongs to the beginning of the file, not inside functions. import
属于文件的开头,而不是函数内部。 Instead of building a string with extra ,
and removing it by converting it to a list and back again to a string, you could simply use相反建设有额外的字符串
,
并把它转换到一个列表,然后再返回一个字符串删除它,你可以简单地使用
return_value = return_value[:-2]
but it would be better to not create a string in first place, but a list:但最好不要首先创建一个字符串,而是一个列表:
import random
def roll_dice(x):
try:
y = int(x)
except ValueError:
return None
values = []
for _ in range(y):
values.append(str(random.randint(1, 6)))
return f'({", ".join(values)})'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.