如果 N 是正数,则输出从 N 到 0 之间的所有值,不包括 0。如果 N 是负数,则输出从 N 到 0 之间的每个值,不包括 0。

2024-04-26 23:34:13 发布

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

正如我之前所说的,我是一个初学者,试图在大学课程中学习Python,但是他们教给我们的东西并不总是适用于现实世界,当我试图研究解决方案时,没有什么可以找到的。总之,我最近的问题是:

This is a tricky challenge for you.

We will pass in a value N. N can be positive or negative.

If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.

and the starting code is:

# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = 0
while counter <= N:
print(counter)
counter = counter + 1
elif counter >= N:
print(N+counter)
counter = counter - 1

My solution produced an error:

SyntaxError: unexpected EOF while parsing
There is an error is your program.

老实说,我不知道从哪里开始,因为我们的教科书没有涵盖这些挑战。提前感谢您在这件事上提供的任何帮助。顺便说一句,我的代码是在Codio中输入的,必须传入Codio的IDE。在


Tags: andthetofromoutputifisvalue
2条回答

这里的主要问题是你有一段时间和一个elif。Elif与其他if语句一起使用。
例如:

if condition:
    do something
elif condtion:
    do something else
else:
    do something as a "last resort"

我想你是想这么做:

^{pr2}$

最后几件事:

  • 如果您想了解什么是“真实世界”编程,那么我建议您查看一些在线资源,例如https://www.codecademy.com/或查看文档。在
  • 当发布堆栈溢出时,请详细解释您的问题
  • 在堆栈溢出时输入代码时,请确保其格式正确(例如缩进),因为这样可以使解码更大的程序更容易。在
  • 堆栈溢出不是一个“为我做作业”的网站
# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
if N > 0:
    for x in range(N, 0, -1):
        print x
if N < 0:
    for x in range(N, 0):
        print x

While循环版本

^{pr2}$

相关问题 更多 >