-3

i am trying to write a program that if a user press 1, it reads the file, if 2, it write to the file and if 3, it erase the file. Unfortunately, the code stop working after the first input from user. Is it possible to write a function for that?

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.")
superv
  • 45
  • 1
  • 8

2 Answers2

0

Python3 does not have separate raw_input() and input() functions for returning ints and strings. It only has input(), which returns a string. You are attempting to compare the output of input() (a string) to an int, for example on this line:

if user_input == 1:

The solution is to use the int() function to get the types right, i.e.

if int(user_input) == 1:

More reading

Source 1

Source 2

Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
  • Thanks. I did use use int() earlier but the code didn't run at all. I will try that and see. – superv Jul 24 '18 at 14:50
  • 1
    @superv could you please update your original question with what you mean by "not run at all"? – Joseph Farah Jul 24 '18 at 14:55
  • Thanks guys. I saw i did not add a line of code earlier on. i have done that and also add the int() conversion. The code seems to work but with few errors which i cant seems to find. here is the code: – superv Jul 24 '18 at 15:04
0

The problem is that your user input should be an int. Use this instead :=>"user_input = int(input("Please select one: "))" And also you cannot write an integer to a file so use this: => "readfile.write("user_input")" or convert your user input to string before writing to the file.