Python代码运行报语法错误 提示可能遗漏逗号如何解决
错误原因
运行时触发perhaps you forgot a comma语法错误,根源是标注了#THIS IS THE LINE的print行存在引号使用错误:
- 该行里
"{}"被Python识别为独立的字符串参数,后面的has {} words内容没有被引号包裹,和前一个字符串之间也没有逗号分隔,解析器就会判定参数间遗漏了逗号。 - 该行还存在两处笔误:多写了一个完全没用的
"\\"参数,.format()方法的调用位置错误,没有包裹完整的输出模板。
除此之外代码还有两个会触发运行报错的问题:
- 存储排序结果的变量名是
sorted_words,打印时错写成sort_words,会触发变量未定义错误 - 调用的
break_words、sort_sentence等自定义函数没有给出实现,直接运行会报函数不存在错误
修正后可直接运行的代码
# 补全所需的自定义函数 def break_words(sentence): return sentence.split(" ") def count_words(words): return len(words) def sort_sentence(sentence): words = break_words(sentence) return sorted(words) def print_first_word(words): print("第一个单词:", words[0]) def print_last_word(words): print("最后一个单词:", words[-1]) def print_first_and_last_word(sentence): words = break_words(sentence) print("首尾单词分别为:", words[0], words[-1]) sentence = "I think it's interesting that 'cologne' rhymes with 'alone'" words = break_words(sentence) sorted_words = sort_sentence(sentence) # 修复语法错误的打印行 print("句子「{}」一共有{}个单词".format(sentence, count_words(words))) print("拆分得到的单词:", words) print("排序后的单词:", sorted_words) print_first_word(words) print_last_word(words) print_first_and_last_word(sentence)
核心修改点
- 调整报错print行的引号范围,把整个输出模板放在同一对引号内,让
.format()正确匹配两个占位符,删除多余的无意义"\\"参数 - 修正排序结果打印时的变量名拼写错误,把错写的
sort_words改为提前定义的sorted_words - 补全所有调用的自定义函数逻辑,覆盖分词、计数、排序、打印首尾单词的需求
内容的提问来源于stack exchange,提问作者mattramey27
相关产品推荐
相关产品推荐

