-1

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".

colidyre
  • 4,170
  • 12
  • 37
  • 53

1 Answers1

4

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"]:
Melebius
  • 6,183
  • 4
  • 39
  • 52
krish
  • 166
  • 5