python - 如何在 Python 中的 if 语句内运行函数

标签 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)

最佳答案

你已经很接近了!您不需要在 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 mentioned ,它不起作用的原因是因为 how_often 是一个 int,但您将它与一个字符串进行比较,并且它们不相等。

访问https://repl.it/repls/ScaredGhostwhiteRegister看看这个 codin 的 Action 。虽然该函数实际上不会加载,但您可以根据您提供的输入查看它正在尝试调用哪个函数。

关于python - 如何在 Python 中的 if 语句内运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275717/

相关文章:

Python 在 IDLE 中播放声音,但在 Thonny 中给出 "no module called gi"错误; Ubuntu 终端中的混合结果

python - 如何在Python中正确注释函数

python - 模板 - 菜单

python - 如何在同一字符串python上用不同的输入替换多个字符

python - 快速有效地减去数组的方法

python - 避免绘制数组不同轴的冗余代码

python - 当鼠标悬停在窗口上时在 Tkinter 中显示按钮

python - email.header.decode_headers() 抛出 HeaderParseError

python - 如何在开发服务器(Google App Engine)中使用生产 BlobStore

python - 使用 strptime() 的 2 位数年份不能很好地解析生日