简体   繁体   English

如何确保用户在python 3.5.1中的Guess游戏中输入正确的输入?

[英]How can I make sure users are turning in correct input, for Guess game in python 3.5.1?

This is my code: 这是我的代码:

from random import randint
print("What is your name?")
name=input()
tries=0
number= randint(1,100)
print("Hello, %s guess a number from 0 to 100" % name)
while tries < 8:
    print("Take a Guess")
    guess=input()
    guess=int(guess)
    if guess < number:
        print("Too Low")
        tries += 1
    if guess > number:
        print("Too High")
        tries += 1
    if guess == number:
        break

if guess == number:
   print("You got it, in %s tries" % tries)

if guess != number:
    print("Sorry try again!")

But it gives an error: 但是它给出了一个错误:

Traceback (most recent call last):
  File "/Users/Zuazua/PycharmProjects/untitled/GuessMyNumber2.py", line 10, in <module>
    guess=int(guess)
ValueError: invalid literal for int() with base 10: '23!'

将行guess=int(guess)更改为此:

guess=int(re.search(r'\d+', guess).group())

Attempt to parse entered value with guess=int(guess) can lead to different exceptions. 尝试使用guess=int(guess)解析输入的值可能导致不同的异常。 Quick and dirty way to fix it - is to wrap it in try ... except block. 修复它的快速而又肮脏的方法-将其包装在try ... except块。 Like: 喜欢:

try:
    guess=int(guess)
except ValueError:
    print("Cannot understand your input. Pls, try again")
    continue

This code will catch all ValueError exceptions occured during parsing. 此代码将捕获在解析期间发生的所有ValueError异常。 You may find here more info on exceptions: https://docs.python.org/3/tutorial/errors.html#errors-and-exceptions 您可以在此处找到有关异常的更多信息: https : //docs.python.org/3/tutorial/errors.html#errors-and-exceptions

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

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