【问题标题】:How to choose between input in Python 3.2如何在 Python 3.2 中的输入之间进行选择
【发布时间】:2012-11-07 03:34:08
【问题描述】:
input("Would you like to read: comedy, political, philisophical, or tragedy?")

a = "comedy"
b = "political"
c = "philisophical"
d = "tragedy"

if a:
    input("Would you like the author's nationality to be: English or French?")
    e = "French"
    d = "English"
    if e:
        print("Tartuffe")
    elif d:
        print("Taming of the Shrew")

当我运行程序时,它只是默认为喜剧,然后是 Tartuffe。
如何让它识别字符串中的不同流派?

【问题讨论】:

    标签: python string input


    【解决方案1】:

    您需要存储输入,然后将其与您想要的进行比较,例如:

    a = "comedy"
    b = "political"
    c = "philisophical"
    d = "tragedy"
    
    user_input = input("Would you like to read: comedy, political, philisophical, or tragedy?")
    
    if user_input == a:
        user_input = input("Would you like the author's nationality to be: English or French?")
    
        if user_input == e:
            #do more stuff
    

    更好的方法(在我看来)是这样做:

    def comedy():
        print("comedy")
    
    def political():
        print("political")
    
    def philisophical():
        print("philisophical")
    
    def tragedy():
        print("tragedy")
    
    types = {"comedy":comedy,
             "political":political,
             "philisophical":philisophical,
             "tragedy":tragedy
            }
    
    user_input = input()
    
    types[user_input]()
    

    因为它更容易管理和读取不同的输入。

    【讨论】:

    • 说得好。你不只是喜欢一流的物品吗?
    • @Makoto 挑衅!那和函数指针(来自 C++)使输入处理更容易。
    • @gnibbler 谢谢,很好!我正在使用 python 2.7 进行测试并忘记更改它:)
    【解决方案2】:

    您只是在测试 e 的值是否为真(字符串不为空,因此为真)。

    您也没有存储输入。

    selection = input("Would you like the author's nationality to be: English or French? ")
    
    if selection == e:
        print("Tartuffe")
    elif selection == d:
        print("Taming of the Shrew")
    

    【讨论】:

      【解决方案3】:

      高度可扩展的代码。

      choices = {'e': ('French', 'Tartuffe'), 'd': ('English', 'Taming of the Shrew')}
      
      cstr = ', '.join('%r = %s' % (k, choices[k][0]) for k in sorted(choices))
      prompt = 'What would you like the author\'s nationality to be (%s): ' % cstr
      
      i = input(prompt).lower()
      
      print('%s: %s' % choices.get(i, ('Unknown', 'Untitled')))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 2013-01-03
        • 1970-01-01
        • 2022-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多