gpt4 book ai didi

python - 类型错误:必须是 str,而不是类型

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:03 24 4
gpt4 key购买 nike

我正在编写一个可以掷骰子的程序。这是我的代码:

import random

Number_of_sides = input("How many sides should the die have?")
Number_of_sides = int

print("OK, the number of sides on the die will be" + Number_of_sides)

number = random.randit(1, Number_of_sides)

print(number)

当我运行该程序时出现此错误:

File "die.py", line 6, in <module>
print("OK, the number of sides on the die will be" + Number_of_sides)
TypeError: must be str, not type

我的问题是:出了什么问题,我该如何解决?以后如何避免?

最佳答案

您没有正确地将字符串转换为 int。

import random

number_of_sides = input("How many sides should the die have?")
number_of_sides_int = int(number_of_sides)

print("OK, the number of sides on the die will be " + number_of_sides)

number = random.randint(1, number_of_sides_int)

print(number)

不是将字符串转换为 int,而是将变量 number_of_sides 转换为 Python 类型 int。这就是错误可能令人困惑的原因,但 Python int 是 python type

关于python - 类型错误:必须是 str,而不是类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024852/

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