Python - 猜数字游戏:无输出

Python - Guessing a number game: no output

我在这里做错了什么?我正在尝试构建一个猜数字游戏,但不确定为什么控制台不显示任何内容?!

import random

    game_random_number = random.randint(1, 100)
    game_active = True  
    
    
    while game_active:  
      game_start_message = "guess a number between 1 and 100"
      user_guess = int(input()) 
    if user_guess == game_random_number:
      print("You guessed it correctly")
      game_active = False
    elif user_guess < game_random_number:
      print("Too low guess again")
    else:
      print("Too high, guess again")

使用正确的缩进效果很好。否则你会陷入无限循环,除了请求用户输入一个数字什么都不做。

import random

game_random_number = 42 # just for the test
game_active = True  
    
    
while game_active:  
    game_start_message = "guess a number between 1 and 100"
    user_guess = int(input()) 
    if user_guess == game_random_number:
        print("You guessed it correctly")
        game_active = False
    elif user_guess < game_random_number:
        print("Too low guess again")
    else:
        print("Too high, guess again")

示例:

1
Too low guess again
2
Too low guess again
50
Too high, guess again
42
You guessed it correctly

注意。 game_start_message = "guess a number between 1 and 100" 什么都不做。也许你应该在循环之前打印这个字符串?

你的缩进错了,导致你的 if...elif...else 结构落在 while 循环之外,因为 while 循环永远不会停止,它会不断要求用户输入并且永远不会实际打印任何东西其他

这是您的代码,缩进正确:

import random

game_random_number = random.randint(1, 100)
game_active = True  

while game_active:  
    game_start_message = "guess a number between 1 and 100"
    user_guess = int(input())

    if user_guess == game_random_number:
        print("You guessed it correctly")
        game_active = False
    elif user_guess < game_random_number:
        print("Too low guess again")
    else:
        print("Too high, guess again")