【问题标题】:typeerror: must be str, not typetypeerror: 必须是 str,而不是 type
【发布时间】:2017-03-26 13:44:39
【问题描述】:

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

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。使用str(Number_of_sides) 并去掉这一行:Number_of_sides = int
  • 有很多问题。 Number_of_sides = int 是什么?你为什么要分配一个类型?您还必须在连接之前强制转换为字符串。
  • @NFriesen 不是唯一的错误......

标签: python string typeerror


【解决方案1】:

您没有正确地将字符串转换为 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

【讨论】:

    【解决方案2】:

    问题是你的语句顺序不正确。

    您需要在打印确认语句后转换该值,以便在随机函数中正确使用。

    如果在打印之前转换它,你会得到一个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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 2020-11-22
      • 1970-01-01
      相关资源
      最近更新 更多