英文:
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("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()
答案1
得分: 3
识别错误
determine_stars()
函数存在一些问题:
-
avg
的作用域:它是从main()
函数分开的独立函数,因此无法识别在main()
函数中定义的变量avg
。换句话说,avg
超出了determine_stars()
的作用域。应该有自己的参数来表示这个值。
-
离散范围:
float
类型的值实际上是连续的,因此其小数部分可以有尽可能多的位数。因此,使用离散范围将忽略在8.9
和9.0
之间的值(如8.951
)。相反,应保持范围连续。
-
没有输出:不要忘记使用
return
语句指定determine_stars()
函数的输出值。 -
条件语句:
if
语句的条件应该使用and
,而不是or
。否则每个条件都将为真,始终导致五颗星。
另外对于 main()
函数:
-
验证:
while
循环应该位于for
循环内,以跟踪用户输入的每个值。 -
计算平均值:
avg
变量没有很好定义。需要一个变量来累积分数,充当它们的总和。然后可以将该值除以数量来获取平均值。 -
循环范围:
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:
-
Scope of
avg
: It is a separate function frommain()
and therefore will not recognise the variableavg
defined in themain()
function. In other words,avg
is outside the scope ofdetermine_stars()
.Instead it should have its own parameter representing this value.
-
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 between8.9
and9.0
(such as8.951
).Instead, keep the ranges continuous.
-
No output: Don't forget to specify the output value of the
determine_stars()
function using thereturn
statement. -
If conditions: The conditions of the
if
statements should useand
, notor
. Every one of them would otherwise beTrue
, resulting always in five stars.
Also for the main()
function:
-
Validation: The
while
loop should be inside thefor
loop, to track every input entered by the user. -
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. -
For loop range: The
range(i, j)
function iterates over numbers in the interval[i, j)
(it is exclusive). Thereforerange(1, 5)
will only do4
iterations rather than5
. Instead writerange(0, 5)
(or simplyrange(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 <= 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}')
答案2
得分: 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()
- 这是第一步。第二件需要做的事情是计算这五个分数的平均值。如果这是你需要做的,可以稍微修改
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.
- 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("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()
- 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("Enter a score between 0 and 10: "))
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 <= score <= 10):
try:
score = float(input("Enter a score between 0 and 10: "))
if not (0 <= score <= 10):
raise ValueError
except ValueError:
print("Error: Invalid Input")
# 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'Your score of {avg} gives you {determine_stars(avg)}')
def determine_stars(avg):
if avg >= 9:
stars = "*****"
elif avg >= 8 and avg < 9:
stars = "****"
elif avg >= 7 and avg < 8:
stars = "***"
elif avg >= 6 and avg < 7:
stars = "**"
elif avg >= 5 and avg < 6:
stars = "*"
else:
stars = "No Stars"
return stars # Returning content's of "stars"
main()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论