简体   繁体   English

Python - 猜数字游戏:没有 output

[英]Python - Guessing a number game: no output

What am I doing wrong here?我在这里做错了什么? I am trying to build a guessing a number game but not sure why the console doesn't display anything?!我正在尝试构建一个猜数字游戏,但不确定为什么控制台不显示任何内容?!

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")

It works fine with the correct indentation.使用正确的缩进效果很好。 You otherwise fall in an infinite loop where you do nothing but request user to input a number.否则你会陷入无限循环,除了请求用户输入一个数字之外你什么都不做。

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")

example:例子:

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

NB.注意。 game_start_message = "guess a number between 1 and 100" doesn't do anything. game_start_message = "guess a number between 1 and 100"什么都不做。 Maybe you should rather print this string before the loop?也许你应该在循环之前打印这个字符串?

You did your indentation wrong, causing your if...elif...else structure to fall outside of the while loop, since that while loop never stops, it will keep asking for user inputs and never actually print anything else你做错了缩进,导致你的 if...elif...else 结构落在 while 循环之外,因为 while 循环永远不会停止,它会不断要求用户输入并且永远不会实际打印任何其他内容

Here is your code with the correct indentation:这是带有正确缩进的代码:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM