제 질문은 할당 된 변수를 변경하기 전에 while 루프에서 변수를 사용할 때입니다 (즉, 등호의 오른쪽). 왜 우리가 다음 변수에 이전 값을 변경하도록 할당 한 것입니까? ?변수가 파이썬의 while 루프에서 이전 값을 유지할 수 있습니까?
나는 완전히 내 프로그램에 내가 나중에 while 루프에서 disp
의 값을 변경하기 전에 disp
에 predisp
라는 변수를 쓰고, 연결 되는가 측면에서, 그래서에 발견되지 않는 내 질문의 말씨를 실현. 여기 파이썬에서 모든 코드가 위에서 아래로 실행된다고 가정합니다. 값 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!")
감사합니다. 파이썬을 읽을 수있는 책이 있습니까? 나는 정말 내 기술을 연마해야합니다. – Afr0
이 기사는 SO 베테랑 Ned Batchelder가 작성한 [Python 이름 및 값에 관한 사실 및 신화] (http://nedbatchelder.com/text/names.html)에서 찾을 수 있습니다. –
아니, 죄송합니다. 실용적인 프로그래밍을 통해 파이썬을 배웠습니다. 책은 사용되지 않았습니다. 그러나 나는 여기에 아주 많은 것들을 배웠다. 때로는 대답 할 수 없다는 것을 알고있는 질문을 클릭해도 여전히 돈을 지불합니다! –