Cadeh
Cadeh

Reputation: 29

typeerror: must be str, not type

I am writing a program that will roll a die. This is my code:

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)

When I run the program I get this error:

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

My questions are: what went wrong and how can I fix it? How can I avoid it in the future?

Upvotes: 2

Views: 20922

Answers (2)

Jenner Felton
Jenner Felton

Reputation: 807

You aren't properly casting the string to an 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)

Rather than casting the string to an int, you are making the variable number_of_sides into the Python type int. That's is why the error may have been confusing, but Python int is a python type.

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

The problem is that the order of your statements is incorrect.

You need to convert the value, after you print your confirmation statement, so that it is correctly used in the random function.

If you convert it before you print it, you'll get a TypeError because Python cannot add a string and a number together

Finally, there is a small typo in your random call, the method is randint not randit.

Putting all these together, you have:

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)

Upvotes: 1

Related Questions