2017-05-05 11 views
1

저는 Python 2.7.x에서 함수에 대해 배우고 있으며, 사용하고있는 책의 제안 중 하나는 사용자의 입력을 요청하여 스크립트.int()를 사용하여 raw_input()에서 사용자의 입력을 변환합니다.

You need to use int() to convert what you get from raw_input()

나는 아직 int()를 사용하는 방법을 잘 모르겠어요 다음과 같이 함수에 raw_input을 사용하는 방법에 대한 조언입니다.

def cheeses_and_crackers(cheeses, crackers): 
    print "You have %d types of cheeses." % cheeses 
    print "You have %d types of crackers." % crackers 
    print "That is a lot of cheese and crackers!\n" 

print "How many cheeses do you have?" 
cheeses1 = raw_input("> ") 
int(cheeses1) 

print "How many types of crackers do you have?" 
crackers1 = raw_input("> ") 
int(crackers1) 

cheeses_and_crackers(cheeses1, crackers1) 

나는 다음과 같이이 실행하려고 할 때 내가 오류 :

TypeError: %d format: a number is required, not str

나는 그래서 일부 감사하겠습니다 int()을 사용하는 방법 같은데요를 이것은 내가 지금까지 시도한 것입니다 기본 구문에도 도움이됩니다.

+1

'치즈 1 = INT (raw_input을 (">"))'당신은'INT를 호출 한 후 저장해야 –

+0

()'. 'cheeses1 = int (cheeses1)'처럼 – kuro

+0

'int (raw_input (">"))'를 사용하면 입력 값이 즉시 int로 변환됩니다. 당신은 또한 올바른 fromat, 즉 int가 아닌 문자열을 제공하지 않기 때문에 try/catch를 사용하십시오. – Ludisposed

답변

0

int은 사용자 입력 (실제로는 변경 불가능한 문자열)을 변경하지 않지만 정수를 생성 한 다음이를 반환합니다.

반환 값에 이름을 지정하지 않으므로이 값은 손실됩니다.

데모 :

>>> user_input = raw_input('input integer > ') 
input integer > 5 
>>> type(user_input) 
<type 'str'> 
>>> input_as_int = int(user_input) 
>>> input_as_int 
5 
>>> type(input_as_int) 
<type 'int'> 
>>> type(user_input) # no change here 
<type 'str'>