【问题标题】:Why do I keep getting arbitrary syntax errors in Python?为什么我在 Python 中不断收到任意语法错误?
【发布时间】:2014-05-27 21:32:03
【问题描述】:

我正在用 python 编写一个简单的脚本来返回一个 GDP 值。从第 6 行开始,它给出了“语法错误”,没有进一步说明。我注释掉了这个问题的所有行(第 6 行结束),在第 16 行,我收到“解析时出现 EOF”错误。我真的不确定该怎么做,因为我检查了不匹配的分隔符、不正确的语法等,但我唯一能找到的就是我执行打印语句的方式,但因为它们都是相同的,只有一个得到了一个不太可能出现的解析错误。这是代码:

y_i = int(input("What year did your alt history begin?"))
y_f = 2014
p_i = int(input("Enter population of your territory starting from your alt history.")
p_g = int(input("Enter average population growth from year to year in a numerical value. No percentages.")
p_f = (p_i(p_g - y_f) ** 2)/(10000 * y_i ** 2)

print("This is your nation's population.", p_f, "If you got an error, check that you put in all inputs correctly.")

gdp_capita = int(input("What is your GDP per capita? Please use the number only, in your own currency.")


gdp = pop * gdp_capita

print("This is your nation's GDP.", gdp, "If you get an error, please check that you entered everything in correctly.")

【问题讨论】:

  • “因为我检查了不匹配的分隔符”:似乎不太成功..
  • 在第三行和第四行,您缺少右括号。还有在线gdp_capita = ...
  • 顺便说一句,p_i(p_g - y_f) 也不起作用——它试图调用一个整数。你可能会想到p_i*(p_g - y_f)
  • 为什么倒数第三行有个未调用的变量pop
  • 如果将长文本字符串转换为短常量,可能会更容易发现问题所在。 IE:“你的 alt 历史是从哪一年开始的?”类似于 START_YEAR_PROMPT。

标签: python parsing math syntax


【解决方案1】:

你的错误在你的语法。您缺少右括号。在第 3、4 和 9 行,您有:int(input("...")没有最后的右括号!您还尝试在第 5 行调用整数,使用 p_f = p_i(p_g...)。我假设你正在尝试乘法,所以我在那里放了一个乘法符号(一个星号)。另外,请确保您现在双星号表示“权力”。 2**3 = 8,不是6

将您的代码更改为:

y_i = int(input("What year did your alt history begin?"))
y_f = 2014
p_i = int(input("Enter population of your territory starting from your alt history."))
p_g = int(input("Enter average population growth from year to year in a numerical value. No percentages."))
p_f = (p_i*(p_g - y_f) ** 2)/(10000 * y_i ** 2)

print("This is your nation's population.", p_f, "If you got an error, check that you put in all inputs correctly.")

gdp_capita = int(input("What is your GDP per capita? Please use the number only, in your own currency."))


gdp = pop * gdp_capita

print("This is your nation's GDP.", gdp, "If you get an error, please check that you entered everything in correctly.")

但你在第 1 行就做对了 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-22
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多