Python:从函数返回数组值

时间:2019-09-09 12:27:02

标签: python

我是Python的新手,正试图了解如何正确使用函数。我正在尝试返回2个数组,用于显示学生姓名和分数。但是我无法从第一个函数返回数组变量。

我尝试使用不同的方式定义数组(在全局和本地使用带括号或不带括号)

这是程序代码的相关部分

'''

#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()

我期望被要求输入两个数组的值。

我反而得到:

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

5 个答案:

答案 0 :(得分:2)

您忘记将名称和百分比设置为空字典,因此您可以使用它们。另外,“返回”也应位于for循环之外。

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()

答案 1 :(得分:2)

如果要使用键值对,则需要使用字典而不是列表。此外,您需要返回for循环之外的值。您可以尝试以下代码。

代码:

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)

输出:

>>> 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}

如果您要创建包含学生姓名和百分比的通用词典,可以尝试以下实现:

代码:

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)

输出:

>>> 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}

答案 2 :(得分:1)

可能对您有帮助。

#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)

答案 3 :(得分:0)

这是通过使用两个列表来实现的。 (不建议保留记录。请按照以下说明更好地使用字典。)

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()

以下内容是通过使用字典来实现的,为此,您不需要变量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()

将counter的值更改为所需的记录数。这样可以使标记在0到100(包括)之间并且为整数。如果使用字典实现,效果会更好。

答案 4 :(得分:-1)

将名称和百分比包含在一个字典中会更好吗?

#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)