【问题标题】:Why doesn't my code on Jupyter produce an output为什么我在 Jupyter 上的代码不产生输出
【发布时间】:2018-05-17 09:07:55
【问题描述】:
given_list = [7, 5, 4, 4, 3, 1, -2, -3, -5, -7]

total = 0 
i = 0
while i < len(given_list) and given_list[i] <= 0: 
    total += given_list[i]
    i += 1
    print(total)

我正在使用 Jupyter 笔记本并按照 youtube 上 CSdojo 的 Python 教程进行操作。我想知道为什么当我运行我的代码时,它之后的单元格没有产生输出(总计)?

【问题讨论】:

  • given_list[i] where i is 0 解析为 7 这意味着您的 while 循环甚至没有启动,因为条件之一是 given_list[i] &lt;= 0。显然,7 不小于或等于零。
  • 这是一种非常尴尬的实现方式。考虑sum(n for n in given_list if n &lt;= 0)
  • @DeepSpace sum(n for n in given_list if n &lt; 0) 更短更快:)
  • @Jean-FrançoisFabre 该死:D
  • @DeepSpace "nitpick" 是我的中间名 :)

标签: python jupyter


【解决方案1】:

问题是given_list[i] &lt;= 0

首先是i = 0,然后是given_list[i] = 7

7 不等于或小于 0,则 True and False 的计算结果为 False。这就是它不显示输出的原因。
在这种情况下,您对 Jupyter 或 Python 没有任何问题。你的问题是你的逻辑。请在算法而不是语法上努力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多