我如何让这个Python猜测游戏重新开始?

时间:2017-03-13 14:48:59

标签: python python-3.x

我想在猜测游戏结束时添加一些代码,询问用户是否想再玩一次。如果他们说是,我想,该计划将从一开始就再次运行。我尝试过多种想法,但都没有。最接近的是最后的另一个if循环。谢谢! X

print("Welcome to this guessing game!")

import random

x = random.randrange(50)

guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))

while x != "guess":

print
if guess < x:
    print("Your guess is too low!")
    guess = int(input("Guess again:"))
elif guess > x:
    print("Your guess is too high!")
    guess = int(input("Guess again:"))
else:
    print ("You guessed the right number!")

4 个答案:

答案 0 :(得分:3)

类似的东西:

while True:
    your code

    if input("Continue? Y/N: ").lower() not in {"y", "yes"}:
        break

在每次播放结束时,这会从用户那里获得输入,将其转换为小写,并查看它是否&#34; y&#34;或&#34;是&#34;。如果不是,则游戏突然退出,即退出。否则它会继续循环。

答案 1 :(得分:0)

您可以将游戏包装在一个功能中。然后在用户说“是”时,您调用该函数。在游戏结束时,重新考虑同样的问题。

这是为什么功能。

伪代码:

   function askUser(){
    'Do you want to play'=>yes: launchGame, no:print("ok bye bye")
    }

    function myGame(){
    //your game
        askUser()
    }

答案 2 :(得分:0)

例如

import random
something="yes"

while(something == "yes"):
#your code...
#....
#from your code
else:
    print ("You guessed the right number!")
    something=input("Do you want to play again? (yes/no)")#input return str? I use raw_input all the time in p2.7

和此:

while x != "guess":

为什么要猜测使用&#34; &#34;

x = random.randrange(50)所以x永远不是一个字符串&#34; guess&#34;它与True相似:或者1:

答案 3 :(得分:0)

print("Welcome to this guessing game!")

import random

x = random.randrange(50)

guess = int(input("I've picked an integer between 1 to 99. Guess what it is: "))

while True:

    if guess < x:
        print("Your guess is too low!")
        guess = int(input("Guess again:"))
    elif guess > x:
        print("Your guess is too high!")
        guess = int(input("Guess again:"))
    else:
        print ("You guessed the right number!")
        break

您正在了解python的基础知识,因此没有太多建议来阅读更多书籍 x是int的类型并猜测你使用“”包括“猜测”他不是变量名并成为字符串