2012-02-23 4 views
2

는 여기에 지금까지이 작업은 다음과 같습니다Python : 단어의 정확한 양을 묻는 함수를 만드는 방법은 무엇입니까?

그래서
import string 

나는 사용자가 5 단어를 묻는 5 표현 된 문장을 가지고

def main(sentence = raw_input("Enter a 5 worded sentence: ")): 
    if len(words)<5: 
     words = string.split(sentence) 
     wordCount = len(words) 
     print "The total word count is:", wordCount 

만약 사용자 입력 5 개 이상의 단어 :

elif len(words)>5: 
     print 'Try again. Word exceeded 5 word limit' 

미만 5 개 단어 :

else: 
     print 'Try again. Too little words!' 
,

그것은 그 진술 계속 :

UnboundLocalError: local variable 'words' referenced before assignment 
+0

질문 할 때 문제가 무엇인지 말하십시오. – Kitsune

+0

'string.split (sentence)'? Python2 이상으로 업그레이드해야합니다.'sentence.split()' –

답변

2

귀하의 문제가 변수 words가 존재하기 전에 len(words)를 호출하는 것입니다. 이것은 두 번째 코드 블록의 두 번째 줄에 있습니다. 파이썬에서, 기본 인수 기능 정의시 아닌 함수 호출시에 바인드되어

words = [] 
while len(words) != 5: 
    words = raw_input("Enter a 5 worded sentence: ").split() 
    if len(words) > 5: 
    print 'Try again. Word exceeded 5 word limit' 
    elif len(words) < 5: 
    print 'Try again. Too little words!' 

참고. 즉, 메인이 호출 될 때 메인이 정의 될 때 raw_input()이 실행된다는 것을 의미합니다. 메인 호출은 거의 확실하게 사용자가 원하는 것이 아닙니다.

+0

설명은 시원할 것입니다. – slezica

+2

설명 할 것이 더 무엇입니까? – wim

+0

하하하 내가 무슨 뜻인지 알지만, 내가 의미하는 바를 알았어. 이제는 더 좋아. – slezica

1

출력을 읽습니다. : 'words'변수가 할당 전에 참조됩니다.

다른 말로하면 '단어'가 무슨 뜻인지 말하기 전에 len (단어)를 호출하는 것입니다.

def main(sentence = raw_input("Enter a 5 worded sentence: ")): 
    if len(words)<5: # HERE! what is 'words'? 
     words = string.split(sentence) # ah, here it is, but too late! 
     #... 

이 그것을 사용하기 전에 그것을 정의보십시오 :

words = string.split(sentence) 
wordCount = len(words) 
if wordCount < 5: 
    #... 
+0

고마워요 !! :-) – user1227404

0

이 raw_input을 사용하여 입력을 가지고(). 이 그것이라고 정확히 무엇을 의미 5.

0

UnboundLocalError: local variable 'words' referenced before assignment

같지 않으면 다시 읽기 다음 분할을 (사용하여 단어 수) 를 수행합니다. 실제로 words이 무엇인지 알아내는 부분 앞에 words을 사용하려고합니다.

프로그램이 단계별로 진행됩니다. 체계적인 태도를 취하십시오.

관련 문제