首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python 3.2中选择输入

如何在Python 3.2中选择输入
EN

Stack Overflow用户
提问于 2012-11-07 11:34:09
回答 3查看 1.5K关注 0票数 2
代码语言:javascript
复制
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。

如何让它识别字符串中的不同类型?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-07 11:39:07

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

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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]()

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

票数 5
EN

Stack Overflow用户

发布于 2012-11-07 11:41:57

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

您也没有存储输入。

代码语言:javascript
复制
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")
票数 0
EN

Stack Overflow用户

发布于 2012-11-07 11:44:16

高度可扩展的代码。

代码语言:javascript
复制
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')))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13262769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档