我试图将输入中的变量信息添加到文本文档中。文件在应该放的地方。到目前为止我有这个代码:
import time
import os
print("Welcome!")
name = input("Please enter your name: ")
print("Hello",name, "! I am going to guess your most favorite type of music.")
time.sleep(2)
print("Please, choose from one of the following: ")
listening_time = ["1 - One hour a day", "2 - About two hours per day", "3 - three to four hours per day", "4 - Most of the day"]
print(listening_time)
how_often = int(input("I find myself listening to music..."))
def add_file_1(new_1):
f = open("music.txt", "a")
f.write("1 Hour")
def add_file_2(new_2):
f = open("music.txt", "a")
f.write("2 Hours")
def add_file_3(new_3):
f = open("music.txt", "a")
f.write("3 - 4 Hours")
def add_file_4(new_4):
f = open("music.txt", "a")
f.write("Most of the day")
if how_often == str('1'):
add_file_1(new_1)
elif how_often == str('2'):
add_file_2(new_2)
elif how_often == str('3'):
add_file_3(new_3)
else:
add_file_4(new_4)
你为什么要用func?在
我不认为这是必要的。在
如果我是你,我会在全球范围内打开文件。在
资料来源:
如果我不明白,告诉我。在
你很接近了!您不需要在if语句中进行任何int到string的转换。以下方法可以很好地工作:
作为Brad Solomon mentioned,它不能工作的原因是因为
how_often
是一个int,但是你将它与一个字符串进行比较,它们是不相等的。在请访问https://repl.it/repls/ScaredGhostwhiteRegister以查看此密码子的操作。虽然函数不会实际加载,但您可以根据您提供的输入查看它试图调用哪个函数。在
你可以用字典简化听力时间选项。打开文件的好方法是使用'with'块。在
相关问题 更多 >
编程相关推荐