2017-03-21 57 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等,所以我固定 –