Python 未保留新值
我正在写我的第一个程序,这是一个“琐事”风格的游戏。问题是根据您选择的回合提出的,因此选择第1轮将为您提供列表1中的问题、列表2中的第2轮问题等 我已经编写了一段代码,允许您在游戏中更改回合,但如果您这样做,则只有第一个问题来自新回合,任何后续问题都会返回到上一轮 因此:Python 未保留新值,python,python-2.7,Python,Python 2.7,我正在写我的第一个程序,这是一个“琐事”风格的游戏。问题是根据您选择的回合提出的,因此选择第1轮将为您提供列表1中的问题、列表2中的第2轮问题等 我已经编写了一段代码,允许您在游戏中更改回合,但如果您这样做,则只有第一个问题来自新回合,任何后续问题都会返回到上一轮 因此: 我选择第一轮 获得第一轮提问 切换到第二轮 第二轮只问一个问题 之后的所有问题都回到第一轮 我不知道为什么,我似乎找不到任何理由它应该这样做 出现问题的代码的精简版本是: round = raw_input ("Round?:
round = raw_input ("Round?: ")
def turn(round):
print "Current Round = " + round
if round == "1":
print (choice (ssq1))
play_again = raw_input("Again?: ")
repeat(play_again)
elif round == "2":
print (choice (ssq2))
play_again = raw_input("Again?: ")
repeat(play_again)
def repeat(play_again):
if play_again == "Yes" or play_again == "Y":
turn(round)
elif play_again == "New":
new_round = True
new_turn(new_round)
def new_turn(new_round):
round = raw_input("Okay, Which round?: ")
turn(round)
from random import choice
ssq1 = ["Round1Q1", "Round1Q2", "Round1Q3"]
ssq2 = ["Round2Q1", "Round2Q2", "Round2Q3"]
turn(round)
repeat()
中的round
是全局变量,在开始时设置正确。你需要通过本轮考试;在turn()中使用的本地名称round
:
并在repeat()
函数中将其用作附加参数:
def repeat(play_again, round):
if play_again == "Yes" or play_again == "Y":
turn(round)
elif play_again == "New":
new_round = True
new_turn(new_round)
你的递归函数相当复杂。考虑使用<代码>而<代码>循环代替:
def turn(round):
print "Current Round = " + round
if round == "1":
print (choice (ssq1))
elif round == "2":
print (choice (ssq2))
round = None
while True:
if round is None:
round = raw_input ("Round?: ")
turn(round)
play_again = raw_input("Again?: ")
if play_again == 'New':
# clear round so you are asked again
round = None
elif play_again not in ('Yes', 'Y'):
# end the game
break
现在turn()
函数只处理游戏回合。重复、询问要玩哪一轮以及结束游戏都在一个无休止的while
循环中处理。break
语句用于结束该循环
你可以考虑的另一个改进是使用字典或列表来保存回合,而不是顺序命名变量:
round_questions = {
"1": ["Round1Q1", "Round1Q2", "Round1Q3"],
"2": ["Round2Q1", "Round2Q2", "Round2Q3"],
}
这样就不需要使用大量的条件;您只需按键检索正确的列表:
def turn(round):
if round in round_questions:
print "Current Round = " + round
ssq = round_questions[round]
print choice(ssq)
else:
print "No such round", round
这使得处理错误输入变得更容易;如果拾取的轮不是字典中的键,则第一个if
语句将为false,您可以打印错误消息
请注意,通过使用round
作为变量名,您正在屏蔽。这很好,您没有使用任何需要舍入的数学,但是如果您确实需要使用该函数,请考虑这一点。可能不应该使用舍入作为变量名either@PadraicCunningham:在结尾处将其作为单独的一点进行说明。这不像使用dict
、list
或str
作为名称那样是个大问题。@martjin Pieters,这不是一个大问题,但我仍然认为最好避免隐藏内置名称,英语中不缺少单词;)。
def turn(round):
if round in round_questions:
print "Current Round = " + round
ssq = round_questions[round]
print choice(ssq)
else:
print "No such round", round