设计猜测 python 中的数字列表的游戏时遇到问题

Trouble in designing a game of guessing a list of numbers in python

今天我想设计一个游戏来猜我设置的数字列表。玩家应该打印出所有 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”。为什么会出错?

您刚刚在 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!

在我这边,它正在工作。唯一一点不起作用,我需要在退出 while 循环之前输入第 6 个元素。我只是要向您概述可能的改进和不同的实施方式。

此外,您正在使用 python 2。您应该考虑转向 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!")

截至 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 is legacy, Python 3.x is the present and future of the language)