[英]What is wrong with this code? I cant figure it out
這段代碼有什么問題? 我試過運行它,但一直給我錯誤,我無法弄清楚。
def main():
# Variables
total_sales = 0.0
# Initialize lists
daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
days_of_week = ['Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday' 'Friday',
'Saturday']
for i in range(7):
daily_sales[i] = float(input('Enter the sales for ' \
+ days_of_week[i] + ': '))
for number in daily_sales:
total_sales += number
# Display total sales
print ('Total sales for the week: $', \
format(total_sales, ',.2f'), sep='')
# Call the main function.
main()
days_of_week = ['Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday',
'Saturday']
你忘記了,
在“星期四”之后,這就是為什么它會超出范圍。
你的代碼:
def main():
# Variables
total_sales = 0.0
# Initialize lists
daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
days_of_week = ['Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday',
'Saturday']
for i in range(7):
daily_sales[i] = float(input('Enter the sales for ' \
+ days_of_week[i] + ': '))
for number in daily_sales:
total_sales += number
# Display total sales
print('Total sales for the week: ${:.2f}'.format(total_sales))
# Call the main function.
main()
也許我們可以稍微改進一下這段代碼:
def main():
# Initialize lists
daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
days_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday']
# Use `enumerate` to get the item directly.
for index, day in enumerate(days_of_week):
daily_sales[index] = float(
input('Enter the sales for {0}: '.format(day)))
# Use the built-in `sum` to sum the sales.
total_sales = sum(daily_sales)
# Display total sales
print('Total sales for the week: ${:.2f}'.format(total_sales))
# Call the main function.
main()
把它扔進我的編輯器時,我發現了一些縮進錯誤。 修復它並添加,
在'Thursday'
之后@lord63。 j 發現,您需要清理並修復main()
最終print
語句。 試試下面的代碼,因為它對我來說效果很好,現在:
def main():
# Variables
total_sales = 0.0
# Initialize lists
daily_sales = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
days_of_week = ['Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday',
'Saturday']
for i in range(7):
daily_sales[i] = float(input('Enter the sales for '+ \
days_of_week[i] + ': '))
for number in daily_sales:
total_sales += number
# Display total sales
print ('Total sales for the week: $' \
+ format(total_sales, '.2f'))
# Call the main function.
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.