Python食材用量计算程序报ingredient_two行语法错误,无法定位求解答
Python食材计算程序语法错误排查
问题根因定位
1. 函数调用缺失闭合右括号
逐行核对所有使用int(input())的输入行,每一处都缺少外层int()函数对应的收尾右括号:
- 原写法示例:
ing_one_oz = int(input("How many ounces of this ingredient?: "),仅完成了input()的括号闭合,没有补上int()的收尾) - 后续对应
ing_two_oz、ing_three_oz、servings_amt的输入行都存在完全相同的括号缺失问题
为啥报错提示指向ingredient_two开头的行?
Python解释器遇到未闭合的括号时,会持续向后扫描代码寻找可以匹配的右括号,直到扫描到ingredient_two所在的行,始终找不到能和int()配对的闭合括号,才会抛出语法错误。这也是新手容易遇到的迷惑场景:语法错误提示的行号,往往不是真正写错的代码行,而是解释器检测到括号逻辑断裂时已经走到的位置。刚好这行和上面写ingredient_one的行格式完全一致,就会更难定位问题。
2. 续行符使用错误
原代码在长字符串拼接的print语句里,把**正斜杠/**当做了续行符使用。Python的行续接符是反斜杠\,正斜杠是除法运算符,写在字符串末尾、引号外的位置会直接触发语法错误。
修正后的可运行代码
ingredient_one = input("What is the first ingredient?: ") ing_one_oz = int(input("How many ounces of this ingredient?: ")) ingredient_two = input("What is the second ingredient?: ") ing_two_oz = int(input("How many ounces of this ingredient?: ")) ingredient_three = input("What is the third ingredient?: ") ing_three_oz = int(input("How many ounces of this ingredient?: ")) servings_amt = int(input("How many servings would you like?: ")) ing_one_oz = ing_one_oz * servings_amt ing_two_oz = ing_two_oz * servings_amt ing_three_oz = ing_three_oz * servings_amt print("In order to make " + str(servings_amt) + " servings of your recipe, you will need " + str(ing_one_oz) + " ounces of " + str(ingredient_one) + ", " + str(ing_two_oz) + " ounces of " + str(ingredient_two) + ", and " + str(ing_three_oz) + " ounces of " + str(ingredient_three) + ".")
实用提示:长字符串拼接场景下,推荐把所有待拼接内容放在同一对圆括号内,不需要额外使用续行符,既可以提升代码可读性,也能减少符号输入错误的概率。
内容的提问来源于stack exchange,提问作者Groovy Julie
相关产品推荐
相关产品推荐

