Python编写一个猜数字游戏的设计问题

3
今天我想设计一个猜数字游戏,由我设置一组数字列表。玩家需要打印出所有的5个数字才能赢得游戏。不允许重复打印数字。以下是代码:
def guess(): 

   print "Please input a number smaller than 10, let's see if it is in my plan."

   print "You should figure out all the 5 numbers."

   n = int(raw_input('>'))
   my_list = [1, 3, 5, 7, 9]
    your_list = []
    count = 0
    while count < 5:
        if n in my_list:
            if n not in your_list:
                your_list.append(n) 
                count = count + 1
                print "Good job! You have got %d numbers!" % count
                n = int(raw_input('>'))
            else:
                print "You have already typed that. Input again!"
                n = int(raw_input('>'))
        else:
            print "That is not what I want."
            n = int(raw_input('>'))
    print "Here you can see my plan:", my_list
    print "You are so smart to  guess out, you win!"

guess()

当我尝试运行它时,看到结果后非常困惑:
 Please input a number smaller than 10, let's see if it is in my plan
 You should figure out all the 5 numbers
>1
Good job! You have got 1 numbers
>2
That is not what I want
>3
Good job! You have got 2 numbers
>5
Good job! You have got 3 numbers
>7
Good job! You have got 4 numbers
>4
Here you can see my plan: [1, 3, 5, 7, 9]
You are so smart to  guess out, you win!

当我输入数字4时,它应该打印出"That is not what I want",而不是显示“win”。为什么会出错呢?

寻求调试帮助的问题(“为什么这段代码不起作用?”)必须在问题本身中包含所需的行为、具体问题或错误以及重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参见:如何创建一个最小、完整和可验证的示例。 - FHTMitchell
1
我无法重现那个输出。即使 count == 5,它仍会要求一个额外的输入,但当计数为4时它并不停止。 - tobias_k
1
我刚刚复制并粘贴了你的代码,当我点击4时,我收到了“这不是我想要的。”。所以在我的Python 2.7上它可以工作。 - Carlo 1585
@Carlo1585 是的,我刚刚再试了一次并获得了与你相同的结果。很有趣。但是当我尝试输入其他数字时,代码仍然会出错。所以这不是Python版本的问题。 - FrancesWu
@AdamJaamour 是的!谢谢:) - FrancesWu
显示剩余2条评论
3个回答

0

你的代码中有一些逻辑错误,涉及到raw_input的顺序。

在代码开头多了一个额外的raw_input

而且在每个条件语句的结尾都有一个raw_input。最好只在while循环的开头有一个raw_input,并根据该输入显示一条消息。

按照你的逻辑,即使你找到了所有5个猜测,仍然会有一个输入等待,无论这个输入是什么,它都会显示获胜消息。因此,即使你在最后输入了4,由于count<5条件已经完成,但raw_input的位置意味着它仍然会请求一个输入,即使你已经赢了。

def guess(): 
    print "Please input a number smaller than 10, let's see if it is in my plan."
    print "You should figure out all the 5 numbers."
    my_list = [1, 3, 5, 7, 9]
    your_list = []
    count = 0

    while count < 5:
        n = int(raw_input('>'))
        if n in my_list:
            if n not in your_list:
                your_list.append(n) 
                count = count + 1
                print "Good job! You have got %d numbers!" % count
            else:
                print "You have already typed that. Input again!"
        else:
            print "That is not what I want."

    print "Here you can see my plan:", my_list
    print "You are so smart to  guess out, you win!"

guess()

这是我的修复代码的示例输出:

Please input a number smaller than 10, let's see if it is in my plan.
You should figure out all the 5 numbers.
>1
Good job! You have got 1 numbers!
>2
That is not what I want.
>3
Good job! You have got 2 numbers!
>5
Good job! You have got 3 numbers!
>7
Good job! You have got 4 numbers!
>4
That is not what I want.
>9
Good job! You have got 5 numbers!
Here you can see my plan: [1, 3, 5, 7, 9]
You are so smart to  guess out, you win!

1
更正一下,你只是修复了他的代码,没有任何解释,现在你已经解释了你的更改,我已经删除了它 :), 现在回答好多了。 - Nick stands with Ukraine
1
@NickA 可以理解,我通常会在回答后立即添加解释 ^^ - Adam Jaamour
1
谢谢!你的代码运行得非常好!现在我明白了我错在哪里。非常感谢 :) - FrancesWu

0
在我的电脑上,它是可以工作的。唯一不起作用的地方是,在退出 while 循环之前,我需要输入第六个元素。我将向您提供可能的改进和不同的实现概述。
此外,您正在使用 Python 2。如果您刚开始学习 Python,应考虑转移到 Python 3。
改进:
- `while count < 5:` 可以简单地变成 `while sorted(my_list) != sorted(your_list):`。 - 嵌套语句可以简化。 - 对输入进行检查会很好。
实现:
def guess_2():
    print ("Please input a number smaller than 10, let's see if it is in my plan.")
    print ("You should figure out all the 5 numbers.")

    # Parameters
    my_list = [1, 3, 5, 7, 9]
    your_list = []
    count = 0

    while sorted(my_list) != (sorted(your_list)):

        # Input:
        not_valid = True
        while not_valid:
            try:
                n = int(input('>'))
                not_valid = False
            except:
                print ("Please input a number.")

        if n in my_list and not n in your_list:
            your_list.append(n) 
            count = count + 1
            print ("Good job! You have got %d numbers!" % count)

        elif n in my_list and n in your_list:
            print ("You have already typed that. Input again!")

        else:
            print ("That is not what I want.")

    print ("Here you can see my plan:", my_list)
    print ("You are so smart to  guess out, you win!")

谢谢:)我刚开始学习Python,从来没有考虑过用你的方式编码。那真的很启发我!感谢您关于Python版本的建议。然而,我正在使用《笨办法学Python》这本书,作者建议我使用Python 2而不是Python 3来完成他书中的练习。所以我不知道该怎么办... - FrancesWu
@FrancesWu 我的观点是,开始学习一个即将被弃用的编程语言版本并不明智。你可以继续使用相同的课程,但使用Python 3。你会遇到错误,这也会教你了解版本之间发生了什么变化。 - Mathieu

0
截至2018年7月24日,所涉及的代码存在缩进错误。第3、5、7和8行的缩进为3个空格而不是4个。
当这些错误被纠正后,该代码可以在Python 2.7中运行,但"raw_input()"的位置不正确。在您的代码中:
while count < 5:
    # do some stuff
    # If previous guess correct, increment count
    n = int(raw_input('>'))  # This prompts the user again after the 5th success

raw_input() 应该只被调用一次:

while count < 5:
    n = int(raw_input('>'))
    # If previous guess correct, increment count

正如Mathieu所写,用户输入应始终进行验证。在这种情况下,如果输入了非数字字符,则程序会崩溃并引发ValueError异常。这可以很容易地通过Try: Except:习惯用法捕获:
guess = raw_input('>')
try:
    value = int(guess)
except ValueError:
    # Handle the error

另一个问题是,如果“my_list”有一个或多个重复的数字,那么游戏就无法完成。
一种可能的解决方案是:不要为“your_list”构建第二个列表,而是从“my_list”中删除元素,直到没有元素为止。
def guess(): 
    print "Please input a number smaller than 10, let's see if it is in my plan."
    print "You should figure out all the 5 numbers."
    my_list = [1, 3, 5, 3, 9]
    my_plan = str(my_list)

    while len(my_list) > 0:
        guess = int(raw_input('>'))
        try:
            int(guess)
        except ValueError:
            print "'%s' is not a number." % str(guess)
            continue

        if guess < 0 or guess > 9:
            print "ONE digit 0 to 9 please."
        else:
            if guess in my_list:
                my_list.remove(guess)  # Remove ONE instance of 'guess'
                # or remove ALL instances of 'guess'
                # my_list = [num for num in my_list if num != guess]
                print "Good job! You have got %d numbers!" % (5 - len(my_list))
            else:
                print "That is not what I want."
    print "Here you can see my plan:", my_plan
    print "You are so smart to  guess out, you win!"

guess()

(Python 2.x 是遗留版本,而 Python 3.x 是该语言的现在和未来)


抱歉排版有些问题:(我是用iPhone发送代码的,所以出了点差错...非常感谢你的建议!确实帮了我不少! - FrancesWu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接