Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中,如何获取一个项并在for循环中执行特定的操作?_Python_Python 3.x_List_Loops_For Loop - Fatal编程技术网

在Python3中,如何获取一个项并在for循环中执行特定的操作?

在Python3中,如何获取一个项并在for循环中执行特定的操作?,python,python-3.x,list,loops,for-loop,Python,Python 3.x,List,Loops,For Loop,代码如下: ls = ['apple', 'banana', 'pear'] for z in ls: x = input("Do you like %s ?" %z) if x == 'yes': print('Cool, ' + z + ' is very good.') break elif x == 'no': continue else: print('I am not sure

代码如下:

ls = ['apple', 'banana', 'pear']


for z in ls:
    x = input("Do you like %s ?" %z)
    if x == 'yes':
        print('Cool, ' + z + ' is very good.')
        break
    elif x == 'no':   
        continue
    else:
        print('I am not sure what you want')
有了这段代码,我想做两件事:

第二次循环后(你喜欢香蕉吗?),我想打印一条消息。但只有在“你喜欢香蕉吗”之后,而不是在其他时候,它才循环。 那么,有没有一种方法可以只为其中一个循环打印消息?因为如果我这样尝试:

elif x == 'n':   
    print('are you sure you do not like it?')
    continue
它将打印列表中所有3项(苹果、香蕉和梨)的消息

2-另一件事是设置当else语句运行时(用户输入与“是”或“否”不同的内容),我希望它在循环开始时重新启动(再次询问用户“你喜欢苹果吗?”而不是继续第二项(“你喜欢香蕉吗”)。 有没有办法将循环设置回开始

希望问题足够清楚


谢谢

我想这就是你需要的:

ls = ['apple', 'banana', 'pear']
i = 0
flag = True
while i<len(ls) :

    x = input("Do you like %s ?" %ls[i])
    if x == 'yes':
        print('Cool, ' + ls[i] + ' is very good.')
        flag = True
        break

    elif x == 'no':   
        if i >=1 and flag:
            print('are you sure you do not like it?')
            i = i -1
            flag = False
    else:
        i = -1
        flag = True
    i+=1
二,

三,


如果你觉得可以的话,我用enumerate和一个标志做了这件事:

为True时:
成功标志=真
对于枚举中的i,z(ls):
x=输入(“您喜欢%s吗?”%z)
如果x==‘是’:
打印(“很酷,+z+”非常好。”)
elif x==‘否’:
如果i==1:
打印('您确定不喜欢吗?')
其他:
打印('我不确定您想要什么')
成功标志=错误
打破
如果成功(u标志):
打破
输出:

你喜欢苹果吗?是的
酷,苹果很好。
你喜欢香蕉吗?不喜欢
你确定你不喜欢吗?
你喜欢梨吗?出去
我不知道你想要什么
你喜欢苹果吗?

所谓的“状态机”可以很好地描述您的问题

图中的每个圆/正方形都是一个“状态”。用户的输入控制状态之间的转换 代码: 示例输出:

########################################
RESULTS:
----------------------------------------
Do you like apples?   yes
Do you like bananas?   yes
Do you like pears?   yes
Do you want to play again?   yes
Do you like apples?   yes
Do you like bananas?   yes
Do you like pears?   yes
Do you want to play again?   no
----------------------------------------

Process finished with exit code 0

您似乎需要一个
while
循环。
Do you like apple ?yes
Cool, apple is very good.
Do you like apple ?no
Do you like banana ?yes
Cool, banana is very good.
class YesNoStateBase:
    pass

class ExitState(YesNoStateBase):
    def ask_for_instructions(self):
        return ""

    def ask_for_data(self):
        return str(self)

    def ask_for_geography(self, *args):
        return self
ExitState.ExitState = ExitState

class YesNoState:

    def __init__(self, prompt, *, yes=ExitState, no=ExitState):
        self._prompt = prompt + " "
        self._yes = yes
        self._no = no

    def set_yes(self, state):
        self._yes = state

    def ask_for_instructions(self):
        return self._prompt

    def ask_for_data(self):
        return self._data

    def ask_for_geography(self, x_stryng):
        i_stryng = str(x_stryng).strip().lower()
        nxt_state = type(self).ExitState
        if i_stryng == "y" or i_stryng == "yes":
            self._data = self._prompt + " yes"
            nxt_state = self._yes
        elif i_stryng == "n" or i_stryng == "no":
            self._data = self._prompt + " no"
            nxt_state = self._no
        else:
            nxt_state = YesNoState(
                "I don't understand. Please try again\n" + self._prompt,
                yes=self._yes,
                no=self._no
            )
        return nxt_state

YesNoState.YesNoState = YesNoState
YesNoState.ExitState = ExitState

class StateMiner:
    def __init__(self):
        self._data = list()
    def go_to_work(self, state):
        while True:
            # `msg`............`message`
            msg = state.ask_for_instructions()
            nxt_state = state.ask_for_geography(input(msg))
            datum = state.ask_for_data()
            self._data.append(datum)
            if nxt_state== state.ExitState:
                return
            state = nxt_state



GoAgainQ    = YesNoState("Do you want to play again? ")
PearQ       = YesNoState("Do you like pears? ", yes=GoAgainQ, no=GoAgainQ)
SureBananaQ = YesNoState("Are you certain that you do not like bananas (yes = hate bananas)?", yes=PearQ, no=PearQ)
BananaQ     = YesNoState("Do you like bananas? ", yes=PearQ, no=SureBananaQ)
AppleQ      = YesNoState("Do you like apples? ", yes=BananaQ, no=BananaQ)
GoAgainQ.set_yes(AppleQ )

bob = StateMiner()
bob.go_to_work(AppleQ)
print(40*"#", "RESULTS:", 40*"-", sep="\n")
print("\n".join(bob._data))
print(40*"-", sep="\n")
########################################
RESULTS:
----------------------------------------
Do you like apples?   yes
Do you like bananas?   yes
Do you like pears?   yes
Do you want to play again?   yes
Do you like apples?   yes
Do you like bananas?   yes
Do you like pears?   yes
Do you want to play again?   no
----------------------------------------

Process finished with exit code 0