2016-07-24 6 views
0

제 질문은 할당 된 변수를 변경하기 전에 while 루프에서 변수를 사용할 때입니다 (즉, 등호의 오른쪽). 왜 우리가 다음 변수에 이전 값을 변경하도록 할당 한 것입니까? ?변수가 파이썬의 while 루프에서 이전 값을 유지할 수 있습니까?

나는 완전히 내 프로그램에 내가 나중에 while 루프에서 disp의 값을 변경하기 전에 disppredisp라는 변수를 쓰고, 연결 되는가 측면에서, 그래서에 발견되지 않는 내 질문의 말씨를 실현. 여기 파이썬에서 모든 코드가 위에서 아래로 실행된다고 가정합니다. 값 predisp 괜찮 그래서 disp = ['_','_'] 경우

predisp = ['_','_'] 

을 보유하고 무엇을

그래서 여기의 예입니다. 그러나 내가 교수형 집행자의 일부로 편지를 입력하는 순간 disp의 값은 ['u','_'] 가되지만 문제는 프리 스피 스도 내가 원하는 것이 아닌 ['u','_']이됩니다. 변경을 수행하기 전에 이전 값이 항상 disp이 되길 원합니다. 저는 파이썬에 익숙하지 않아 모든 변수가 어떻게 작동하는지 이해하지 못합니다. C++에서 익숙해졌습니다. 다음은 코드입니다 (필자가 작성한 간단한 행맨 게임 용). 파이썬에서

# Created by Zur-en-Arrh 

import random # Useful to select a topic from the file. 


# Functions 

def same_letter(user_letter, word_to_guess): 
    if user_letter == word_to_guess: 
     return True 
    else: 
     return False 

def wrong_guess(prevdisp,currdisp): 
    if prevdisp == currdisp: 
     return True 
    else: 
     return False 

# Dealing with the file. 
filename = input("Which file do you want to play with ") 
topics = str(open(filename, 'r').read()) 
list_of_topics = topics.split() # This is the list that contains the topics randomly selected from the file. 
guess_me = list(list_of_topics[random.randint(0, len(list_of_topics) - 1)]) # This is what the user will need to figure out. 

# Printing out the Dashes for the user. 
disp = [] 
for i in range(0, len(guess_me)): 
    disp.append("_") 

# This is just the declaration of the number of wrong guesses. This'll always be 0 at the start of the game. 
wrong_guesses = 0 

# While loop for game. Also note in hangman, you're only allowed 5 wrong guesses till the body is complete. 
while wrong_guesses < 6: 
    print(' '.join(disp)) # Prints the game in an acceptable format to the user. 
    predisp = disp 
    if disp == guess_me: # end the game when the user wins. 
     break 
    user_guess = str(input("Which letter do you think will there be? ")) 
    for i in range(len(guess_me)): 
     if same_letter(user_guess, guess_me[i]): 
      disp[i] = user_guess 
    print(predisp) 
    if wrong_guess(predisp, disp): 
     wrong_guesses += 1 

    if wrong_guesses == 6: 
     print("You got hung! Better luck next time") 
     break 

if wrong_guesses < 6: 
    print("Well Done you won the game!") 
+0

감사합니다. 파이썬을 읽을 수있는 책이 있습니까? 나는 정말 내 기술을 연마해야합니다. – Afr0

+0

이 기사는 SO 베테랑 Ned Batchelder가 작성한 [Python 이름 및 값에 관한 사실 및 신화] (http://nedbatchelder.com/text/names.html)에서 찾을 수 있습니다. –

+0

아니, 죄송합니다. 실용적인 프로그래밍을 통해 파이썬을 배웠습니다. 책은 사용되지 않았습니다. 그러나 나는 여기에 아주 많은 것들을 배웠다. 때로는 대답 할 수 없다는 것을 알고있는 질문을 클릭해도 여전히 돈을 지불합니다! –

답변

1

, 변수는 참조 객체에 있습니다

disp = [] 

새로운 list 객체를 생성하고 이름 disp하여 액세스 할 수 있습니다. 실제로 수행하는 작업은 새로 작성된 목록 오브젝트를 가리 키도록 disp으로 설정됩니다. 할당 문

predisp = disp 

disp 같은 목록 개체를 참조하는 predisp을 설정 즉, 같은 일을한다. 따라서 disp이 가리키는 객체에 적용된 모든 변경 사항은 predisp이 가리키는 객체에서도 볼 수 있습니다. 이는 매우 동일한 객체입니다. 이를 방지하기 위해

한 가지 방법은 할당에 복사본을 생성하는 것입니다

predisp = disp[:] 

이 쉽게 id 기능을 사용하여 확인할 수 있습니다 도움을

disp = ['_'] * 3 
predisp = disp 
id(disp), id(predisp) 
# same object ids for both variables 
=> (4303250784, 4303250784) 

predisp = disp[:] 
id(disp), id(predisp) 
# different object ids 
=> (4303250784, 4303043832) 
+0

고마워! 포인터가 자동으로 업데이트되는 방식에 대해서는별로 몰랐습니다. 나는 또 다른 질문이있다. C++에서는 while 조건이 위반되면 while 루프가 즉시 중단됩니다. 그러나 파이썬에서는 그 바로 그 조건을 위해 break 문을 써야합니다.이 주위에 어떤 방법이 있습니까? – Afr0

+0

@ Afr0 루프는 C++과 Python에서 같은 방식으로 작동합니다. 두 언어 모두에서 루프의 시작 부분에서 조건이 검사됩니다. 차이점이 있다고 생각하게 만드는 이유는 무엇입니까? –

+0

포인터가 자동으로 업데이트되지 않습니다. C++ 용어에서 파이썬 변수는 객체에 대한 참조이므로 객체를 변경할 때이 객체에 대한 참조 인 모든 변수를 통해이 변경 사항을 볼 수 있습니다. – miraculixx

관련 문제