0

I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.

I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)

This is the relevant section of code for the program

#function to ask user to input name and score
def GetInput():
    for counter in range(0,10):
        names[counter] = input("Please enter the student's name: ")
        
        valid = False
        while valid == False:
            percentages[counter] = int(input("Please enter the student's score %: "))
            if percentages[counter] < 0 or percentages[counter] > 100:
                print("Please enter a valid % [0-100]")
            else:
                valid = True
        return names, percentages

name, mark = GetInput()

I'm expecting to be asked to enter the values for both arrays.

I'm instead getting:

Traceback (most recent call last):
  File "H:/py/H/marks.py", line 35, in <module>
    name, mark = GetInput()
  File "H:/py/H/marks.py", line 7, in GetInput
    names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
3
  • "I've tried using different ways of defining the arrays". Ok, where are you doing that? Because it looks like you're referring to names on the third line without ever defining that variable beforehand. Commented Sep 9, 2019 at 12:29
  • while not valid; don't compare boolean values directly, because that just produces another boolean value. Also, you don't need a flag: just use while True, and use break where you would set value = True. Commented Sep 9, 2019 at 12:43
  • Why do you expect names to be defined? Commented Sep 9, 2019 at 12:59

5 Answers 5

2

You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.

Code:

def GetInput():
    names = {}  # Needs to declare your dict
    percentages = {}  # Needs to declare your dict
    for counter in range(0, 3):
        names[counter] = input("Please enter the student's name: ")

        valid = False
        while valid == False:
            percentages[counter] = int(input("Please enter the student's score %: "))
            if percentages[counter] < 0 or percentages[counter] > 100:
                print("Please enter a valid % [0-100]")
            else:
                valid = True
    return names, percentages  # Return outside of for loop.

name, mark = GetInput()
print(name)
print(mark)

Output:

>>> python3 test.py 
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}

If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:

Code:

def GetInput():
    students = {}
    for _ in range(0, 3):
        student_name = input("Please enter the student's name: ")
        valid = False
        while not valid:
            student_percentages = int(input("Please enter the student's score %: "))
            if student_percentages < 0 or student_percentages > 100:
                print("Please enter a valid % [0-100]")
                continue
            valid = True
            students[student_name] = student_percentages
    return students


students = GetInput()
print(students)

Output:

>>> python3 test.py 
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked thanks very much. I'm teaching at a new school, having previously used different languages. The material I'm working with drew no distinctions between dictionaries, lists and arrays. This has really helped!
2

You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:

def GetInput():
    names={}
    percentages={}
    for counter in range(0,10):
        names[counter] = input("Please enter the student's name: ")

        valid = False
        while valid == False:
            percentages[counter] = int(input("Please enter the student's score %: "))
            if percentages[counter] < 0 or percentages[counter] > 100:
                print("Please enter a valid % [0-100]")
            else:
                valid = True
    return names, percentages

name, mark = GetInput()

Comments

1

Probably this may help to you.

#function to ask user to input name and score
def GetInput():
    names=[]
    percentages=[]
    for counter in range(0,3):
        names.append(input("Please enter the student's name: "))

        valid = False
        while valid == False:
            percentages.append(int(input("Please enter the student's score %: ")))
            if percentages[counter] < 0 or percentages[counter] > 100:
                print("Please enter a valid % [0-100]")
            else:
                valid = True
    return names, percentages

name, mark = GetInput()
print(name,mark)

Comments

0

This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)

counter = 10
def GetInput():
    names = []
    percentage = []
    for i in range(counter):
        names.append(input("Please enter the student's name: "))
        valid = False
        while not(valid):      
            try:
                percent = int(input("Please enter the student's score between 0 and 100%: "))
                if percent >= 0 and percent <= 100:
                    percentage.append(percent)
                    valid = True
                    break
                else:
                    continue
            except ValueError:
                print("\nEnter valid marks!!!")
                continue
            valid = True

    return names, percentage

students, marks = GetInput()

The following is implemented by using dictionary, and for this, you do not need the variable counter.


def GetInput():
    records = dict()
    for i in range(counter):
        name = input("Please enter the student's name: ")
        valid = False
        while not(valid):      
            try:
                percent = int(input("Please enter the student's score between 0 and 100%: "))
                if percent >= 0 and percent <= 100:
                    #percentage.append(percent)
                    valid = True
                    break
                else:
                    continue
            except ValueError:
                print("\nEnter valid marks!!!")
                continue
            valid = True
        records[name] = percent
    return records

record = GetInput()

Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.

Comments

-1

Wouldn't it be better to have name and percentage in one dict?

#function to ask user to input name and score
def GetInput():
    name_percentage = {}
    for counter in range(0,10):
        name = input("Please enter the student's name: ")

        valid = False
        while not valid:
            percentage = int(input("Please enter the student's score %: "))
            if percentage < 0 or percentage > 100:
                print("Please enter a valid % [0-100]")
            else:
                valid = True
        name_percentage[name] = percentage
    return name_percentage
name_percentage = GetInput()
print(name_percentage)

1 Comment

Please pay attention and try your code. It is not working. Error: NameError: name 'percentages' is not defined. You need to define percentages dict as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.