Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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
如何在Python 3.2中选择输入_Python_String_Input - Fatal编程技术网

如何在Python 3.2中选择输入

如何在Python 3.2中选择输入,python,string,input,Python,String,Input,当我运行该程序时,默认为喜剧,然后是Tartuffe。 如何让它识别字符串中的不同类型?您需要存储输入,然后将其与所需内容进行比较,例如: 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

当我运行该程序时,默认为喜剧,然后是Tartuffe。

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

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

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")

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

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

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

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

您也没有存储输入

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]()

高度可扩展的代码

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")

说得好。“你难道不喜欢一流的东西吗?”Makoto挑衅地说!这和函数指针(来自C++)使输入处理变得更加容易。@gnibbler谢谢,捕捉得好!我使用Python2.7进行测试,但忘了更改:)
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')))