猜游戏(Python)问题。初学者总数

时间:2019-07-07 04:39:44

标签: python

我有几天的Python知识。我上过Codecademy之类的课程,我想潜入一个项目。在该项目开始时,我观看了YouTube视频,以了解其精髓。

我的游戏会询问是否要玩,如果是,它将继续玩。如果“否”,程序将停止。我不知道如何更改它以使其继续播放。

程序也不会显示该数字大于或小于显示while循环之后的数字。最初,我在while循环之后使用了这段代码,但是没有什么区别。

我只是一个总初学者,想通过实际项目更好地学习Python,所以我真的不确定在这里采取哪些步骤:

import random

number = random.randint(1,10)
tries = 1

name = input("Hello, What is your name?")

print("Hello there,", name)

question = input("Time to guess, ready? [Y/N]")
if question == "n":
    print("sorry, lets go!")

if question == "y":
    print("Im thinking of a number between 1 and 10.")
    guess = int(input("Have a guess"))

    if guess < number:
        print("That is too low!")
    if guess == number:
        print("Congrats! You win!!")
    if guess > number:
        print("That is too high!")
while guess != number:
        tries += 1
        guess = int(input("Try again: "))

Hello, What is your name?name
Hello there, name
Time to guess, ready? [Y/N]y
Im thinking of a number between 1 and 10.
Have a guess1
That is too low!
Try again: 10
Try again: 10
Try again: 10
Try again: 

永远不会显示消息“太高”。

3 个答案:

答案 0 :(得分:0)

if语句可以进入while循环内。

您可以使用break语句终止while循环。

您可以在此处找到更多详细信息:https://docs.python.org/2.0/ref/break.html

答案 1 :(得分:0)

使用elif不连续的if语句。更改您的while循环以允许break退出,以便您可以显示正确的获胜消息。

import random

number = random.randint(1,10)
tries = 1

name = input("Hello, What is your name?")

print("Hello there,", name)

question = input("Time to guess, ready? [Y/N]")
if question == "n":
    print("sorry, lets go!")

if question == "y":
    print("Im thinking of a number between 1 and 10.")
    guess = int(input("Have a guess"))

while True:
    if guess < number:
        print("That is too low!")
    elif guess == number:
        print("Congrats! You win!!")
        break
    elif guess > number:
        print("That is too high!")
    tries += 1
    guess = int(input("Try again: "))

答案 2 :(得分:0)

我使用@furas,因为这实际上应该是一对嵌套的while循环,其结构类似于:

import random

name = input("Hello, What is your name? ")

print("Hello there,", name)

answer = "y"

while answer.lower().startswith("y"):
    number = random.randint(1, 10)

    print("I'm thinking of a number between 1 and 10.")
    guess = int(input("Have a guess: "))

    while True:
        if guess < number:
            print("That is too low!")
        elif guess > number:
            print("That is too high!")
        else:
            print("Congrats! You win!")
            break

        guess = int(input("Try again: "))

    answer = input("Play again? [Y/N]: ")

print("Goodbye!")