输入验证数字猜谜游戏导致错误 [英] Input validation for number guessing game results in error

查看:62
本文介绍了输入验证数字猜谜游戏导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在这个社区中的第一篇文章,我当然是新手.我期待有一天我能帮助别人.无论如何,这是一个简单的代码,我希望这样做,以便在用户输入字符串时出现错误.不幸的是,它没有执行我想要的方式,这是代码:

This is my first post in this community and I am a beginner of course. I look forward to the day I can help others out. Anyway, this is the a simple code and I would like it so that there is an error if the user enters a string. Unfortunately, it does not execute the way I'd like to, here's the code:

number = 1

guess = int(input('Guess this number: '))

while True:
    try:
        if guess > number:
            print("Number is too high, go lower, try again")
            guess = int(input('Guess this number: '))
        elif guess < number:
            print("Too low, go higher, try again")
            guess = int(input('Guess this number: '))
        else:
            print("That is correct")
            break
    except (SyntaxError, ValueError):
            print("You can only enetr numbers, try again")

当程序被执行时,当我写任何字符串时,它要求我猜这个数字:"."d",则显示错误:

When the program gets executed, and it asks me to "Guess this number: ", when I write any string e.g. "d", it gives the error:

Guess this number: d
Traceback (most recent call last):
  File "Numberguess.py", line 5, in <module>
    guess = int(input('Guess this number: '))
ValueError: invalid literal for int() with base 10: 'd'


感谢您的时间和支持.


Thank you for your time and support.

推荐答案

欢迎使用堆栈溢出!每个人都需要从某个地方开始

Welcome to Stack Overflow! Everyone needs to start somewhere

看看下面的代码:

# import random to generate a random number within a range
from random import randrange


def main():
    low = 1
    high = 100

    # gen rand number
    number = gen_number(low, high)

    # get initial user input
    guess = get_input()

    # if user did not guess correct than keep asking them to guess
    while guess != number:
        if guess > number:
            print("You guessed too high!")
            guess = get_input()
        if guess < number:
            print("You guess too low!")
            guess = get_input()
    # let the user know they guess correct
    print(f"You guessed {guess} and are correct!")


def gen_number(low, high):
    return randrange(low, high)


# function to get input from user
def get_input():

    guess = input(f"Guess a number (q to quit): ")
    if guess == 'q':
        exit()

    # check to make sure user input is a number otherwise ask the user to guess again
    try:
        guess = int(guess)
    except ValueError:
        print("Not a valid number")
        get_input()

    # return guess if it is a valid number
    return guess


# Main program
if __name__ == '__main__':
    main()

这是一个绝佳的机会,可以包含Python的random模块以生成一定范围内的随机数.还有一个很好的递归示例,可以不断要求用户进行猜测,直到他们提供有效的输入为止.如果可行,请将此答案标记为正确答案,如果您有任何疑问,请随时发表评论.

This was a great opportunity to include Python's random module to generate a random number within a range. There is also a nice example of recursion to keep asking the user to guess until they provide valid input. Please mark this answer as correct if this works and feel free to leave comments if you have any questions.

快乐编码!!!

这篇关于输入验证数字猜谜游戏导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆