python - 如何在 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)
解决方案
你很近!您不需要在 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以查看此编码操作。虽然该函数实际上不会加载,但您可以根据您提供的输入查看它尝试调用的函数。
推荐阅读
- ios - iOS 权限描述限制
- powershell - 将 PSCustomObject 添加到数组会产生错误,但在 Powershell 中调试代码时工作正常
- reactjs - 当我通过真实性测试时,ReactJS 给了我无法访问的代码
- c++ - 关于:C++ 中异常对象的范围:为什么我没有得到副本?
- python - eq函数python的对面/选择列中具有两个以上相同条目的行
- date - 如何将包含月份和年份的日文日期拆分为日期格式
- html - 如果用户一直按下按钮(查看更多),多次没有结果
- java - 获取与 chrome 浏览器兼容的 chrome 驱动程序版本
- logstash - Logstash 替换过滤器上的所有 json 键
- delphi - 有没有办法在运行时调用 StringGrid OnCellDraw