By Timjinlun via Discussions on Python.org at 07Jun2022 23:02:
So I was doing a problem on the textbook, and it says " using a
function called computegrade
that takes a score as its parameter and
returns a grade as a string."
my question is, how come that it returns more than one string? Where did I go wrong?
PLZ help me, thanks everyone, I stuck this for 2 days and had no clue why.
Thank you for including your code and example output. BTW, paste code
between triple backticks to preserve the indentation:
```python
your python code here
```
and other output like this:
```
output here
```
That will keep the formatting.
Here’s your function:
def computegrade(score):
score=(0.5,0.6,0.7,0.8,0.9,1.0)
for score in [0.5,0.6,0.7,0.8,0.9,1.0]:
if score>0.9:
print('a')
elif 0.8<=score<0.9:
print ('b')
elif 0.7<=score<0.8:
print('c')
elif 0.6<=score<0.7:
print('d')
elif score<0.6:
print('failed')
else:
print('no answer')
The first thing it does is throw away the value of score
which was
passed to the function, and replace it with a tuple of several values.
Then it ignores that as well and runs a for-loop against a list of the
same values. And the function does not return a grade, it prints a
grade. These are different things.
You want your function to accept a single score and return a single
grade. So it should loook like this:
def computegrade(score):
if score>0.9:
return 'a'
elif 0.8<=score<0.9:
return 'b'
elif 0.7<=score<0.8:
return 'c'
elif 0.6<=score<0.7:
return 'd'
elif score<0.6:
return 'failed'
else:
return 'no answer'
That does not print anything - printing is for the caller of the
function, which you do here:
nam=input('enter your score')
print(computegrade(nam))
If you wanted to test several scores you might use your for-loop, again
as a caller of the computegrade
function:
for score in [0.5,0.6,0.7,0.8,0.9,1.0]:
print(score, "=>", computegrade(score))
Cheers,
Cameron Simpson cs@cskk.id.au