python - 第一个输入未插入列表
问题描述
我正在编写一个程序来接受用户输入以逐字构建句子。用户完成后,它应该显示列表中的句子和单词数量。我知道我的代码不完整,我只针对一个问题请求帮助。截至目前,我无法将第一个输入追加或插入到列表中,而其他输入则是。任何帮助都会很棒。我一直在寻找一段时间没有进展。
代码:
index = 0
def main():
wordList = []
inputFunc(wordList = [])
def inputFunc(wordList = []):
global index
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.insert(index,wordInput)
index += 1
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
inputCalc(choice)
completeList(wordList)
def inputCalc(choice):
while choice == 'y':
inputFunc()
while choice == 'n':
return
while choice == 'r':
clearList()
def completeList(wordList):
print(wordList)
exit()
def clearList():
wordList.clear()
main()
main()
解决方案
您的代码存在很多问题,但是您的单词未附加到列表中的主要原因是可变的默认参数通常不会执行您想要的操作。
相反,只需在一个函数中执行所有操作。
def main():
inputFunc()
def inputFunc():
running = True
wordList = []
while running:
print("To make a sentence, enter one word at a time... ")
wordInput = input("Enter word... : ")
wordList.append(wordInput)
while True:
choice = input("(y = Yes, n = No, r = Reset List)Another word?: " )
if choice == 'y':
break
elif choice == 'n':
running = False
break
elif choice == 'r':
wordList = []
break
print(wordList)
if __name__ == "__main__":
main()
详细的答案是你第一次在inputFunc()
里面调用main()
你传递一个空列表:
def main():
wordList = []
inputFunc(wordList=[])
当您通过内部递归再次调用它时,inputCalc(choice)
您inputFunc()
无需传递任何参数即可调用,因此使用不同的列表,即预初始化列表。
def inputCalc(choice):
while choice == 'y':
inputFunc()
推荐阅读
- c++ - C ++如何强制每隔几分钟更新一次NTP并检查更新是否成功
- ios - 启动画面和首屏之间的黑屏 (iOS)
- c# - 当一个接口用相同的方法签名多次实现但结果不同时会发生什么?
- email - 捕获退回到无回复电子邮件地址的邮件
- qt - QML从抽屉拖动到另一个项目,当抽屉关闭时如何保持连续拖动
- php - PHP preg_match_all 带有可选参数
- git - 由于 git branch (git-branch) 支持 --format 选项的哪个确切版本?
- javascript - html超链接下载文件问题
- c# - 等待操作符,执行直到任务返回
- java - 等待一些线程处于等待状态才能继续