这是一个我已经解决的问题,但我需要理解为什么我在我的第一次尝试失败
目标是打印单词(大写),从“h”开始,不包括非字母
这句话的意思是:“无论你走到哪里,都要全心投入”
这是我的第一次尝试:
quote = input("Enter a quote: ")
word=""
for x in quote:
if x.isalpha()==True and len(x)>0:
word+=x.lower()
else:
if word[0]>="h" and len(word)>0:
print(word.upper())
word=""
else:
word=""
if word[0]>="h" and len(word)>0:
print(word.upper())
导致:
Enter a quote: Wheresoever you go, go with all your heart
WHERESOEVER
YOU
Traceback (most recent call last):
File "/home/dubirka/PycharmProjects/dasho-project/dasho-
beginner.py", line 7, in <module>
if word[0]>="h" and len(word)>0:
IndexError: string index out of range
Process finished with exit code 1
但是当我加上“if word.isalpha()==True”和“it worked:
else:
if word.isalpha()==True and word[0]>="h" and len(word)>0:
print(word.upper())
word=""
else:
word=""
那是因为
word
一开始是空的所以呢
失败,因为第一个条件触发异常(数组越界)
现在使用:
isalpha
返回空字符串上的False
,因此没有访问越界数组的风险(顺便说一句,不需要对True
进行测试,word.isalpha()
就足够了)注意,正确的解决方法是首先测试
word
的“真值”(即,如果不是空的话进行测试):相关问题 更多 >
编程相关推荐