我是编码新手,正在尝试弄清楚如何以 p 的步骤生成从 n 到 m 的序列,其中 n、m 和 p 由用户输入。到目前为止我已经写了一些代码,但我不知道如何继续。这是我所拥有的:
# Getting user inputs
n = int(input("Enter the start value (n): "))
m = int(input("Enter the end value (m): "))
p = int(input("Enter the step value (p): "))
# I want to create a sequence from n to m in steps of p
# Not sure how to proceed
我知道我需要使用循环来生成序列,但我不确定如何正确实现它。我研究过 range() 函数,但我不确定如何在这种情况下应用它。 我对 Python 和一般编程很陌生。 我正在使用Python 3。 谁能帮助我了解如何实现这一目标?任何指导或代码示例将不胜感激!
以下是您正在寻找的。
https://docs.python.org/3/tutorial/controlflow.html#for-statements https://docs.python.org/3/library/stdtypes.html#range
现在,您尝试编写的代码片段如下所示:
n = int(input("First Number: "))
m = int(input("Second Number: "))
p = int(input("Third Number: "))
# Start from n, go until m (includes m), in steps of p
for i in range(n, m + 1, p):
print(i, end = " ")
print()