简体   繁体   中英

I have syntax error on my code and I don't know what the problem is?

Q: "Ask the user how many numbers they want to enter. Let them enter this many numbers and write them to a text file. Each number must be on a separate line." I don't know what the error is

user = int(input("how many numbers to enter"))
file = open("file1.txt" , "a")
for x in range(user):
    number = input("Enter number" + str(user + 1) + "\n")
    file.writelines(user+"\n")  
file.close()

I believe that you are using your user variable instead of your x variable. The fixed code:

user = int(input("how many numbers to enter"))
with open("file1.txt" , "a") as file:
    for x in range(user):
        number = input("Enter number " + str(x + 1) + "\n")
        file.writelines(user + "\n")  

By reading the exercise order, I see you were close to the answer and assumed this is what you wanted.

user = int(input("How many numbers you want to enter?\n"))
file = open("file1.txt", "w")
for x in range(user):
    number = input("Enter number " + str(x + 1) + ":\n")
    file.writelines(str(x) + "\n")
file.close()

You forgot to add the user variable and on row

file.writelines(user+"\n")  

you forgot to convert the int to a string.

file.writelines(str(user)+"\n")

note your code is just going to write the user number "user" times.

Here is the edited code that works for me:

user = 5 #number of users
file = open("file1.txt" , "a")
for x in range(user): #loop every user
    number = input("Enter number" + str(x + 1) + "\n") #Use "str()"" to convert number, called int, to a string 
    file.writelines(str(user) + "\n") 
file.close()

Even though your question was not clear to me, I presume this is what you expect.

user_input = int(input("how many numbers to enter:"))
with open("file1.txt" , "w") as output_file:
    for x in range(user_input):
        number = input("Enter number" + f'{x + 1}:' + "\n")
        print(number, file=output_file)

since print function itself does line carriage, you can omit adding new line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM