在Python中遇到了难以理解的参数、参数传递以及向函数传递变量的问题。

huangapple go评论57阅读模式
英文:

Having trouble figuring out params, arguments, passing variables to functions in Python

问题

我在概念上理解了这一点但在语法上似乎无法理解这是我具体正在做的事情 - 获取5个输入的平均评分并显示与平均评分相关的星级数量

```python
def main():
    score = float(input("输入一个介于0到10之间的分数:"))

    while score < 0 or score > 10:
        score = float(input("错误!输入一个介于0到10之间的分数:"))
    else:
        for num in range(1,5):
            score = float(input("输入一个介于0到10之间的分数:"))
            avg = score / 5
        stars = determine_stars()
        print(f'你的得分为 {avg} 给了你 {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 = "没有星星"

main()
英文:

I understand this conceptually, but I can't seem to wrap my head around the syntax. Here is specifically what I'm working on - getting an average rating, from 5 inputs, and displaying an amount of stars as it relates to the average rating

def main():
    score = float(input(&quot;Enter a score between 0 and 10: &quot;))

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

main()

答案1

得分: 3

识别错误

determine_stars() 函数存在一些问题:

  1. avg的作用域:它是从 main() 函数分开的独立函数,因此无法识别在 main() 函数中定义的变量 avg。换句话说,avg 超出了 determine_stars() 的作用域。

    应该有自己的参数来表示这个值。

  2. 离散范围float 类型的值实际上是连续的,因此其小数部分可以有尽可能多的位数。因此,使用离散范围将忽略在 8.99.0 之间的值(如 8.951)。

    相反,应保持范围连续。

  3. 没有输出:不要忘记使用 return 语句指定 determine_stars() 函数的输出值。

  4. 条件语句if 语句的条件应该使用 and,而不是 or。否则每个条件都将为真,始终导致五颗星。

另外对于 main() 函数:

  1. 验证while 循环应该位于 for 循环内,以跟踪用户输入的每个值。

  2. 计算平均值avg 变量没有很好定义。需要一个变量来累积分数,充当它们的总和。然后可以将该值除以数量来获取平均值。

  3. 循环范围range(i, j) 函数迭代在区间 [i, j) 中的数字(不包括 j)。因此 range(1, 5) 将只执行 4 次迭代,而不是 5。取而代之,使用 range(0, 5)(或简单地 range(5))。

修复的代码和注释

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

# 根据给定的值输出星级评分。
def determine_stars(avg):
    # 五星:9 <= avg <= 10
    if avg >= 9 and avg <= 10:
        stars = "*****"
        
    # 四星:8 <= avg < 9
    elif avg >= 8 and avg < 9:
        stars = "****"
        
    # 三星:7 <= avg < 8
    elif avg >= 7 and avg < 8:
        stars = "***"
        
    # 二星:6 <= avg < 7
    elif avg >= 6 and avg < 7:
        stars = "**"
        
    # 一星:5 <= avg < 6
    elif avg >= 5 and avg < 6:
        stars = "*"
        
    # 否则,没有星星。
    else:
        stars = "无星级"
    
    # 使函数产生星级的值作为其输出
    return stars
# 主程序执行
def main():
    
    # 用于存储用户分数的总和。
    total = 0

    # 执行 5 次循环,以获取用户输入的 5 个分数。
    for num in range(0, 5):
        # 要求用户输入介于 0 到 10 之间的分数。将其输入转换为浮点数(即小数)。
        score = float(input("请输入介于 0 到 10 之间的分数:"))

        # 验证:只有在其在有效范围内(0 到 10)时才接受其输入。
        while score < 0 or score > 10:
            score = float(input("错误!请输入介于 0 到 10 之间的分数:"))
        
        # 将分数添加到总和中。
        total += score
    
    # 通过将总和除以分数的数量(5)来计算平均分数。
    avg = total / 5
    
    # 确定星级评分。
    stars = determine_stars(avg)
    
    # 输出星级评分。
    print(f'您的分数 {avg} 给您 {stars}')
英文:

Identifying bugs

There are a few problems with the determine_stars() function:

  1. Scope of avg: It is a separate function from main() and therefore will not recognise the variable avg defined in the main() function. In other words, avg is outside the scope of determine_stars().

    Instead it should have its own parameter representing this value.

  2. Discrete ranges: The values of a float are essentially continuous, and so its decimal part can have as many digits as possible. So using discrete ranges will miss, for instance, values between 8.9 and 9.0 (such as 8.951).

    Instead, keep the ranges continuous.

  3. No output: Don't forget to specify the output value of the determine_stars() function using the return statement.

  4. If conditions: The conditions of the if statements should use and, not or. Every one of them would otherwise be True, resulting always in five stars.

Also for the main() function:

  1. Validation: The while loop should be inside the for loop, to track every input entered by the user.

  2. Calculating average: The avg variable is not well defined. There needs to be a variable that can accumulate the scores, acting as the sum of all of them. It is this value that can then be divided to get the average.

  3. For loop range: The range(i, j) function iterates over numbers in the interval [i, j) (it is exclusive). Therefore range(1, 5) will only do 4 iterations rather than 5. Instead write range(0, 5) (or simply range(5)).

Fixed code and annotation

I have edited your code with fixes to these problems. To help you understand the syntax I have also added comments.

# Outputs the star average from a given value.
def determine_stars(avg):
    # Five stars: 9 &lt;= avg &lt;= 10
    if avg &gt;= 9 and avg &lt;= 10:
        stars = &quot;*****&quot;
        
    # Four stars: 8 &lt;= avg &lt; 9
    elif avg &gt;= 8 and avg &lt; 9:
        stars = &quot;****&quot;
        
    # Three stars: 7 &lt;= avg &lt; 8
    elif avg &gt;= 7 and avg &lt; 8:
        stars = &quot;***&quot;
        
    # Two stars: 6 &lt;= avg &lt; 7
    elif avg &gt;= 6 and avg &lt; 7:
        stars = &quot;**&quot;
        
    # One star: 5 &lt;= avg &lt; 6
    elif avg &gt;= 5 and avg &lt; 6:
        stars = &quot;*&quot;
        
    # Otherwise, no stars.
    else:
        stars = &quot;No Stars&quot;
    
    # 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&#39;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(&quot;Enter a score between 0 and 10: &quot;))

        # Validation: Keep rejecting their input until it is in the valid range (0 to 10).
        while score &lt; 0 or score &gt; 10:
            score = float(input(&quot;ERROR! Enter a score between 0 and 10: &quot;))
        
        # 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&#39;Your score of {avg} gives you {stars}&#39;)

答案2

得分: 1

有几件事情需要注意和修改。

  1. determine_stars 是一个与 main 不同的函数(至少是当前的写法)。因为它是一个不同的函数,所以它不会识别函数内的 avg 作为一个变量(查看全局变量以了解原因)。这里最简单的解决办法是将 avg 作为该函数的输入提供。可以像这样修改:
def main():
    score = float(input("输入一个0到10之间的分数: "))

    while score < 0 or score > 10:
        score = float(input("错误!请输入一个0到10之间的分数: "))
    else:
        for num in range(1, 5):
            score = float(input("输入一个0到10之间的分数: "))
            avg = score / 5
        stars = determine_stars(avg)
        print(f'您的平均分 {avg} 对应的星级是 {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 = "没有星级"

main()
  1. 这是第一步。第二件需要做的事情是计算这五个分数的平均值。如果这是你需要做的,可以稍微修改 else 语句如下:
else:
    score = 0
    for num in range(1, 5):
        score += float(input("输入一个0到10之间的分数: "))
    avg = score / 5

请注意,我只翻译了你提供的代码部分,没有额外的内容。

英文:

There are a couple of things that are happening here that you might need to change.

  1. determine_stars is a separate function from main (at least the way it is currently written). Because it's a different function, it doesn't recognize avg as a variable inside the function (Look at global variables to understand why). The easiest solution here is to provide avg as an input to that function. something like this:
def main():
    score = float(input(&quot;Enter a score between 0 and 10: &quot;))

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

main()
  1. That's step one. The second thing you need to do is calculate the average of the 5 scores. Assuming that is what you need to do, I would change the else statement a little bit:
else:
    score = 0
    for num in range(1,5):
        score += float(input(&quot;Enter a score between 0 and 10: &quot;))
    avg = score/5

答案3

得分: 0

你的 determine_stars() 函数需要返回一些东西,目前它没有返回任何内容。同时,它需要接受你的 avg 作为参数。我添加了 return stars,这是你要寻找的内容。另外,你必须将你的 "OR" 调整为 "AND",因为你要同时满足两个条件,而不仅仅是其中一个。

至于你的主要函数,你打算收集 5 个介于 0 到 10 之间的值,如果输入了不希望的内容,你希望出现错误,并要求输入有效的内容。你可以通过首先创建一个 for 循环来进行 5 次运行来实现这一点。然后是一个 while 循环,除非插入有效的输入,否则不会退出。一旦收到有效的输入,脚本就会继续。

我还使用了一个总分值来满足 while 循环的条件,因为分数已经设定,你不想改变它。

def main():
    total_score = 0
    for _ in range(5):
        score = None  # 为了满足 while 循环的条件,不让所有 5 个输入都相同
        # While 循环直到得到 0 到 10 之间的输入
        while score is None or not (0 <= score <= 10):
            try:
                score = float(input("输入一个介于 0 到 10 之间的分数:"))
                if not (0 <= score <= 10):
                    raise ValueError
            except ValueError:
                print("错误:无效的输入")
        # 现在我们有了有效的输入,将其添加到 total_score 中
        total_score += score

    avg = total_score / 5
    # 打印输出,将 `avg` 传递给 `determine_stars`
    print(f'你的平均分 {avg} 给你 {determine_stars(avg)}')

def determine_stars(avg):
    if avg >= 9:
        stars = "*****"
    elif 8 <= avg < 9:
        stars = "****"
    elif 7 <= avg < 8:
        stars = "***"
    elif 6 <= avg < 7:
        stars = "**"
    elif 5 <= avg < 6:
        stars = "*"
    else:
        stars = "没有星星"
    return stars  # 返回 "stars" 的内容

main()

希望这对你有所帮助!

英文:

Few things, your determine_stars() function needs to return something which it currently does not. As well it needs to take in your avg as an argument. I added return stars which is what you were looking for. Secondly you must adjust your "OR" to "AND" as you are trying to meet both conditions and not just one or the other.

As for your main function, you are intending to gather 5 inputs of values between 0-10, if somethings is thrown that you do not want you want an error, asking for the a valid input. You Can achieve this by first creating a for loop set to do 5 runs. THEN a while loop that won't break unless a valid input is inserted, once receiving a valid input the script proceeds.

I also use a total score value to meet conditions of the while loop as the score is already set and you don't want to change it.

def main():
    total_score = 0
    for _ in range(5):
        score = None # To meet condition of while loop and not make all 5 inputs the same
        # While loop until we get a input from 0 to 10
        while score is None or not (0 &lt;= score &lt;= 10):
            try:
                score = float(input(&quot;Enter a score between 0 and 10: &quot;))
                if not (0 &lt;= score &lt;= 10):
                    raise ValueError
            except ValueError:
                print(&quot;Error: Invalid Input&quot;)
        # Now that we got a valid input add to total_score
        total_score += score

    avg = total_score / 5
    # Printing output, passing `avg` to determine_stars
    print(f&#39;Your score of {avg} gives you {determine_stars(avg)}&#39;)



def determine_stars(avg):
    if avg &gt;= 9:
        stars = &quot;*****&quot;
    elif avg &gt;= 8 and avg &lt; 9:
        stars = &quot;****&quot;
    elif avg &gt;= 7 and avg &lt; 8:
        stars = &quot;***&quot;
    elif avg &gt;= 6 and avg &lt; 7:
        stars = &quot;**&quot;
    elif avg &gt;= 5 and avg &lt; 6:
        stars = &quot;*&quot;
    else:
        stars = &quot;No Stars&quot;
    return stars # Returning content&#39;s of &quot;stars&quot;

main()

huangapple
  • 本文由 发表于 2023年2月27日 02:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574039.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定