私の質問は、割り当てられた変数を変更する前にwhileループで変数を使用するときです(つまり、等価の右辺に)なぜこの新しい変数が次の変数に前の値を代入して割り当てたのでしょうか?変数はPythonのwhileループで以前の値を保持できますか?
は、私は完全に私のプログラムでは、私は私が後でwhileループ内disp
の値を変更する前にdisp
にpredisp
と呼ばれる変数を書いて、分かりやすくする観点ので、上のスポットされていない私の質問のフレージングを実現します。ここで私はPythonのすべてのコードが上から下に実行されていると仮定しています。だからここ
はdisp = ['_','_']
predisp = ['_','_']
場合値predispが罰金であるので を保持しているものの例です。 しかし、私の掛け屋の推測の一部として手紙を入力する瞬間 dispの値は['u','_']
になりますが、問題はプリスピーでもありますが、私が望んでいないのは['u','_']
になります。変更を受ける前に常に前の値がdisp
になるようにします。私はPythonの初心者なので、すべての変数がどのように機能するのか分かりません.C++でもっと慣れています。ここにコードがあります(これは私が書いている簡単なハンベットゲーム用です)。 Pythonで
# 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!")
ありがとう:
これは簡単に
id
機能を使用して確認することができます。あなたはPythonを読む本を持っていますか?私は本当に自分のスキルを磨く必要があります。 – Afr0この記事は役に立ちましたか?:SOベテランのNed Batchelderによって書かれた[Pythonの名前と値に関する事実と神話](http://nedbatchelder.com/text/names.html) –
いいえ、申し訳ありませんが、私は実践的なプログラミングを使ってPythonを学びました。しかし、私はここでかなりのことを学んだ。あなたが答えられないことを知っている質問をクリックすると、時々報酬が得られます! –