Reputation:
Python Challenge 25
Write a sign-up program for an after-school club; it should ask the user for the following details and store them in a file:
For the above task I wrote the following python code:
# Python Challenge 25
print ("Hello user, this is a virtual application form"
"\nfor joining after-school clubs at -Insert school name here-")
first_name = input("\n\nPlease input your first name:")
last_name = input("Please input your last name:")
gender = input("Please input your gender:")
form = input("Please input your form name:")
club = input("What after-school club would you like to attend?\n")
file = open("application-form.txt", "w")
file.write(first_name)
file.write (last_name)
file.write (gender)
file.write (form)
file.write (club)
file.close()
print (first_name, "Thank you for taking your time to fill this virtual form"
"\nall the information has been stored in a file to maintain confidentiality")
An example of the outcome of the above code:
My question
When the text file is saved all the user inputs is stored in one line, is there a way where I can put each input on a separate line?
Is there a more efficient way to write the above code?
Upvotes: 0
Views: 1351
Reputation: 303
As for making the code more efficient/neater, you could use a function to request and store the data:
def get_info(prompts):
file = open("application-form.txt", "w")
for prompt in prompts:
file.write(input(prompt))
file.write('\n')
print ("Hello user, this is a virtual application form"
"\nfor joining after-school clubs at -Insert school name here-")
prompts = ["\n\nPlease input your first name:",
"Please input your last name:",
"Please input your gender:",
"Please input your form name:",
"What after-school club would you like to attend?\n"]
get_info(prompts)
print ("Thank you for taking your time to fill this virtual form"
"\nall the information has been stored in a file to maintain confidentiality")
Unfortunately to do this I had to take out the first_name
call in the thank you (last print statement). If you absolutely need that you're probably better off with what you have so far.
Upvotes: 0
Reputation: 8184
Contrary to print
, write
doesn't automatically append end of lines. You can add file.write("\n")
between your writes to intercalate ends of line.
Alternatively, you can create a single string interspersing the end of lines, using join
, and write that single string.
Example:
file.write("\n".join([line1, line2, line3]))
Upvotes: 1
Reputation: 36013
1) Replace file.write(first_name)
with file.write(first_name + '\n')
or add the line file.write('\n')
just after.
2) I don't think the code can be made to run faster, and I don't think it needs to, but in terms of code quality/length I would write the file writing section like this:
with open("application-form.txt", "w") as f:
for item in [first_name, last_name, gender, form, club]:
f.write(first_name + '\n)
Upvotes: 1