【问题标题】:Python: The code disobeys the conditional depending on the inputPython:代码根据输入不服从条件
【发布时间】:2016-03-24 21:21:14
【问题描述】:

我正在制作一个刽子手游戏。当我在没有条件和类的情况下编写代码时,它运行良好。基本上我对以下代码的问题是:

  1. 只有字母“t”会匹配。我找不到任何其他字母可以匹配。

  2. 如果我在第一次尝试时输入“t”,然后故意将接下来的 4 个字母弄错,直到 7 圈后才结束。然而,如果我先输入任何其他字母,它会在 4 个错误的转弯后结束,就像它应该的那样。

我的问题....

  1. 如何让它与self.word 索引中的其他字母匹配?

  2. 如果我在第一次尝试时输入“t”并且此后所有其他字母都出错,为什么它不遵守我在 main 方法中使用 while 循环设置的条件?

    class Hang():
    
        def __init__(self):
            self.turns = 0
            self.word = ['t', 'h', 'i', 's']
            self.empty = ["__", "__", "__", "__"]
            self.wrong = []
    
        def main(self):
            while self.turns < 4:
                for i in self.word:
                    choice = raw_input("Enter a letter a-z: ")
                    if choice == i:
                        index = self.word.index(i)
                        self.empty.pop(index)
                        self.empty.insert(index, i)
                        print self.empty
                    else:
                        print "Wrong"
                        self.wrong.append(choice)
                        print self.wrong
                        print self.empty
                        self.turns += 1
    
    char1 = Hang()
    char1.main()
    

【问题讨论】:

    标签: python-2.7 class while-loop iteration


    【解决方案1】:

    在刽子手游戏中,您可以按任意顺序猜出短语中的任意字符。但是你正在使用 for 循环按顺序遍历每个字符,并且只有当玩家正确地按顺序猜出字符时它才是正确的

    试试这个

    while self.turns < 4:
    
        choice = raw_input("Enter a letter a-z: ")
    
        # optional, if user enters more than a single letter
        if len(choice) > 1:
            print "invalid choice"
            continue                   # loop again from start
    
        index = self.word.index(choice)
    
        if index != -1:    
            # -1 indicates character in not int the string
            # so this block is only executed if character is
            # in the string
    
            self.empty[index] = choice     # no need to pop, you can simply change the value of the list at a given index
    
        else:
            print "wrong"
            self.turns += 1
    
        print self.empty
    

    【讨论】:

    • index = self.word.index(i)index()方法中的i是哪里来的?
    • @staredecis 对此感到抱歉,应该是 index(choice)
    猜你喜欢
    • 2019-01-13
    • 2022-01-19
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    相关资源
    最近更新 更多