boys=("david","andrew","ted","tom","james","nicholas","kyle","michael","mark")
startn=()
uname=raw_input("What is your first name?: ")
begin=uname[0]
for name2 in range(len(boys)):
if begin== boys[name[0]]:
startn+=(boys[name2],)
print startn,"start with",begin
else:
print "Sorry there are no names that begin with", begin
答案 0 :(得分:0)
您在访问name[0]
时使用boys
作为索引。您想要使用name2
:
if begin == boys[name2][0]:
startn += boys[name2]
或者,您可以遍历boys
数组本身:
for boy_name in boys:
boy_name[0] == begin:
startn += boy_name
(我不完全确定您使用startn
做了什么,因为您还没有包含您的代码。)
答案 1 :(得分:0)
作为此目标的pythonic方式使用str.startswith()
:
>>> boys=("david","andrew","ted","tom","james","nicholas","kyle","michael","mark")
>>> boys[1].startswith('a')
True
>>> boys[2].startswith('b')
False
所以你的代码必须是:
boys=("david","andrew","ted","tom","james","nicholas","kyle","michael","mark")
startn=()
uname=raw_input("What is your first name?: ")
for name2 in boys:
if name2.startswith(uname[0]):
startn+=(boys[name2],)
print startn,"start with",begin
else:
print "Sorry there are no names that begin with", begin
答案 2 :(得分:0)
你可以在这里改进一些事情。让我们看看我们如何清理它并使其正常工作。
for name2 in range(len(boys)):
您不需要range()
或len()
来电。如果要迭代名称,可以直接使用for循环执行此操作。
for name in boys:
现在你的循环中有两个变量。您输入的名称为uname
,循环name
中的当前名称。您可以通过比较uname[0]
和name[0]