Python: 简化计数程序

Python: Simplify a Counting Program

我是 Python 的新手,我制作了一个程序,要求用户输入 select 2 个号码。第一个必须在 1 到 10 之间,第二个必须在 100 到 200 之间。程序然后要求用户 select 1 到 5 之间的第三个数字。分别将这三个数字称为 X、Y 和 Z然后程序以 Z 为步长从 X 数到 Y。

预期行为:如果用户选择 10、105 和 5,那么 Python 应该打印 15、20、25 等等,直到 105。此外,如果用户尝试输入值超出程序指定的值,它将拒绝输入并要求用户重试。

该程序有效,但正如我所说,我对 Python 还很陌生,所以如果我以最佳方式完成它,我会感到非常惊讶。您认为有什么方法可以简化下面的代码以提高效率吗?

代码如下:

x = int(input("Please enter any number between 1 and 10: ").strip())

while x > 10 or x < 1:
    print("No!  I need a number between 1 and 10.")
    x = int(input("Please enter any number between 1 and 10: ").strip())

y = int(input("Now enter a second number between 100 and 200: ").strip())

while y > 200 or y < 100:
    print("No!  I need a number between 100 and 200.")
    y = int(input("Please enter any number between 100 and 200: ").strip())

print("Now we're going to count up from the first to the second number.")
print("You can count every number, every second number, and so on. It's up to you.")
z = int(input("Enter a number between 1 and 5: ").strip())

while z > 5 or z < 1:
    print("No.  I need a number between 1 and 5!")
    z = int(input("Enter a number between 1 and 5: ").strip())

print("You have chosen to count from {} to {} in steps of {}.".format(x, y, z))

input("\nPress Enter to begin")

for q in range(x,y):
    if q == x + z:
    print(q)
    x = x + z

该程序有效,但我的直觉告诉我必须有更简洁的方法来执行此操作。如果您有任何建议,我们将不胜感激。

干杯!

您可以将循环替换为:

for q in range(x,y,z):
    print(q)

将第三个参数添加到范围表达式会使其按步数递增。

好的,我喜欢压缩代码,我喜欢挑战,

巴姆 代码:

x, y, z = None, None, None
while x == None or x > 10 or x < 1: x = int(input("Please enter any number between 1 and 10: "))
while y == None or y > 200 or y < 100: y = int(input("Please enter any number between 100 and 200: "))
print("Now we're going to count up from the first to the second number."+'\n'+"You can count every number, every second number, and so on. It's up to you.")
while z == None or z > 5 or z < 1: z = int(input("Enter a number between 1 and 5: "))
tmp=raw_input(str("You have chosen to count from {} to {} in steps of {}.".format(x, y, z))+'\n'+"Press Enter to begin")
x = x-1
for q in range(x,y,z): print(q)
print x+z

尽可能紧凑。