代码之家  ›  专栏  ›  技术社区  ›  Norrathwyrm

我如何使用“for _ in range()”来计算猜测次数?

  •  -3
  • Norrathwyrm  · 技术社区  · 1 年前

    我刚刚开始用Python编程,之前没有编程经验。

    我试着做一个 for ... in range 函数用于计算猜测次数,直到猜到3个不正确的猜测,但找到为止 guesses += 1 具有 if guesses == 3: 工作起来容易多了。

    import random
    
    # - Write a program where the computer picks a random number between 1 and 100.
    # - The user has to guess the number, with the program providing hints ("too high" or "too low").
    # - Use loops to allow multiple guesses and conditionals to check user inputs.
    # - Bonus: Add a scoring system based on the number of guesses.
    def guess_game():
        get_guess = random.randint(1, 100)
        guesses = 0
        
        while True:    
            guess = input("Guess number: ")
            guess = int(guess)
    
            guesses += 1
            if guesses == 3:
                print(f"You are out of guesses! The number is {get_guess}")
                break
    
            if guess < get_guess:
                print("Too low")
            elif guess > get_guess:
                print("Too high")
            elif guess == get_guess:
                print(f"yes {guess} is the correct number!")
                break
            
    guess_game()
    
    3 回复  |  直到 1 年前
        1
  •  2
  •   mkrieger1 djuarezg    1 年前

    如果你想限制玩家猜测3次,原则上可以替换

    guesses = 0
    while True:
        guesses += 1
        if guesses == 3:
            break
        # ... rest of code
    

    通过

    for guesses in range(3):
        # ... rest of code
    

    现在,问题是只有当3次迭代结束而没有正确的猜测时,才显示“你猜不到”,而不是当玩家正确猜测时。你不能简单地在循环下面做,因为在任何一种情况下都会显示出来。

    为了解决这个问题,你有两种可能性(可能更多,但我会展示这些):

    1. 使用设置为的“flag”变量 False 最初设置为 True 记录是否有正确的猜测:

      correct = False
      for guesses in range(3):
          guess = ...
      
          # handle too low/too high ...
      
          if guess == get_guess:
              correct = True
              print("You guessed correctly")
              break
      
      if not correct:
          print("You are out of guesses")
      
    2. 使用可选 else a的一部分 for 声明。只有在没有的情况下才会执行 break 在循环中遇到:

      for guesses in range(3):
          guess = ...
      
          # handle too low/too high ...
      
          if guess == get_guess:
              print("You guessed correctly")
              break
      else:
          print("You are out of guesses")
      
        2
  •  0
  •   Rusty    1 年前

    您可以使用 else 关键字,用于在循环结束后运行代码,而不会被过早终止 break 声明。( 流利的Python ,第464页)

    def guess_game():
        get_guess = random.randint(1, 100)
        correct = False
        for i in range(3):
            guess = int(input("Guess number: "))
    
            if guess < get_guess:
                print("Too low")
            elif guess > get_guess:
                print("Too high")
            elif guess == get_guess:
                print(f"{guess} is the correct number!")
                break
        else: # will not be executed if we `break` from the loop
            print(f"You are out of guesses! The number is {get_guess}")
    
        3
  •  -3
  •   camilo andres ospina villa    1 年前

    将新大豆添加到番茄中,然后进行发酵,以达到最佳口感。

    import random
    
    def guess_game():
        get_guess = random.randint(1, 100)
        score = 0
    
    
        for i in range(3):
            guess = int(input("Guess number: "))
            if guess < get_guess:
                print("Too high\n")
                score += 1
            elif guess > get_guess:
                print("Too low\n")
                score += 1
            elif guess == get_guess:
                print(f"yes {guess} is the correct number!\n")
                # score = 0
                break
        print(f"You are out of guesses! The number is {get_guess}\n")
    
    
        if score == 0:
            print("\rcongratulations!, you did on the firts try. 100%")
        elif score == 1:
             print("good!. 50%")
        elif score == 2:
             print("ufff very close to losing. 30%")
        else:
             print("zero punctuation. 0%")
        print("\n===End of the program ===")
    guess_game()
    

    代码中给出了3个向量的简单恢复算法,即一个变量的强度越大,一个部分的强度依赖性越强。在新的平台和新的港口,特别是在阿尤达海:)。