首页 > 解决方案 > 如何在 Python 中的 if 语句中运行函数

问题描述

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

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)

标签: python

解决方案


你很近!您不需要在 if 语句中进行任何整数到字符串的转换。以下将正常工作:

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 所提到的,它不起作用的原因是因为how_often它是一个 int,但是你将它与一个字符串进行比较,它们并不相等。

访问https://repl.it/repls/ScaredGhostwhiteRegister以查看此编码操作。虽然该函数实际上不会加载,但您可以根据您提供的输入查看它尝试调用的函数。


推荐阅读