2017-03-21 66 views
1

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

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

程序工作,但我的直觉告诉我,必须有这样做一个更清洁的方式。你可能会有任何建议将大量赞赏。

干杯!

+1

你想评论的工作代码一般属于[代码评论](http://codereview.stackexchange.com/) – TemporalWolf

+0

@TemporalWolf,所以我不必评论完全:)此外,代码和问题似乎以适应CR:甚至会在那里获得upvotes。投票结束。 –

+2

我投票结束这个问题作为题外话,因为它是一个完美的适合http://codereview.stackexchange.com –

回答

1

您可以替换循环:

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

添加第三个参数的范围内表达使其逐步计数。

0

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

BAM CODE:

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 

紧凑,我能做到。

+0

以前的代码没有打印100上计数1-100 5。 也,它从一开始,并计数6,11,16等,所以我固定 –