【问题标题】:Proper Syntax for a for-loop?for循环的正确语法?
【发布时间】:2020-10-07 18:42:30
【问题描述】:

这是我的代码

days = 10
total = 0

for currentday in range(1, days +1):
 > bugs = int(input("how many bugs were collected on day"+ str(currentday),": ")
 > total += bugs
print("The total number of bugs caught by the end of all",days,"days was",total)

我在第 6 行或“total += bugs”所在的位置不断遇到语法错误。 我什至无法确定错误是什么,所以我需要帮助找出问题所在

【问题讨论】:

  • > 是您代码的一部分吗?如果是这样,那就是你的问题
  • 代码中的> 无济于事。
  • 您没有关闭第 5 行中的输入括号,您还使用了, 而不是+。应该是bugs = int(input("how many bugs were collected on day"+ str(currentday) + ": "))
  • 插入 > 是为了在此处标记块,并不是我实际代码的一部分。下次我会省略它们。

标签: python loops for-loop syntax


【解决方案1】:
days = 10
total = 0

for currentday in range(1, days +1):
    bugs = int(input(f"how many bugs were collected on day {currentday}: "))
    total += bugs
print("The total number of bugs caught by the end of all",days,"days was",total)

A:您在第 6 行末尾缺少一个括号“)”。

B:您不能将这样的变量放入输入中,请使用如上所示的格式化选项

【讨论】:

    【解决方案2】:

    “>”没有帮助,但可能是在您复制粘贴代码时添加的。主要问题只是上面一行被遗忘的括号。它在应该结束 ": ")) 时结束 ": ")

    此外,你不能只用逗号来添加字符串和整数来组成字符串。您必须先将整数变量days 和total 转换为字符串。

    这是您解决了错误的代码:

    days = 10
    total = 0
    
    for currentday in range(1, days + 1):
        bugs = int(input("how many bugs were collected on day" + str(currentday) + ": "))
        total += bugs
    
    print("The total number of bugs caught by the end of all ", str(days), " days was ", str(total))
    
    

    【讨论】:

    • print 调用中的逗号很好。 print 接受多个参数并将它们全部打印出来,它们之间有一个分隔符,分隔符默认为一个空格。 input 调用中的逗号不没问题。
    • @user2357112supportsMonica 感谢您的澄清!我将立即编辑我的答案。我不知道 print 可以这样使用。
    • 我将 > 用于标记块,因为我认为这是网站告诉我的,以使其更易于阅读。下次我会删除它们。另外,我之前使用逗号将整数插入字符串。
    猜你喜欢
    • 2012-03-29
    • 1970-01-01
    • 2015-04-21
    • 2015-07-10
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多