Man, I'm on here a lot tonight.
Ok, so I just finished my assignment. My only problem at this point is when I go to test the "else", it keeps spamming print until I stop it.
Here is the full code.
import re
from statistics import mean
def file_info():
# Open & read file
grades_file = open('grades.txt', 'r')
file_contents = grades_file.read()
# Print Header & spacer
print('Name' + '\t\tGrade')
print('---------------------')
# Print contents of file
print(file_contents.rstrip('\n'))
# Extract numbers from file, calculate avg
num_list = re.findall(r"[-+]?\d*\.\d+|\d+", file_contents)
grades = [float(num) for num in num_list]
average = mean(grades)
# Print avg
print('Average Grade:', format(average, '.2f'))
# Close file
grades_file.close()
def main():
file_info()
# Open file to append
grades_file = open('grades.txt', 'a')
# Continue program press y or n
fwd = str(input('\nAdd another student (Y/N): '))
while True:
if fwd.lower() == 'y':
while True:
name = str(input("Enter student's name: "))
if not name.isalpha():
print("Please enter a valid name.")
continue
else:
break
while True:
grade = float(input("Enter student's grade: "))
if grade < 0:
print("Input grade between 0-100.")
continue
elif grade > 100:
print("Input grade between 0-100.")
continue
else:
break
# Write data to file
grades_file.write(name + ' ' + str(grade) + '\n')
# Continue adding more students?
cont = str(input('Add another student (Y/N): '))
if cont.lower() == 'y':
continue
elif cont.lower() == 'n':
grades_file.close()
file_info()
exit()
else:
print('Choose "Y" or "N"')
elif fwd.lower() == 'n':
exit()
else:
print('Choose "Y" or "N"')
continue
main()
If I try to test the last "else" statement, it spams "Choose Y or N" until I stop the program.
The only thing that stops it is if I "break" but then the program stops and doesn't try to ask the user input again. Ideas?
Edit: This is what the output looks like
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Choose "Y" or "N"
Aucun commentaire:
Enregistrer un commentaire