#Dancing Text :D
listinput = raw_input("Input text(usually between 1-10 letters ")
dance_time = raw_input("Alternate How Many Times? ")
listinput = list(listinput)
length = len(listinput)
alternate = 0
counter = 0
first_input = listinput
swap_counter = 0
tempchar = ""
counter = int(counter) #Just to make sure...getting errors
#above are just defining variable types and changing types to lists.
while counter <= length:
if alternate == 0: #first, third, fifth character
alternate = alternate + 1
counter = counter + 1
elif alternate == 1: #second, fourth, sixth character and so on....
tempchar = listinput[counter]
tempchar = str(tempchar)
tempchar = tempchar.swapcase()
listinput[counter] = tempchar #It should be the number 1 the first time it runs, but it gives a index error.
alternate = alternate - 1
counter = counter + 1
while swap_counter <= dance_time:
print first_input
print input
swap_counter = swap_counter + 2
这就是错误-
第20行,模块内
tempchar=listinput[计数器]
索引器错误:列表索引超出范围
我查找了索引错误,“1”应该在列表的范围内,(每当我测试它时,我都会输入“hello”)
如果我理解正确的话,第20行在运行时应该是“listinput[1]”,变量“counter”是1,因为它只循环一次
你的
dance_time
是一个字符串。请使用swap_counter <= int(dance_time):
一些可能有用的东西:
你不需要临时工。您可以转换代码:
至singlr线:
注意,您只是根据
alternate
的值交换交替字符的大小写。我猜,虽然在这个例子中设置为0
,但在实际的程序中,您会想随意更改它。然后,您可以尝试以下操作:或者简单地说:
这是一样的,假设
alterante
是0
或1
,这很容易用if
条件检查最后,请注意Python中的函数是一级值。也可以返回一个函数,并将其作为条件,如下所示:
这是一个稍微容易阅读
在这里,我又把事情简单化了。如果alternate不是
0
或1
,则可能需要raise
函数中的ValueError
最后,按照上述示例,您还可以执行以下操作:
我认为你的问题是假设列表的索引是从1开始的,实际上它们是从0开始的,所以如果你的列表中有一个项目,列表[0]会给你这个项目
所以,能够执行
你得确定
是真的,这里不是这样,因为counter可以等于length
相关问题 更多 >
编程相关推荐