2013-12-19 112 views
0

我是一个真正的Python新手,我将它作为GCSE在我的学校,我已被赋予完成任务。我完成了这个简单代码的所有要求,但不知道如何重复。有人能告诉我一个重复代码的简单方法吗?重复整个算法

感谢

import random 

Random = random.randint(1,100) 

Guess = int(input("Please guess a number between 1 and 100: ")) 

counter = 1 

while Guess != Random: 
    if Guess > Random: 
     print("Too high") 
     Guess = int(input("Please guess the number: ")) 
    else: 
     print("Too low") 
     Guess = int(input("Please guess the number: ")) 
    counter += 1 

print("Well Done:") 
print("You took:",counter, "Guesses") 
+0

重复代码是什么意思?你想让游戏自动重启吗? – kalhartt

+7

提示:您已经在使用导致代码重复的技术。你如何利用'while'来实现你的目标? – Kevin

+0

重复它直到什么时候? – dansalmo

回答

0

最容易做的是把它在一段时间真循环与条件的中断方式:

import random 


while True: 
    Random = random.randint(1,100) 

    Guess = int(input("Please guess a number between 1 and 100: ")) 

    counter = 1 


    while Guess != Random: 
     if Guess > Random: 
      print("Too high") 
      Guess = int(input("Please guess the number: ")) 
     else: 
      print("Too low") 
      Guess = int(input("Please guess the number: ")) 
     counter += 1 

    print("Well Done:") 
    print("You took:",counter, "Guesses") 

    choice = input("Would you like to continue? y/n") 
    if choice == "n": 
     break 

注意,randint(1100)将返回从数1-99包括在内,你实际上要求用户猜测你的表达方式为2-99。