Python:简化计数程序

时间:2017-03-21 21:30:13

标签: python loops counting simplification

我对Python非常陌生,我制作了一个程序,要求用户选择2个数字。第一个必须介于1和10之间,第二个必须介于100和200之间。程序然后要求用户选择介于1和5之间的第3个数字。分别调用这3个数字X,Y和Z然后程序从X到Y的步长为Z.

预期行为:如果用户选择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

该计划有效,但我的直觉告诉我必须有一个更清洁的方法来做到这一点。您可能会获得任何建议。

干杯!

2 个答案:

答案 0 :(得分:1)

您可以用以下代码替换循环:

Set.empty[Relation] ++ viewRelations ++ indirectRelations

将第三个参数添加到范围表达式会导致它逐步计数。

答案 1 :(得分:0)

好吧,我喜欢压缩代码,我喜欢挑战sooooooooo,

BAM 代码:

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

尽可能紧凑。