2012-07-12 157 views
1

我有这个单词un-scrambler游戏,只是在CMD或python shell中运行。当用户正确或错误地猜测单词时,它会显示“按任意键再次播放”如何在Python中重新运行代码?

如何让它重新开始?

+4

使用某种形式的环... – Ghost 2012-07-12 19:25:21

+0

如果我的回答对您有所帮助,您可以点击下面的投票问题的电话号码对号接受它。 – 2012-07-12 19:47:34

+0

Upvoted - 如果你是python新手,那么Google很难。 – 2016-04-10 02:22:43

回答

4

评估用户输入后没有程序退出;相反,做一个循环。例如,甚至没有用到的功能一个简单的例子:显示

phrase = "hello, world" 

while (input("Guess the phrase: ") != phrase): 
    print("Incorrect.") //Evaluate the input here 
print("Correct") // If the user is successful 

这将输出以下,用我的用户输入,以及:

Guess the phrase: a guess 
Incorrect. 
Guess the phrase: another guess 
Incorrect. 
Guess the phrase: hello, world 
Correct 

这显然是相当简单,但逻辑听起来就像你在做什么。稍微复杂一些的版本,其中,与你定义的函数,看看你的逻辑会适合,可能是这样的:

def game(phrase_to_guess): 
    return input("Guess the phrase: ") == phrase_to_guess 

def main(): 
    phrase = "hello, world" 
    while (not(game(phrase))): 
     print("Incorrect.") 
    print("Correct") 

main() 

输出是相同的。

+3

你在第三次尝试时猜测没有线索,哇+1! ; P – Trufa 2012-07-12 19:34:42

+1

@Trufa我猜测第一次尝试不会显示所有的输出结果,我不希望它看起来像我是通过对第二次猜测打分而作弊... – 2012-07-12 19:39:04

+0

@Ricardo尽管如此,这真是太神奇了!我的+1推理:))) – pepr 2012-07-13 05:22:48

1

尝试循环:

while 1==1: 
    [your game here] 
    input("press any key to start again.") 

或者,如果你想获得幻想:

restart=1 
while restart!="x": 
    [your game here] 
    input("press any key to start again, or x to exit.") 
+0

'raw_input()'不是Python 3的一部分,我假设用户正在使用基于原始标记。 – 2012-07-12 19:29:09

+5

为什么'1 == 1' - 无论是'while 1:'还是'true':肯定? – 2012-07-12 19:29:31

+1

更改为输入(),谢谢。我一直没有保持我的python技能最新,但我认为,即使我可以处理这个问题... – octern 2012-07-12 19:31:10

1

这里是你可以用它来重新运行的代码块的模板。将#code想象成一行或多行Python代码的占位符。

def my_game_code(): 
    #code 

def foo(): 
    while True: 
     my_game_code() 
0

你可以使用一个简单的循环while

line = "Y" 

while line[0] not in ("n", "N"): 
    """ game here """ 
    line = input("Play again (Y/N)?") 

希望这有助于

+0

根据其他答案和评论,'raw_input()'不是Python 3的一部分。 – 2012-07-12 19:32:36

+0

抱歉没有注意到它关于python 3 – zimonestones 2012-07-12 19:45:47

+0

不用担心。我编辑了不正确的陈述。 – 2012-07-12 20:15:22

3

即使以下风格的作品!

检查出来。

def Loop(): 
    r = raw_input("Would you like to restart this program?") 
     if r == "yes" or r == "y": 
      Loop() 
     if r == "n" or r == "no": 
      print "Script terminating. Goodbye." 
    Loop() 

这是 重复执行功能(组语句)的方法。

希望你喜欢它:):}:]

+2

要使它在python 3.x中运行,请将'raw_input'更改为'input' – 2016-12-04 10:02:52

0

的简单方法是使用也布尔值,很容易理解,如果你是一个初学者(像我一样)。这是我做的一组项目:

restart = True 

while restart: 
    #the program 
    restart = raw_input("Press any key to restart or q to quit!") 
    if restart == "q": 
     restart = False