def get_student_list():
iStr = ""
stdlist = []
x = 1
while not iStr == "quit":
iStr = input(f'Please enter a new student name, ("quit" if no more student)')
if not iStr == "quit":
stdlist.append(iStr)
elif iStr == "":
print("Empty student name is not allowed.")
x = 1
print(f'The whole class list is {sum(stdList)}')
What's wrong and how do I fix it?
I'm expecting the user input student into list and end when they type quit. Or when it's empty, print empty student name is not allowed
CodePudding user response:
your list is defined in the function and your print is global so it won't work ^^ you can either define stdlist as a global (outside your function) or indent your print
CodePudding user response:
I fixed some things in your code and made it more readable
def get_student_list():
stdlist = []
while True:
iStr = input('Please enter a new student name, ("quit" if no more student)')
if iStr == "quit":
return stdlist
elif iStr == "":
print("Empty student name is not allowed.")
else:
stdlist.append(iStr)
stdList = get_student_list()
print(f"You have a total of {len(stdList)} students:")
for i, name in enumerate(stdList):
print(f" {i 1}) {name}")
This will return:
You have a total of 3 students:
1) Bob Marley
2) Michael Jackson
3) Elvis Presley
CodePudding user response:
The list stdlist
is local to the function get_student_list()
. Your last print
does not have access to it.
To fix:
def get_student_list():
# All your code here
return stdlist
stdlist = get_student_list()
print(f'The whole class list is {sum(stdlist)}')