Reputation: 54
I wrote this python script to find the passing grades, failing grades and the average grades of a student and write them on a .txt file but I'm having trouble with the script not working as expected.
Here's the part of code responsible for creating the file and writing the data:
avg_f = print('Student: {:10s} Passing grades: {:<10d} Failing grades: {:<10d} Average: {:3.2f}'.format(student_name + " " + student_surname, p_g, f_g, avg))
u_ch = input("Do you want to save? Y/N: ")
while str.isalpha(u_ch) == False:
u_ch = input("You can't insert numbers or special characters.\nDo you want to save? Y/N: ")
while u_ch.lower() != "y" and u_ch.lower() != "n":
u_ch = input("Invalid input. Y/N: ")
if u_ch.lower() == "n":
print("Arresting the script...")
exit()
else:
print()
barr()
file = open("Students.txt", "a")
file.writelines(str(avg_f))
print("The file was successfully saved.")
file.close()
When I run the script, it generates a .txt file but inside the file, it keeps writing "None" instead of the student information. How can I fix this?
It's probably a stupid question but I'm new to coding.
Upvotes: 1
Views: 67
Reputation: 2167
your first line is broken. function print does not return text that prints. See code
avg_f = 'Student: {:10s} Passing grades: {:<10d} Failing grades: {:<10d} Average: {:3.2f}'.format(student_name + " " + student_surname, p_g, f_g, avg)
print(avg_f)
u_ch = input("Do you want to save? Y/N: ")
while str.isalpha(u_ch) == False:
u_ch = input("You can't insert numbers or special characters.\nDo you want to save? Y/N: ")
while u_ch.lower() != "y" and u_ch.lower() != "n":
u_ch = input("Invalid input. Y/N: ")
if u_ch.lower() == "n":
print("Arresting the script...")
exit()
else:
print()
barr()
file = open("Students.txt", "a")
file.writelines(str(avg_f))
print("The file was successfully saved.")
file.close()
Upvotes: 1
Reputation: 51643
The print() function prints on the console and returns None
. You assign this return value to a variable that you then put into the file.
Works.
Change it to
avg_f = 'Student: {:10s} Passing grades: {:<10d} Failing grades: {:<10d} Average: {:3.2f}'.format(student_name + " " + student_surname, p_g, f_g, avg)
print(avg_f)
so your variable holds the string not the retrun of print()
function.
Upvotes: 1