在 Python 中计算参数、参数、将变量传递给函数时遇到问题

问题描述 投票:0回答:4

我从概念上理解这一点,但我似乎无法理解语法。这是我正在做的具体工作——从 5 个输入中获得平均评分,并显示与平均评分相关的星星数量

def main():
    score = float(input("Enter a score between 0 and 10: "))

    while score < 0 or score > 10:
        score = float(input("ERROR! Enter a score between 0 and 10: "))
    else:
        for num in range(1,5):
            score = float(input("Enter a score between 0 and 10: "))
            avg = score / 5
        stars = determine_stars()
        print(f'Your score of {avg} gives you {stars}')
        
def determine_stars():
    if avg >= 9.0 or avg <= 10.0:
        stars = "*****"
    elif avg >= 8.0 or avg <= 8.9:
        stars = "****"
    elif avg >= 7.0 or avg <= 7.9:
        stars = "***"
    elif avg >= 6.0 or avg <= 6.9:
        stars = "**"
    elif avg >= 5.0 or avg <= 5.9:
        stars = "*"
    else:
        stars = "No Stars"

main()
python scope parameter-passing local
4个回答
0
投票

这里发生了一些您可能需要更改的事情。

  1. determine_stars 是一个独立于 main 的函数(至少是目前的写法)。因为它是一个不同的函数,所以它不会将
    avg
    识别为函数内部的变量(查看全局变量以了解原因)。这里最简单的解决方案是提供 avg 作为该函数的输入。像这样:
def main():
    score = float(input("Enter a score between 0 and 10: "))

    while score < 0 or score > 10:
        score = float(input("ERROR! Enter a score between 0 and 10: "))
    else:
        for num in range(1,5):
            score = float(input("Enter a score between 0 and 10: "))
            avg = score / 5
        stars = determine_stars(avg)
        print(f'Your score of {avg} gives you {stars}')
    
def determine_stars(avg):
    if avg >= 9.0 or avg <= 10.0:
        stars = "*****"
    elif avg >= 8.0 or avg <= 8.9:
        stars = "****"
    elif avg >= 7.0 or avg <= 7.9:
        stars = "***"
    elif avg >= 6.0 or avg <= 6.9:
        stars = "**"
    elif avg >= 5.0 or avg <= 5.9:
        stars = "*"
    else:
        stars = "No Stars"

main()
  1. 这是第一步。您需要做的第二件事是计算 5 个分数的平均值。假设这是你需要做的,我会稍微改变一下 else 语句:
else:
    score = 0
    for num in range(1,5):
        score += float(input("Enter a score between 0 and 10: "))
    avg = score/5

0
投票

您的代码中存在许多问题。即使您修复了缩进错误,您也有未声明的变量,以及数学和条件问题。下面是一个完整的注释示例,它简化了整个过程。

from statistics import mean
  
#constant expression
SCMSG = "Enter a score between 0 and 10: "
SCORE = lambda: float(input(SCMSG))

#configure
MIN   = 0
MAX   = 10
AVGS  = 5
HALF  = MAX//2


def main():
    scores = []
    
    #input loop
    for _ in range(AVGS):
        #keep asking for the same input until it is correct
        while MIN > (s:=SCORE()) or s > MAX: pass
            
        #must be correct, append to scores
        scores.append(s)
    
    #loop is finished - get average
    avg   = mean(scores)
    
    #determine stars (0 to 5) - no branches
    stars = "*"*int(min(max(MIN,avg-HALF+1),HALF)) or 'no stars'
    
    #print data
    print(f'Your score of {avg} gives you {stars}')
      
      
main()

测试所有可能的星级结果

for i in range(MAX*100+1):
    print(f'average: {(avg:=(i*.01)):.2f}', 
          "*"*int(min(max(MIN,avg-HALF+1),HALF)) or 'no stars')

0
投票

几件事,你的

determine_stars()
函数需要返回一些它目前没有的东西。它还需要将您的
avg
作为参数。我添加了
return stars
,这正是您要找的。其次,您必须将“或”调整为“和”,因为您要同时满足这两个条件,而不仅仅是一个或另一个。

对于您的主要功能,您打算收集 5 个介于 0-10 之间的值输入,如果抛出您不希望出现的错误,则要求提供有效输入。您可以通过首先创建一个 for 循环集来运行 5 次来实现这一点。然后是一个 while 循环,除非插入有效输入,否则不会中断,一旦收到有效输入,脚本就会继续。

我还使用总分值来满足 while 循环的条件,因为分数已经设置并且您不想更改它。

def main():
    total_score = 0
    for _ in range(5):
        score = None
        while score is None or not (0 <= score <= 10):
            try:
                score = float(input("Enter a score between 0 and 10: "))
                if not (0 <= score <= 10):
                    raise ValueError
            except ValueError:
                print("Error: Enter a valid score between 0 and 10")

        total_score += score

    avg = total_score / 5
    print(f'Your score of {avg} gives you {determine_stars(avg)}')



def determine_stars(avg):
    if avg >= 9.0 and avg <= 10.0:
        stars = "*****"
    elif avg >= 8.0 and avg <= 8.9:
        stars = "****"
    elif avg >= 7.0 and avg <= 7.9:
        stars = "***"
    elif avg >= 6.0 and avg <= 6.9:
        stars = "**"
    elif avg >= 5.0 and avg <= 5.9:
        stars = "*"
    else:
        stars = "No Stars"
    return stars

main()

0
投票

识别错误

determine_stars()
功能有几个问题:

  1. avg
    的范围:它是一个独立于
    main()
    的函数,因此不会识别
    avg
    函数中定义的变量
    main()
    。也就是说,
    avg
    不在
    determine_stars()
    的范围内。

    相反,它应该有自己的参数代表这个值。

  2. 离散范围

    float
    的值本质上是连续的,因此它的小数部分可以有尽可能多的数字。因此,使用离散范围会丢失,例如,
    8.9
    9.0
    之间的值(例如
    8.951
    )。

    相反,保持范围连续。

  3. 无输出:不要忘记使用

    determine_stars()
    语句指定
    return
    函数的输出值。

  4. If条件

    if
    语句的条件应该使用
    and
    ,而不是
    or
    。否则他们每个人都是
    True
    ,结果总是五颗星。

还有

main()
功能:

  1. Validation

    while
    循环应该在
    for
    循环内,以跟踪every用户输入。

  2. 计算平均值

    avg
    变量定义不明确。需要有一个可以累积分数的变量,作为所有分数的总和。然后可以将这个值除以得到平均值。

  3. For循环范围

    range(i, j)
    函数迭代区间
    [i, j)
    中的数字(它是独占的)。因此
    range(1, 5)
    只会进行
    4
    迭代而不是
    5
    。而是写
    range(0, 5)
    (或简单地
    range(5)
    )。

固定代码和注解

我已经编辑了您的代码并修复了这些问题。为了帮助您理解语法,我还添加了注释。

# Outputs the star average from a given value.
def determine_stars(avg):
    # Five stars: 9 <= avg <= 10
    if avg >= 9 and avg <= 10:
        stars = "*****"
        
    # Four stars: 8 <= avg < 9
    elif avg >= 8 and avg < 9:
        stars = "****"
        
    # Three stars: 7 <= avg < 8
    elif avg >= 7 and avg < 8:
        stars = "***"
        
    # Two stars: 6 <= avg < 7
    elif avg >= 6 and avg < 7:
        stars = "**"
        
    # One star: 5 <= avg < 6
    elif avg >= 5 and avg < 6:
        stars = "*"
        
    # Otherwise, no stars.
    else:
        stars = "No Stars"
    
    # Have the function produce the value of stars as its output
    return stars
# Main program execution
def main():
    
    # To store the sum of the user's scores.
    total = 0

    # Do 5 loops, to take 5 scores from the user.
    for num in range(0, 5):
        # Ask the user to input a score between 0 and 10. Convert their input to a float (i.e. a decimal).
        score = float(input("Enter a score between 0 and 10: "))

        # Validation: Keep rejecting their input until it is in the valid range (0 to 10).
        while score < 0 or score > 10:
            score = float(input("ERROR! Enter a score between 0 and 10: "))
        
        # Add the score to the total.
        total += score
    
    # Calculate the average score by dividing the total from the number of scores (5).
    avg = total / 5
    
    # Determine the star rating.
    stars = determine_stars(avg)
    
    # Output the star rating.
    print(f'Your score of {avg} gives you {stars}')
© www.soinside.com 2019 - 2024. All rights reserved.