语法错误:Python“for”循环中缺少的是范围

2024-10-01 22:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我应该做什么,但我相信我在这里错过了一步。。。我之前从第1行得到一个语法错误

range(1, 51)

For answer in range:
   if answer % 3 == 0 and answer % 5 ==0
    print (“Wolly Bully”)
elseif answer % 3 == 0 and answer % 5 = <0
        print (“Wolly”)
elseif answer % 3 = <0 and answer % 5 == 0
    print (“Bully”)
elseif answer % 3 = <0 and answer % 5 = <0
    print (str(answer) + " ", end = "")

Tags: andanswerinforifrangeendprint
2条回答

您可以使用range(1, 51)定义一个范围,但是range是一个函数,因此您需要对它返回的范围做一些处理

例如:

my_range = range(1, 51)
for answer in my_range:
    ...

而且,因为您不需要任何其他方面的范围,这是一个更好的解决方案:

for answer in range(1, 51):
    ...

您的代码还有一些问题,其中许多是打字错误-这里有一个更正的版本(不保证正常工作,但它可以运行):

for answer in range(1, 51):
    if answer % 3 == 0 and answer % 5 == 0:
        print("Wolly Bully")
    elif answer % 3 == 0 and answer % 5 < 0:
        print("Wolly")
    elif answer % 3 < 0 and answer % 5 == 0:
        print("Bully")
    elif answer % 3 < 0 and answer % 5 < 0:
        print(str(answer) + " ", end = "")

有几种类型的更改:

  • elif而不是elseif
  • ifelif后面的冒号
  • 正确压痕
  • <=而不是= <
  • 正确引用
  • 没有资本化for
  • 函数(print)与其参数列表之间的空格
  • 相互排斥的ifelif表达式(如果某个表达式不满足if x == y,那么elif x <= y就没有意义了,编写elif x < y就更清楚了,因为这是执行代码的唯一情况

考虑到大写和奇怪的引号,您可能正在使用不合适的编辑器来编写代码-强烈建议使用编程编辑器或IDE,如VSCode(免费)、PyCharm(免费社区)或许多其他(也免费)替代品

有几个错误,将rangefor一起使用,在Python中是elif,大多数比较运算符需要更正(<=而不是=>):

for answer in range(1, 51):
    if answer % 3 == 0 and answer % 5 == 0:
        print("Wolly Bully")
    elif answer % 3 == 0 and answer % 5 <= 0:
        print("Wolly")
    elif answer % 3 <= 0 and answer % 5 == 0:
        print("Bully")
    elif answer % 3 <= 0 and answer % 5 <= 0:
        print(str(answer) + " ", end="")

输出:

Wolly Bully
Wolly Bully
Wolly Bully

相关问题 更多 >

    热门问题