Python初学者,在将代码添加用文件打开的功能时卡住了
"""
Update your program so that it prints (writes) the output to a file.
How do we do this?
• First you need to open the file for writing. You only need to do this once, so add this line before
your loop starts:
out_file = open(OUTPUT_FILE, 'w')
Note that this code line expects you to define the constant OUTPUT_FILE, so do that above.
• Update any print statements, so they output to the file.
Here’s an (incomplete) example:
print("${:,.2f}".format(price), file=out_file)
• Close the file at the very end:
out_file.close()
• This version uses the .format() method when printing the price. Change this to use f-string
formatting (keet the same output).
"""
import random
MAX_INCREASE = 0.1 # 10%
MAX_DECREASE = 0.05 # 5%
MIN_PRICE = 0.01
MAX_PRICE = 1000.0
INITIAL_PRICE = 10.0
day = 1
print("On day {} price is:".format(day),end="")
price = INITIAL_PRICE
print("${:,.2f}".format(price))
while price >= MIN_PRICE and price <= MAX_PRICE:
price_change = 0
# generate a random integer of 1 or 2
# if it's 1, the price increases, otherwise it decreases
if random.randint(1, 2) == 1:
# generate a random floating-point number
# between 0 and MAX_INCREASE
price_change = random.uniform(0, MAX_INCREASE)
day+=1
print("On day {} price is:".format(day), end="")
else:
# generate a random floating-point number
# between negative MAX_DECREASE and 0
price_change = random.uniform(-MAX_DECREASE, 0)
day+=1
print("On day {} price is:".format(day), end="")
price *= (1 + price_change)
print("${:,.2f}".format(price))
上面代码顶部是给的实现用文件打开功能要求,在这部分我卡住了,麻烦看一下,给一个修改后的代码,如果有注释就更好啦,谢谢