Reputation: 19
I cannot figure out why my code is not returning the minimum score:
def min_score(student):
x = student[0]
for i in student:
if i < x:
minimum = i
i += 1
print('Minimum score:', minimum)
return minimum
brian = [input('Enter brians scores:')]
min_score(brian)
I tried adding .split()
to the end of the input but that did nothing.
Upvotes: 0
Views: 160
Reputation: 6781
Your input
statement requires few tweaks. Previously it was just a list
of one string
. What you need to do is split
your numbers by whitespace
, map each element to int
and then convert that to list
.
brian = list(map(int,input('Enter brians scores:').split()))
And few changes in your function too are required.
def min_score(student):
x_min = student[0]
for ele in student[1:]:
if ele < x_min:
x_min = ele
print('Minimum score:', x_min)
return x_min
#driver values :
IN : Enter brians scores: 3 5 1
IN : brian = [3,5,1]
OUT : Minimum score: 1
But ofcourse, its far more easier to just use the min
function on the list.
brian = list(map(int,input('Enter brians scores:').split()))
print('Minimum score:', min(brian))
Upvotes: 2
Reputation: 152
In addition to Kaushik's changes, you need to remove the line
i += 1
In a for loop, the i is already changed every time you go through the for loop. You also have to return minimum at the end of the for loop. If you return minimum as soon as you find a value lower than i, you would only find the first minimum value, not the minimum for the entire list. The revised code would look like this:
def min_score(student):
minimum = student[0]
for i in student:
if i < minimum:
minimum = i
return minimum
brian = list(map(int,input('Enter brians scores:')))
print min_score(brian)
If you put
44,33,55
into the input, the function would return
33
accurately.
Upvotes: 1
Reputation: 118
Try this, i assume the scores are comma separated when entered.
def min_score(student):
x = student[0]
print x
for i in student:
if i < x:
x = i
print('Minimum score:', x)
return x
brian = input('Enter brians scores:')
min_score(brian)
Upvotes: 1
Reputation: 5078
brian is a string. A string in python is a list of chars. With your for loop you go through each char in your string. You should split the string to get a list (of strings!). To evaluate the values you need to typecast each element of the list. Also there was a problem with your variables and you indentation. This works:
def min_score(student):
minimum = int(student[0])
for score in student:
i = int(score)
if i < minimum:
minimum = i
print('Minimum score:', minimum)
return minimum
brian = input('Enter brians scores:').split()
min_score(brian)
Upvotes: 1
Reputation: 39818
x
, but you assign to minimum
.print
and return
nested inside the if
, you won't wait until you have the minimum of the entire list.i
; it's a value out of your list, not an index.Upvotes: 0