简体   繁体   English

在 Python 中使用另一个函数的返回输出

[英]Using returned outputs from one function in another in Python

new to Python - struggling with functions. Python 新手 - 在函数方面苦苦挣扎。 - Image of code attached. - 附上代码的图像。

It inputs the name & scores just fine with the validation checks.它通过验证检查输入名称和分数就好了。 I need to use the scores input by the user and total them.我需要使用用户输入的分数并将它们加总。 However, when I've tried to sum(score) it doesn't like it.但是,当我尝试求和(得分)时,它不喜欢它。 I can't work out how to sum the 4 total scores.我不知道如何将 4 个总分相加。

Please help :) Also would love any feedback on the style of coding etc. Thanks in advance x请帮忙 :) 也希望对编码风格等提供任何反馈。在此先感谢 x

Image: Code in Python图片:Python 代码

In the absense of code for people to see, we have something like在人们看不到代码的情况下,我们有类似的东西

def get_stuff():
    for i in rnage(4):
        name = input("Name?")
        score = int(input("Score?"))

and another function和另一个功能

def TotalScore():
    pass

How do we call total score?我们如何称呼总分? Answer: Make sure we don't forget the user inputs and return them:答:确保我们不会忘记用户输入并返回它们:

def get_stuff():
    names = []
    scores = []
    for i in range(4):
        names.append(input("Name?"))
        scores.append(int(input("Score?")))
    return names, scores

and take the scores in the summing function:并在求和函数中取分数:

def TotalScore(scores):
    return sum(scores)

This, of course, changes the calling code.当然,这会更改调用代码。 For example, you need to capture the returns when you call get_stuff :例如,您需要在调用get_stuff时捕获返回:

names, scores = get_stuff()
total = TotalScores(scores)

I would rewrite the main function to be something like:我会将主要功能重写为:

def GetStudentInput():
  score = 0
  for i in range (4):
      print("Mrs Pearson's Class Test Score Data")
      name = CheckStringInput("What's Your Name: ")
      score += CheckNumericInput("What's Your Score: ")
  print(score)

This eliminates the need for an extra function and avoids using a list since you don't appear to need the individual values elsewhere -- only the sum total.这消除了对额外函数的需要并避免使用列表,因为您似乎不需要其他地方的单个值——只需要总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM