【问题标题】:Python code won't run?Python代码不会运行?
【发布时间】:2016-08-28 09:37:04
【问题描述】:

您好,我想知道为什么这段代码不会运行,谢谢。

count = 0
finished = False
total = 0
while not finished:
    number = int(input("Enter a number(0 to finish)"))
    if number == 0:
        finished = True
        else:
            total = total + number
            count = count + 1
print("the average is", total/ count)
count = 0

【问题讨论】:

  • 有错误提示吗?
  • 欢迎来到Stack Overflow,我们正在尝试在这里创建一个good Qs&As 的存储库。请至少阅读tour 并为您当前的帖子带来一些质量(通过编辑)。 1)您的帖子不包含问题。它在语句上标记了一个问号,这是不一样的。 2)“你好”和“谢谢”对帖子的清晰度没有任何帮助,所以不要使用它们。 3) 其他人不关心你想知道、相信、早餐吃了什么;包含一句话会提供更多信息:为什么以下代码在我运行程序时会抛出错误“ABC XYZ”
  • 4) 通过选择您粘贴的完整代码块,然后点击编辑框上方的{} 图标,至少学会正确地格式化代码。 5) 对“i”等词使用正确的拼写,并不是每个人都是母语人士并理解书面俚语。

标签: python python-3.x


【解决方案1】:

您的脚本没问题,您没有正确缩进 elseclause,这是一个工作示例,此外,您应该强制转换为浮动平均值:

count = 0
finished = False
total = 0

while not finished:
    number = int(input("Enter a number(0 to finish)"))
    if number == 0:
        finished = True
    else:
        total = total + number
        count = count + 1

print("the average is", float(total) / float(count))
count = 0

另一种可能的方法是用几行来做同样的事情:

values = []
while True:
    number = int(input("Enter a number(0 to finish)"))
    if number == 0:
        break

    values.append(number)

print("the average is", float(sum(values)) / float(len(values)))

【讨论】:

  • 如果我们只讨论几行:print(f"the average is {__import__('statistics').mean(map(int, iter(input, '0')))}")。 ;-)
  • @Veky 很好,我会给你点赞,因为 OP 的标签之一是 python-3.x ;-)
【解决方案2】:

它确实运行,我能看到的唯一问题是你的 else 在你的 if 块内缩进。在 Python 中,缩进很重要,就像花括号或关键字在其他编程语言中很重要一样。

count = 0
finished = False
total = 0
while not finished:
    number = int(input("Enter a number(0 to finish)"))
    if number == 0:
        finished = True
    else:
        total = total + number
        count = count + 1
print("the average is", total/ count)
count = 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2020-12-16
    • 2014-02-08
    • 2019-05-12
    相关资源
    最近更新 更多