微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我想在while循环中进行操作,如果使用字典进行statematent并返回我用return分配的值

如何解决我想在while循环中进行操作,如果使用字典进行statematent并返回我用return分配的值

如果它们等于字典的值并打印字典值,我想返回if语句,而不仅仅是使用=='HW'并打印一些文本。现在我什么也没退,所以我想知道自己做错了什么。当我先给出错误答案然后给出正确答案时,如何退出while循环?

from ex45f import live
class adult(live):

    def __init__(self,choose):
        self.choose = choose

    def choices(self):
        options = {
            'HW': 'Hard Working','PA': 'Partying','DE': 'Doing everyting a bit',}
#while choose != 'HW' or 'PA' or 'DE':
        while not (self.choose == 'HW' or self.choose == 'PA' or self.choose == 'DE'):
            x = input("""Choose again
> """)
            print(x)
        if self.choose == options['HW']:
            return "You are going to be millionare"
        elif self.choose == options['PA']:
            return "You will have the first year a great life and then you will hate it"
        elif self.choose == options['DE']:
            return "nothing intersting in life happens."
        else:
            return "Wrong input"

choose = input("""Choose one of those options: HW,PA,DE)
> """)
zw = adult(choose)
zw.choices()

解决方法

所以有几点评论:

  1. self.choose将为HW,PA或DE 您的政治家是否检查if self.choose == options['HW']
    options ['HW']实际上是“辛勤工作” ,因此在上述情况下,self.choose总是在else处结束。
    您的if语句应为:
    if self.choose == "HW":
    if self.choose == "PA":
    if self.choose == "DE":

  2. 您的while循环看起来像:while self.choose not in options:

  3. 如果self.choose不在列表中,则您将获得一个新输入并将其存储在x中。 self.choose保持不变。因此while循环将是无限的。
    而不是x = input进行self.choose = input,因此,当用户输入正确的选项之一时,他们将退出while循环。

  4. 如果要获取options的值,请添加return "{} The text to return".format(options[self.choose])

  5. 最后,如果您对术语Hard WorkingPartyingDoing everthing a bit不感兴趣,则只需将选项作为列表即可:
    {{1} }那么您就不需要options = ["DE","PA","HW"]



希望对您有所帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。