Python:类型索引异常错误? [英] Python: exception of type index error?

查看:56
本文介绍了Python:类型索引异常错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为我正在学习的入门编程课程编写一小段代码-在尝试这一课程之前,我没有遇到任何麻烦.就我所知,代码可以正常工作,但我不断收到IndexError,有人可以告诉我我缺少什么吗?

I have to write small sections of code for an introductory programming class I'm taking - I had no trouble until I tried this one. The code works fine so far as I can tell but I keep getting the IndexError, can anyone tell me what I'm missing?

vowel = {"a", "e", "o", "i", "u", "A", "E", "I", "O", "U"}
word = input("Enter a phrase: ")

if word[0] in vowel:
    print("an", word)
else:
    print("a", word)

该代码现在可以正常工作,我所需要的只是根据您的建议添加一个空字符串的附加if语句

The code's working perfectly now, all I needed was the additional if statement for an empty string, as per your suggestions

推荐答案

您可能需要检查是否为空输入,这意味着测试系统只是按回车键而不是输入实际的字符串.当您尝试为空字符串的第一个字符建立索引时,会出现索引错误.试试类似的东西:

You probably need to check for null input, meaning the test system is just hitting enter rather than entering an actual string. When you try to index the first character of an empty string you will get an index error. Try something similar to:

vowel = {"a", "e", "o", "i", "u", "A", "E", "I", "O", "U"}
word = input("Enter a phrase: ")
if word == "":
    print("please enter a word")
elif word[0] in vowel:
    print("an", word)
else:
    print("a", word)

您应该检查任务是否对如何处理空字符串有任何说明.

You should check if the assignment has any instructions on how to handle empty strings.

这篇关于Python:类型索引异常错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆