变量可以在Python中的while循环中保留以前的值吗?
我的问题是,当我们在一个while循环中使用一个变量,然后再改变我们赋予它的变量(即在等于的右侧)为什么这个新变量我们应该指定下一个变量上一个值来改变?变量可以在Python中的while循环中保留以前的值吗?
我意识到我的问题的措辞并不完全发现,所以在深入浅出而言,在我的程序我正在写一个叫predisp
到disp
之前,我改变disp
值在while循环后变量。在这里,我假设python中的所有代码都是从上到下运行的。
所以这里有一个例子什么价值predisp持有 所以如果disp = ['_','_']
predisp = ['_','_']
这是罚款。 但是,当我输入一个字母作为我的hang子手的一部分猜测 disp的值变成['u','_']
但问题是predisp也变成['u','_']
这不是我想要的。我希望它在经历任何更改之前始终具有以前的值disp
。我是python的新手,所以我不太了解所有变量是如何工作的,我在C++中更习惯于这些变量。这是代码(这是我写的一个简单的hang子手游戏)。
# 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!")
在Python中,变量是对象的引用:
disp = []
创建一个新的list
对象,并使其通过名称disp
访问。它的真正作用是将disp
设置为指向新创建的列表对象。赋值语句
predisp = disp
做同样的事情,即它设置predisp
引用相同的列表对象disp
。因此,对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)
谢谢!我对指针如何自动更新本身并不十分了解。我还有另一个问题。在C++中,当条件被违反时,while循环会立即中断。然而,在python中,我必须为这种情况输入一个break语句。有没有办法解决? – Afr0
@ Afr0循环在C++和Python中以相同的方式工作。在这两种语言中,条件在循环开始时被检查。是什么让你觉得有区别? –
指针不会自动更新自身。用C++术语来说,Python变量是对对象的引用,所以当你改变对象时,这个改变将通过所有引用这个对象的变量可见。 – miraculixx
感谢您的帮助。你有阅读Python的书吗?我真的需要磨练我的技能。 – Afr0
你可能会发现这篇文章有帮助:[关于Python名称和值的事实和神话](http://nedbatchelder.com/text/names.html),这是由SO老将Ned Batchelder写的。 –
不,很抱歉,我通过动手编程学习了python,没有涉及任何书籍。但是我在这里学到了很多东西。有时点击你知道你不能回答的问题仍然会有回报! –