gpt4 book ai didi

Python:从函数返回数组值

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:31 24 4
gpt4 key购买 nike

我正在尝试了解如何正确使用函数。在此代码中,我想为学生姓名和百分比分数返回 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

最佳答案

如果你想使用键值对,你需要使用字典而不是列表。此外,您需要返回 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}

关于Python:从函数返回数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57854072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com