英文:
Why does my code do stuff i dont tell it to do?
问题
I'm new to coding so I don't get why my code isn't functioning. I want to have the variable com
with input()
as a line to write commands in and if the command is for example "delete file", I ask for a file name and it should delete the file. But if I type "delete file" it just shows me this:
Command: delete file
File Name: tester.txt
Contents:
testfile 123 test
File name:
It just shows the contents of the file instead of deleting it. It should only read the contents if com
is "open file". I hope you get my problem.
Thats the code:
com = input("Command: ")
if com == "open file" or com == "openfile":
file = input("File Name: ")
f = open(file, "r")
print("Contents: ")
print(f.read())
if com == "delete file" or com == "deletefile":
filefordelete = input("File name: ")
if os.path.exists(filefordelete):
os.remove(filefordelete)
else:
print("File does not exist!")
input("Press enter to stop the program")
I want to delete the file when I type into the variable com
"delete file". I cant find a solution why it's doing the stuff it should do when the variable com
is "open file".
英文:
I'm new to coding so I don't get why my code isn't functioning. I want to have the variable com
with input()
as a line to write commands in and if the command is for example "delete file", I ask for a file name and it should delete the file. But if I type "delete file" it just shows me this:
Command: delete file
File Name: tester.txt
Contents:
testfile 123 test
File name:
It just shows the contents of the file instead of deleting it. It should only read the contents if com is "open file". I hope you get my problem.
Thats the code:
com = input("Command: ")
if com == "open file" or "openfile":
file = input("File Name: ")
f = open(file, "r")
print("Contents: ")
print(f.read())
if com == "delete file" or "deletefile":
filefordelete = input("File name: ")
if os.path.exists(filefordelete):
os.remove(filefordelete)
else:
print("File does not exist!")
input("Press enter to stop the program")
I want to delete the file when I type into the variable com "delete file". I cant find a solution why it's doing the stuff it should do when the variable com is "open file".
答案1
得分: 4
if com == "open file" or "openfile":
评估为
if False or "openfile"
"openfile" 在 if
语句中评估为 True
值。
由于这是一个 or
条件 - False or True
评估为 True
,因此你的第一个 if
语句为 True
,并且执行相应的代码块。
你需要将你的条件重写为以下之一:
if com == "open file" or com == "openfile":
或者
if com in ["open file", "openfile"]:
英文:
if com == "open file" or "openfile":
evaluates to
if False or "openfile"
"openfile"
evaluates to True
value in the if
statement.
And now since it’s an or
condition - False or True
evaluates to True
, therefore your first if
statement is True
and the block is executed.
You will need to rewrite your condition like this:
if com == "open file" or com == "openfile":
or
if com in ["open file", "openfile"]:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论