2017-03-26 1 views
2

나는 주사위를 굴릴 프로그램을 작성 중입니다. 이건 내 코드입니다 : 나는이 프로그램을 실행하면typeerror : type이 아닌 str이어야합니다.

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

당신은'int'을 연결하려는. 'str (Number_of_sides)'를 사용하고 다음 줄을 제거하십시오 :'Number_of_sides = int' – NFriesen

+0

많은 것들이 잘못되었습니다. 'Number_of_sides = int' 란 무엇입니까? 왜 타입에 할당하는거야? 또한 연결하기 전에 문자열로 변환해야합니다. – Li357

+0

@NFriesen 잘못된 것만이 아닙니다 ... – Li357

답변

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로 문자열을 캐스팅하는 대신, 파이썬 유형 int에 변수 number_of_sides하고 있습니다. 그래서 오류가 혼란 스러울 수 있지만, 파이썬 int은 파이썬 type입니다.

+0

@ 부란 카일리드 무엇? 왜이게 효과가 없을까요? –

1

문제는 명령문의 순서가 잘못되었습니다.

확인 문을 인쇄 한 후에 값을 변환해야 임의의 기능에서 올바르게 사용됩니다.

당신이 그것을 인쇄하기 전에 당신이 그것을 변환하면 파이썬은 문자열과 함께 다수의 마지막

를 추가 할 수 있기 때문에, 당신이 TypeError을 얻을 것이다, 당신의 임의 전화의 작은 오타가, 방법은 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) 
관련 문제