高低游戏输出不正确的问题

0 投票
2 回答
30 浏览
提问于 2025-04-12 00:56

我需要让玩家知道他们的猜测是太低、太高还是正确,但在询问他们的范围后,我没有得到任何输出。请问我哪里做错了?这是我当前版本的Python,我想是这样。

print('Welcome to the Higher or Lower game!')
import random
lowr = int(input('What would you like for your lower bound to be?: '))
upr = int(input('And your highest?: '))
x = (random.randint(lowr, upr))
if lowr >= upr:
    print('The lowest bound must not be higher than highest bound. Try again.')
    if lowr < upr:
        g = int(input('Great now guess a number between', lowr, 'and', upr, ':'))
    while g > x:
        int(input('Nope. Too high, Guess another number: '))
        while g < x:
            int(input('Nope. Too high, Guess another number: '))
            if g == x:
                print('You got it!')

2 个回答

0

这是一个没有使用循环和break的版本。

import random


print('Welcome to the Higher or Lower game!')

are_boundaries_fixed = False
is_guessed = False
while not (is_guessed and are_boundaries_fixed):

    if not are_boundaries_fixed:
        lowr = int(input('What would you like for your lower bound to be?: '))
        upr = int(input('And your highest?: '))

        if lowr >= upr:
            print('The lowest bound must not be higher than highest bound. Try again.')
        else:
            are_boundaries_fixed = True
            x = random.randint(lowr, upr)
            g = int(input(f'Great now guess a number between {lowr} and {upr}:'))
    else:
        if g > x:
            g = int(input('Nope. Too high, Guess another number: '))
        elif g < x:
            g = int(input('Nope. Too small, Guess another number: '))
        else:
            is_guessed = True
            print('You got it!')

注意,input函数只接受一个参数,也就是要在屏幕上显示的文本。所以,像'Great now guess a number between', lowr, 'and', upr, ':'这样的写法会出错,应该使用字符串格式化,比如f-string的方式。

0

这里有一个可能的正确代码版本:

import random
print('Welcome to the Higher or Lower game!')
while True:
    lowr = int(input('\nWhat would you like for your lower bound to be?: '))
    upr = int(input('And your highest?: '))
    x = (random.randint(lowr, upr))
    if lowr >= upr:
        print('The lowest bound must not be higher than highest bound. Try again.')
    if lowr < upr:
        g = int(input(f"""Great now guess a number between
            {lowr} and {upr}:"""))
        while True:
            if g < x:
                g = int(input('Nope. Too low, Guess another number: '))
            elif g > x:
                g = int(input('Nope. Too high, Guess another number: '))
            if g == x:
                print('You got it!')
                break

在这里面有一些错误:使用输入方法和事件延迟的问题。

撰写回答