这段代码有什么问题?我试图运行它,但一直给我错误,我无法弄明白。
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()
答案 0 :(得分:0)
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()
答案 1 :(得分:0)
我把它扔进编辑器时发现了一些缩进错误。修复后,在{lord63 ,
之后添加'Thursday'
。 j发现,您需要清理并修复print
中的最终main()
声明。请尝试下面的代码,因为它现在对我很有用:
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()