简体   繁体   English

猜数字游戏:我如何接受数字前面输入“ guess =”的猜测?

[英]Number guessing game: How can I accept input that says “guess =” before the number?

import random
guess = input("What is your guess?")
answer = random.randint(0,100)

while guess != answer:
    try:
        guess = float(guess)
        if guess > answer:
            print ("Your guess is too high!")
        elif guess < answer:
            print ("Your guess is too low!")
        elif guess == answer:
            print ("Congratulations!")
            break
        guess = input("What is your guess?")
        continue
    except ValueError:
        print ("Bad input. Try again!")
        guess = input("What is your guess?")

So my code works except that when i enter for example: guess = 30, it seems the input as invalid...how can I make it so it accepts it as a correct guess? 因此,我的代码可以正常工作,但是当我输入例如guess = 30时,输入似乎无效...我如何进行输入,使其接受为正确的猜测?

New to python here :) Thanks. python的新功能:)谢谢。

I copied and pasted your code into Python 3.5, and....apart from needing to indent everything after the while statement it worked fine. 我将您的代码复制并粘贴到Python 3.5中,..除了需要在while语句后缩进所有内容外,它还可以正常工作。

Are you inputting just the number: 30 您是否仅输入数字:30

...or "guess = 30"? ...或“猜测= 30”? Because that does cause a problem since it's not a number. 因为那不是数字,所以确实会引起问题。 You only need to input the number. 您只需要输入号码。 :) :)

If you want to accept "guess = 30" then: 如果要接受“猜测= 30”,则:

import random
import re ###<-Add this

guess = input("What is your guess?")
answer = random.randint(0,100)

while guess != answer:
    try:
        guess = re.sub("[^0-9]", "", guess) ###<- Add this
        guess = float(guess)
        if guess > answer:
            print ("Your guess is too high!")
        elif guess < answer:
            print ("Your guess is too low!")
        elif guess == answer:
            print ("Congratulations!")
            break
        guess = input("What is your guess?")
        continue
    except ValueError:
        print ("Bad input. Try again!")
        guess = input("What is your guess?")

These two lines will use Regular Expressions to strip the input of any non numeric characters before processing. 这两行将使用正则表达式在处理之前去除任何非数字字符的输入。

It depends on how much you have learnt in that class, but adding the following line should allow you to accept both 30 and guess = 30 (or even foo=bar=30 ): 这取决于您在该课程中学到的知识,但是添加以下行应可以接受30guess = 30 (甚至foo=bar=30 ):

...
while guess != answer:
    guess = guess.split('=')[-1]    # Add this line
    try:
        guess = float(guess)
        ...

It simply splits the input using = as a delimiter and only uses the last part ( [-1] ). 它仅使用=作为分隔符来分割输入,并且仅使用最后一部分( [-1] )。

So I reordered your code: 所以我重新排序了您的代码:

  • I narrowed try/except down to just the line which can cause the ValueError, because that makes it clear what particular error this except block is trying to handle - puts the error handling near the source of the error. 我将try/except缩小到可能导致ValueError的行,因为这样可以清楚地知道此except块试图处理的是哪个特定错误-将错误处理放在错误源附近。 This also makes a good reason to have continue because it now skips the "too high/too low" code, instead of in your code it does nothing. 这也是continue一个很好的理由,因为它现在跳过“太高/太低”代码,而不是在您的代码中不执行任何操作。

  • I changed the while loop condition so it says while True: to make it an infinite loop. 我更改了while循环条件,因此它说while True:使其成为无限循环。 In your code, while guess != answer implies that it will break when the guess is correct, you actually use break to exit the loop, so that is misleading. 在您的代码中, while guess != answer表示猜测正确时它会中断,但是您实际上使用break退出了循环,因此具有误导性。 It would be sensible to use while guess != answer and not have break anywhere, but if you have to use break as part of the assignment then my code has some 'reason' to use it (breaking an infinite loop). while guess != answer使用并且在任何地方都没有break是明智的,但是如果您必须使用break作为赋值的一部分,那么我的代码就会有一些“理由”来使用它(中断无限循环)。

  • I moved the guess = input(...) code inside the loop only, because it doesn't need to be duplicated at the top or inside the error handling. 我只将guess = input(...)代码移到了循环内,因为不需要在顶部或错误处理内将其重复。 (Imagine if you had to change the text, 3 places is more annoying than 1 place). (想象一下,如果您不得不更改文本,那么3个地方比1个地方更令人讨厌)。

  • There are lots of ways to handle the guess = 30 input. 有很多方法可以处理guess = 30输入。 You could literally handle that, and only that, by looking for if "guess = " in guess: and then if that text matches, use guess = guess.replace("guess = ", "") to replace it away, leaving just the number. 您可以按字面意思处理,只有这样,即if "guess = " in guess:查找if "guess = " in guess: ,然后如果文本匹配,则使用guess = guess.replace("guess = ", "")替换掉,只剩下号码。 Or use regular expressions, as another answer has used to drop text and leave digits, or use string split() , as yet another answer has. 或使用正则表达式,如另一个答案用来删除文本并保留数字,或使用字符串split() ,如另一个答案一样。 My answer here has filter() which filters something using a test - in this case it tests if something is a number, and only allows numbers through, so it drops all the text. 我在这里的答案有filter() ,它使用测试来过滤某些内容-在这种情况下,它将测试某些内容是否为数字,并且仅允许数字通过,因此将丢弃所有文本。 Same as the regex is doing, really, just a different approach. 与正则表达式相同,实际上只是一种不同的方法。

code: 码:

import random

answer = random.randint(0,100)

while True:
    guess = input("What is your guess?")

    # filters out only the numbers
    # and makes them into a string, e.g.
    # 1) "guess = 30"
    # 2) [3,0]
    # 3) "30"
    guess = ''.join(filter(str.isdigit, guess))

    try:
        guess = float(guess)
    except ValueError:
        print ("Bad input. Try again!")
        continue

    if guess > answer:
        print ("Your guess is too high!")
    elif guess < answer:
        print ("Your guess is too low!")
    else:
        print ("Congratulations!")
        break

Try it online at repl.it 在repl.it在线尝试

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

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