Well, you have 2 language errors, 1 logic error, and a few minor issues :D
The language errors are both in biggestNumber == numbers[x]
:
- first, the double equal sign, not an assignment; your code will check if
biggestNumber
is equal to numbers[x]
but then the result is not assigned to anything so it is just thrown away
- second, you didn't declare the variable as
global
. So once you have corrected ==
in =
you will assign to a local variable which has nothing to do with the external one. Add global biggestNumber
before you assign it
The logic error is in for x in range(realLength):
:
range()
will return numbers up to but not including the stop value, so length
is the value we want. If the last number were the biggest you would not find it
Now the minor issues:
x = 1
and x = x + 1
are useless: the for loop takes care of its control variable (in this case they are just useless, but there are situations in which tampering with a control variable can cause a bug)
len()
already returns an integer so there's no need to do `int(len(numbers))
- although you can use a
global
, this is almost never a good idea: handle the variable in the function, and return
it to the caller
- instead of accessing the items in your list by index you could directly use them in your loop
- you could start the loop from the second item (the one at index 1) since you already handled the first one
To sum up, I would change your code this way:
numbers=[34, 23, 65, 435, 34, 56, 67, 454, 34, 2]
def displayBiggest(numbers):
biggestNumber = numbers[0]
for n in numbers[1:]:
if n > biggestNumber:
biggestNumber = n
return biggestNumber
displayBiggest(numbers) # will return 454