首先,我要解釋一下你的代碼做,然後,什麼樣的代碼會做你想要什麼。
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_start
取amount_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
不要猶豫,問你是否有關於我的回答任何問題。我希望這有助於。
非常感謝您對此的清晰和準確的解釋。這對我幫助很大。 –