【问题标题】:Trying to get the number of tries to start at 1 and not 0试图获得从 1 而不是 0 开始的尝试次数
【发布时间】:2017-10-17 06:16:08
【问题描述】:

每当您运行游戏并开始猜测时,它首先会询问猜测 #0 是什么?我试图让它显示“猜测#1是什么?”但。同时保持猜测的数量等于猜测的数量(如果有意义的话)。到目前为止,这是我的代码:

import random

def play_game(name, lower=1, upper=10):
    secret = random.randint(lower, upper)
    tries = 0

    print("-----------------------------\n"
          "Welcome, {}!\n"
          "I am thinking of a number\n"
          "between {} and {}.\n"
          "Let's see how many times it\n"
          "will take you to guess!\n"
          "-----------------------------".format(name, lower, upper))

    # Main loop
    guessing_numbers = True
    while guessing_numbers:
        guess = input("What is guess #{}?\n".format(tries))


        while not guess.isdigit():
            print("[!] Sorry, that isn't a valid input.\n"
                  "[!] Please only enter numbers.\n")
            guess = input("What is guess #{}?\n".format(tries))

        guess = int(guess)
        tries += 1

        if guess < secret:
            print("Too low. Try again!")
        elif guess > secret:
            print("Too high. Try again!")
        else:
            guessing_numbers = False

    if tries == 1:
        guess_form = "guess"
    else:
        guess_form = "guesses"

    print("--------------------------\n"
          "Congratulations, {}!\n"
          "You got it in {} {}!\n"
          "--------------------------\n".format(name,tries,guess_form))

    if tries < 3:
        # Randomly chooses from an item in the list
        tries_3 = ["Awesome job!","Bravo!","You rock!"]
        print (random.choice(tries_3))
        # ---
    elif tries < 5:
        tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon!     You can do better than that."]
        print (random.choice(tries_5))
    elif tries < 7:
        tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
        print (random.choice(tries_7))
    else:
        tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
        print (random.choice(tries_8))

    choice = input("Would you like to play again? Y/N?\n")
    if "y" in choice.lower():
        return True
    else:
        return False

def main():
    name = input("What is your name?\n")
    playing = True
    while playing:
        playing = play_game(name)


if __name__ == "__main__":
    main()

我在开始时将“尝试”次数设置为 0。但是,如果我将其设置为 1 然后玩游戏,我只需要尝试 3 次,它会显示我尝试了 4 次。所以我不知道该怎么做。对 python 还有些陌生,所以我希望得到一些帮助

【问题讨论】:

  • 好吧,为什么不改变你的显示方式呢? .format(tries + 1)
  • 行得通。谢谢!!

标签: python


【解决方案1】:

在您拥有input("What is guess #{}?\n".format(tries)) 的任何地方,使用guess = input("What is guess #{}?\n".format(tries+1))。 (在表达式中为尝试添加 +1,但不更改变量本身)

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多