【问题标题】:Why does the if statement make a failure? (beginner)为什么 if 语句会失败? (初学者)
【发布时间】:2021-03-04 08:21:01
【问题描述】:

我的代码有问题。

我的代码是初学者数字猜测器。代码应该是在用户输入字母的时候写错的。

我首先想到将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")

【问题讨论】:

标签: python string numbers integer letter


【解决方案1】:

最好使用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")

【讨论】:

  • @MattiasHolsting 哎呀!修好了。
【解决方案2】:

尝试将其转换为 ASCII 值。

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

因此,为了检查输入是否为字符,只需检查 ASCII 值是否在该范围之间。ASCII 表:http://sticksandstones.kstrom.com/appen.html

【讨论】:

    【解决方案3】:

    很好的尝试,如果您创建了一个像 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2012-09-28
      • 2017-01-26
      相关资源
      最近更新 更多