【发布时间】:2018-07-24 14:27:59
【问题描述】:
我正在尝试编写一个程序,如果用户按 1,它会读取文件,如果是 2,它会写入文件,如果是 3,它会擦除文件。不幸的是,代码在用户第一次输入后停止工作。是否可以为此编写一个函数?
while True:
print("(1) Read the notebook")
print("(2) Add note")
print("(3) Empty the notebook")
print("(4) Quit")
user_input = input("Please select one: ")
if user_input == 1:
readfile = open("notebook.txt","r")
content = readfile.read()
print(content)
readfile.close()
elif user_input == 2:
new_input = input("Write a new note: ")
readfile = open("notebook.txt", "a")
readfile.write(new_input)
readfile.close()
elif user_input == 3:
readfile = open("notebook.txt", "w")
readfile.close()
elif user_input == 4:
break
print("Notebook shutting down, thank you.")
【问题讨论】:
-
“很遗憾,代码不能按我的预期工作。”为什么不?什么坏了?
-
它在什么方面没有按预期工作?
-
在python 3中,输入返回一个字符串而不是一个整数
-
input总是返回一个字符串。您需要将其转换为int或检查字符串值,例如if user_input == '1': -
@Tgsmith61591 代码没有执行 if 部分。