2017-09-26 68 views
0

先進的道歉,我對Python很陌生。但是,我需要創建一個計算程序,計算一個人在一段時間內可以賺取的金額,如果他的第一天爲1美分,第二天爲2美分,並且每天持續增加一倍。我知道我應該使用&而循環,我只是不完全知道如何執行它。Python 3 For/While Loops

到目前爲止,我有這樣的:

day = int(input('How many days did you work?: ')) 
start = 1 
end = day 
amount_start = 0.01 

print() 
print('Day  Amount ($)') 
print('---  ----------') 

for day in range(start, end + 1): 
    amount_end = amount_start * 2 
    for amount_start in (amount_start, amount_end): 
     print(day, amount_end, sep='   ') 

當我跑了,我看到第1天起數爲0.02,並複製到每個行兩次。任何建議要改變/添加,所以我可以理解這將不勝感激。 謝謝。

回答

0

首先,我要解釋一下你的代碼做,然後,什麼樣的代碼會做你想要什麼。

day = int(input('How many days did you work?: ')) 
start = 1 
end = day 
amount = 0.01 # Start and End shouldn't be a thing 
total = 0 # I think this is what you wanted... the amount will double every time and the total will be increased by the amount every time 

print() 
print('Day  Amount ($)') 
print('---  ----------') 

初始化那裏,沒有錯。現在,我們來看看兩個for循環。

for day in range(start, end + 1): 
    amount_end = amount_start * 2 
    for amount_start in (amount_start, amount_end): 
     print(day, amount_end, sep='   ') 

首先,我會建議不要照顧變量的名稱。變量day之前已經定義過,但由於它不再用於原來的目的,所以在這裏並不重要。

外循環將循環您輸入的次數。這裏也沒有錯。
然後,我們將amount_end的值設置爲amount_start的當前值的兩倍。

現在,讓我們來看看內部循環。這裏,amount_start的值將通過列表(amount_start, amount_end)
我們將在此循環中循環兩次,首先用amount_start保持其初始值,然後用amount_startamount_end的值。
這個循環將是相同

amount_start = amount_start 
print(day, amount_end, sep='   ') 
amount_start = amount_end 
print(day, amount_end, sep='   ') 

然後你可以看到爲什麼它打印在同一行兩次。

爲了消除重複,使代碼更易讀,我建議下面的代碼:

day = int(input('How many days did you work?: ')) 
start = 1 
end = day 
amount_start = 0.01 

print() 
print('Day  Amount ($)') 
print('---  ----------') 

for day in range(start, end + 1): 
    amount_end = amount_start * 2 
    print(day, amount_end, sep='   ') 
    amount_start = amount_end 

不要猶豫,問你是否有關於我的回答任何問題。我希望這有助於。

+0

非常感謝您對此的清晰和準確的解釋。這對我幫助很大。 –

1

不要窩在for循環

您應該只有一個for循環:

day = int(input('How many days did you work?: ')) 
start = 1 
end = day 
amount = 0.01 # Start and End shouldn't be a thing 
total = 0 # I think this is what you wanted... the amount will double every time and the total will be increased by the amount every time 

print() 
print('Day  Amount ($)') 
print('---  ----------') 

for day in range(start, end + 1): 
    total += amount # Give the person salary 
    print(day, total, sep='   ') # Print the total amount of money earned 
    amount *= 2 # Double the salary 
+0

非常感謝! –