为什么 if 语句会失败? (初学者)

Why does the if statement make a failure? (beginner)

我的代码有问题。

我的代码是初学者数字猜测器。当用户键入字母时,代码应该会写入错误。

我首先想到将 usrin_guess 转换为整数,然后说“它是字符串还是整数”,但我意识到这行不通。然后我写了这个......在我的脑海里它应该工作但是当我写一封信时它在 if int(usrin_guess) > uo_rand_num: 失败了。

def rand_num(num):
    return random.randint(1, num) # Making a random number between the amount of number input and 1

uo_rand_num = rand_num(amount_of_numbers)

while int(usrin_guess) != uo_rand_num:
    
    usrin_guess = input("Enter a number between " + "1" + " and " + usrin_amount_of_numbers + " ") 
    
    try:
        val = int(usrin_guess)  
    except ValueError:
        val_input == False


    if val_input == True:
        if int(usrin_guess) > uo_rand_num:
            print("The number is lower than " + usrin_guess)
        elif int(usrin_guess) < uo_rand_num: 
            print("The number is higer than " + usrin_guess)
        elif int(usrin_guess) == uo_rand_num:
            answer = True

        usr_guesses += 1
    else:
        print("Please don't enter a character")

最好用一个while True循环,满足条件时break跳出循环。这样,您就不必将输入语句写两次。

您可以在字符串中使用格式化字符串而不是串联。

无需定义变量来检测是否发生错误,您可以直接将代码块放入tryexcept块中:

def rand_num(num):
    return random.randint(1, num) # Making a random number between the amount of number input and 1

uo_rand_num = rand_num(amount_of_numbers)
usrin_guess = 0

while True:
    usrin_guess = input(f"Enter a number between 1 and {usrin_amount_of_numbers} ")
    if int(usrin_guess) == uo_rand_num:
        break
    try:
        val = int(usrin_guess)
        if int(usrin_guess) > uo_rand_num:
            print("The number is lower than " + usrin_guess)
        elif int(usrin_guess) < uo_rand_num: 
            print("The number is higer than " + usrin_guess)
        elif int(usrin_guess) == uo_rand_num:
            answer = True
        usr_guesses += 1
    except ValueError:
        print("Please don't enter a character")

尝试将其转换为其 ASCII 值。

您可以使用ord() 函数来获取ASCII 值。每个字母都有自己的ASCII值,A065Z090.

因此,为了检查输入是否为字符,只需检查 ASCII 值是否位于 range.ASCII TABLE 之间:http://sticksandstones.kstrom.com/appen.html

伟大的尝试,如果您创建一个像 get_int_input 这样的辅助函数来处理所有验证并利用 f-strings 进行字符串插值,这可能会有所帮助:

import random


def get_int_input(prompt: str, min_num: int, max_num: int) -> int:
    num = -1
    while True:
        try:
            num = int(input(prompt=prompt))
            if min_num <= num <= max_num:
                break
            print(f'''Error: Integer outside of the allowed range, \
[{min_num}, {max_num}], try again...''')
        except ValueError:
            print('Error: Enter an integer, try again...')
    return num


def rand_num(min_num: int, max_num: int) -> int:
    return random.randint(a=min_num, b=max_num)


def guessing_game() -> None:
    min_num, max_num = 1, 10
    num_to_guess = rand_num(min_num=min_num, max_num=max_num)
    attempts = 0
    user_guess = -1
    while user_guess != num_to_guess:
        attempts += 1
        user_guess = get_int_input(
            prompt=
            f'Enter a number between {min_num} and {max_num} inclusive: ',
            min_num=min_num,
            max_num=max_num)
        if user_guess < num_to_guess:
            print(f'The number is higher than {user_guess}')
        elif user_guess > num_to_guess:
            print(f'The number is less than {user_guess}')
    attempt_or_attempts = 'attempt' if attempts == 1 else 'attempts'
    print(
        f'Congrats! You guessed the number in {attempts} {attempt_or_attempts}!'
    )


def main() -> None:
    guessing_game()


if __name__ == '__main__':
    main()

用法示例:

Enter a number between 1 and 10 inclusive: 5
The number is higher than 5
Enter a number between 1 and 10 inclusive: 11
Error: Integer outside of the allowed range, [1, 10], try again...
Enter a number between 1 and 10 inclusive: 7
The number is higher than 7
Enter a number between 1 and 10 inclusive: 9
The number is higher than 9
Enter a number between 1 and 10 inclusive: 10
Congrats! You guessed the number in 4 attempts!

试试看here.