2016-07-24 17 views
0

私の質問は、割り当てられた変数を変更する前にwhileループで変数を使用するときです(つまり、等価の右辺に)なぜこの新しい変数が次の変数に前の値を代入して割り当てたのでしょうか?変数はPythonのwhileループで以前の値を保持できますか?

は、私は完全に私のプログラムでは、私は私が後でwhileループ内dispの値を変更する前にdisppredispと呼ばれる変数を書いて、分かりやすくする観点ので、上のスポットされていない私の質問のフレージングを実現します。ここで私は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!") 
+0

ありがとう:

predisp = disp[:] 

これは簡単にid機能を使用して確認することができます。あなたはPythonを読む本を持っていますか?私は本当に自分のスキルを磨く必要があります。 – Afr0

+0

この記事は役に立ちましたか?:SOベテランのNed Batchelderによって書かれた[Pythonの名前と値に関する事実と神話](http://nedbatchelder.com/text/names.html) –

+0

いいえ、申し訳ありませんが、私は実践的なプログラミングを使ってPythonを学びました。しかし、私はここでかなりのことを学んだ。あなたが答えられないことを知っている質問をクリックすると、時々報酬が得られます! –

答えて

1

、変数はオブジェクトへの参照です:

disp = [] 

は新しいlistオブジェクトを作成し、名前をdispによってそれにアクセスできるようになります。実際にはdispが新しく作成されたリストオブジェクトを指すように設定されます。代入文

predisp = disp 

はすなわち、それはdispと同じリストオブジェクトを参照するためにpredispを設定し、同じことを行います。したがって、dispが指し示すオブジェクトに適用された変更は、predispが指し示すオブジェクトにも表示されます。これはまったく同じオブジェクトです。これを回避する

一つの方法は、割り当てにコピーを作成することです:助けを

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ループでは、条件に違反するとすぐにループが壊れます。しかし、Pythonでは、私は非常に条件のためにbreakステートメントをタイプアウトする必要があります。これを回避する方法はありますか? – Afr0

+0

@ Afr0ループはC++とPythonで同じように動作します。どちらの言語でも、ループの開始時に条件がチェックされます。何が違いがあると思いますか? –

+0

ポインタは自動的に更新されません。 C++の用語では、Python変数はオブジェクトへの参照であるため、オブジェクトを変更すると、このオブジェクトへの参照であるすべての変数を通じてこの変更が表示されます。 – miraculixx

関連する問題