简体   繁体   English

嵌套循环的“如果”语句将不会打印元组的值

[英]Nested Loop 'If'' Statement Won't Print Value of Tuple

Current assignment is building a basic text adventure. 当前的任务是建立基本的文字冒险。 I'm having trouble with the following code. 我在使用以下代码时遇到麻烦。 The current assignment uses only functions, and that is the way the rules of the assignment state it must be done. 当前的分配仅使用功能,这就是分配状态规则必须完成的方式。

def make_selections(response):
    repeat = True
    while repeat == True:
        selection = raw_input('-> ')
        for i, v in enumerate(response):
            i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
            if selection == i:
                print v[1]
            else:
                print "There's an error man, what are you doing?!?!?"

firstResponse = 'You chose option one.'
secondResponse = 'You chose option two.'
thirdResponse = 'You chose option three.'

responses = [(0, firstResponse), (1, secondResponse),( 0, thirdResponse)]

make_selections(responses)

My intention in that code is to make it so if the user selects a 1 , it will return firstResponse , if the user selects 2 it will return secondResponse , etc. 我在该代码中的意图是使它成为firstResponse ,如果用户选择1 ,它将返回firstResponse ;如果用户选择2 ,它将返回secondResponse ,等等。

I am basically just bug testing the code to make sure it produces the appropriate response, hence the "Error man..." string, but for some reason it just loops through the error message without printing the appropriate response string. 我基本上只是对代码进行错误测试,以确保它产生适当的响应,因此是"Error man..."字符串,但是由于某种原因,它只是循环遍历错误消息而没有输出适当的响应字符串。 Why is this? 为什么是这样?

I know that this code is enumerating the list of tuples and I can call them properly, as I can change the code to the following and get the expected output: 我知道这段代码正在枚举元组列表,我可以正确地调用它们,因为我可以将代码更改为以下内容并获得预期的输出:

for i, v in enumerate(response):
    i += 1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
    print i, v

Also, two quick asides before anyone asks: 另外,在任何人问到之前,有两个快速解决方案:

  • I know there is currently no way to get out of this while loop. 我知道目前没有办法摆脱这种while循环。 I'm just making sure each part of my code works before I move on to the next part. 在继续下一部分之前,我只是确保代码的每个部分都能正常工作。 Which brings me to the point of the tuples. 这使我想到了元组。
  • When I get the code working, a 0 will produce the response message and loop again, asking the user to make a different selection, whereas a 1 will produce the appropriate response, break out of the loop, and move on to the next 'room' in the story... this way I can have as many 'rooms' for as long of a story as I want, the player does not have to 'die' each time they make an incorrect selection, and each 'room' can have any arbitrary amount of options and possible responses to choose from and I don't need to keep writing separate loops for each room. 当我使代码正常工作时,0将产生响应消息并再次循环,要求用户做出不同的选择,而1将产生适当的响应,跳出循环,然后移至下一个“房间”。在故事中...通过这种方式,我可以根据需要为故事提供尽可能多的“房间”,玩家不必每次选择不正确的地方就“消亡”,每个“房间”可以有任意数量的选项和可能的响应可供选择,我不需要为每个房间编写单独的循环。

There are a few problems here. 这里有一些问题。

First, there's no good reason to iterate through all the numbers just to see if one of them matches selection ; 首先,没有充分的理由遍历所有数字,只是看看其中一个是否与selection匹配; you already know that will be true if 1 <= selection <= len(response) , and you can then just do response[selection-1] to get the v . 您已经知道,如果1 <= selection <= len(response)将是正确的,然后可以只做response[selection-1]来获得v (If you know anything about dict s, you might be able to see an even more convenient way to write this whole thing… but if not, don't worry about it.) (如果您对dict有所了解,您也许可以找到一种更加方便的方式来编写整篇文章……但是,如果不知道,不必担心。)

But if you really want to do this exhaustive search, you shouldn't print out There is an error man after any mismatch, because then you're always going to print it at least twice. 但是,如果您真的想进行详尽的搜索,则不应该打印出任何不匹配There is an error man ,因为那样的话,您总是至少要打印两次。 Instead, you want to only print it if all of them failed to match. 相反,您只想在所有都不匹配的情况下打印它。 You can do this by keeping track of a "matched" flag, or by using a break and an else: clause on your for loop, whichever seems simpler, but you have to do something. 您可以通过跟踪“ matched”标志或在for循环上使用breakelse:子句来执行此操作,看似比较简单,但您必须执行一些操作。 See break and continue Statements, and else Clauses on Loops in the tutorial for more details. breakcontinue语句,以及else对循环条款在本教程中了解更多详情。

But the biggest problem is that raw_input returns a string, and there's no way a string is ever going to be equal to a number. 但是最大的问题是raw_input返回一个字符串,并且字符串永远不会等于一个数字。 For example, try '1' == 1 in your interactive interpreter, and it'll say False . 例如,在您的交互式解释器中尝试'1' == 1 ,它将说False So, what you need to do is convert the user's input into a number so you can compare it. 因此,您需要做的是将用户的输入转换为数字,以便进行比较。 You can do that like this: 您可以这样做:

try:
    selection = int(selection)
except ValueError:
    print "That's not a number!"
    continue

Seems like this is a job for dictionaries in python. 似乎这是python中字典的工作。 Not sure if your assignment allows this, but here's my code: 不知道您的作业是否允许这样做,但这是我的代码:

def make_selections(response):
   selection = raw_input('-> ')
   print response.get(selection, err_msg)

resp_dict = {
    '1':'You chose option one.',
    '2':'You chose option two.',
    '3':'You chose option three.'
}
err_msg = 'Sorry, you must pick one of these choices: %s'%sorted(resp_dict.keys())
make_selections(resp_dict)

The problem is that you are comparing a string to an integer. 问题是您正在将字符串与整数进行比较。 Selection is raw input, so it comes in as a str. 选择是原始输入,因此它作为str出现。 Convert it to an int and it will evaluate as you expect. 将其转换为一个int,它将按照您的期望进行评估。

You can check the type of a variable by using type(var). 您可以使用type(var)检查变量的类型。 For example, print type(selection) after you take the input will return type 'str'. 例如,输入后的打印类型(选择)将返回类型'str'。

def make_selections(response):
    repeat = True
    while repeat == True:
        selection = raw_input('-> ')
        for i, v in enumerate(response):
            i +=1 # adds 1 to the index to make list indices correlate to a regular 1,2,3 style list
            if int(selection) == i:
                print v[1]
            else:
                print "There's an error man, what are you doing?!?!?"

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

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