我正在写一个会掷骰子的程序。这是我的代码:
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
我的问题是:出了什么问题,我该如何解决?我将来如何避免它?
答案 0 :(得分:2)
您没有正确地将字符串转换为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
。
答案 1 :(得分:1)
问题是你的陈述顺序不正确。
您需要在打印确认声明后转换该值,以便在随机函数中正确使用它。
如果在打印之前将其转换,则会得到TypeError
,因为Python无法一起添加字符串和数字
最后,随机调用中存在一个小错字,方法为randint
而不是randit
。
把所有这些放在一起,你有:
import random
Number_of_sides = input("How many sides should the die have?")
# Number_of_sides = int - not here.
print("OK, the number of sides on the die will be" + Number_of_sides)
Number_of_sides = int(Number_of_sides) # - this is where you do the conversion
number = random.randint(1, Number_of_sides) # small typo, it should be randint not randit
print(number)