如何在Python中的ifstatement内部运行函数

2024-09-02 05:00:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将输入中的变量信息添加到文本文档中。文件在应该放的地方。到目前为止我有这个代码:

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)

Tags: ofnametxtaddnewtimedefmusic
3条回答

你为什么要用func?在

我不认为这是必要的。在

如果我是你,我会在全球范围内打开文件。在

资料来源:

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..."))

f =open("music.txt", "a") 
if how_often == 1:
    f.write("1 Hour")
elif how_often == 2:
    f.write("2 Hours")
elif how_often == 3:
    f.write("3 - 4 Hours")
else:
    f.write("Most of the day")

如果我不明白,告诉我。在

你很接近了!您不需要在if语句中进行任何int到string的转换。以下方法可以很好地工作:

if how_often == 1:
    add_file_1(new_1)
elif how_often == 2:
    add_file_2(new_2)
elif how_often == 3:
    add_file_3(new_3)
else:
    add_file_4(new_4)

作为Brad Solomon mentioned,它不能工作的原因是因为how_often是一个int,但是你将它与一个字符串进行比较,它们是不相等的。在

请访问https://repl.it/repls/ScaredGhostwhiteRegister以查看此密码子的操作。虽然函数不会实际加载,但您可以根据您提供的输入查看它试图调用哪个函数。在

你可以用字典简化听力时间选项。打开文件的好方法是使用'with'块。在

print("Please, choose from one of the following: ")

listening_times = {1:"One hour a day", 
                   2:"About two hours per day", 
                   3:"Three to four hours per day", 
                   4:"Most of the day"}

for k in listening_times:
    print "    %d - %s" % (k, listening_times[k])

how_often = int(input("I find myself listening to music..."))

with open("music.txt", 'a') as f:
    f.write(listening_times[how_often])

相关问题 更多 >