【发布时间】:2015-11-11 14:49:08
【问题描述】:
脚本的目的是允许用户输入一个单词并输入一个他们希望在字符串中找到的字符。然后它将查找所有出现并输出索引的位置。 我当前的脚本运行良好,因此没有语法错误,但是当我输入一个字符时,它什么也不做。 我的代码:
print("This program finds all indexes of a character in a string. \n")
string = input("Enter a string to search:\n")
char = input("\nWhat character to find? ")
char = char[0]
found = False
start = 0
index = start
while index < len(string):
if string[index] == char:
found = True
index = index + 1
if found == True:
print ("'" + char + "' found at index", index)
if found == False:
print("Sorry, no occurrences of '" + char + "' found")
哪里出错了?因为它不打印出我的角色。奇怪的是,当我为字符串输入单个字符时,即两个输入都输入“c”时,它表示索引为 1,而它应该为 0。
【问题讨论】:
-
想想
index = index + 1何时到达(尝试在脑海中逐行遍历代码,在纸上或使用例如pythontutor.com)。 -
因为索引从 0 开始,你在给它加 1 后返回索引。
-
提示:正如@jonrsharpe 所写。你的评论“什么都不做”应该是:“它在while循环中无限循环,索引永远停留在0”。
标签: python