My code and how it works

The best way i found of doing this without sorting the list and using a loop would be:

def max_num(nums):
  i = nums[0]
  for num in nums:  
    if i > num:
      continue
    else:
      i = num
  return i

(this is from my basic knowledge of python)

1 Like

could you please explain to me your code, I see that it is functioning, but why does it function I do not understand :slight_smile:
If possible could you please comment on each line of the text?

def max_num(nums):
  i = nums[0]  # i am defining the variable (i) as the first number in the list of num ( the element at index 0) 
  for num in nums:  # this means it will iterate through each element in nums
    if i > num:   # if (i) is greater than the element it will skip the element (i.e continue)
      continue 
    else:            
      i = num    # else if (i) is smaller than the element it will assign that number as i
  return i

so this code will iterate though each element in the list nums, it will then compare each element to the variable i which starts off as the first element in the list, if i is greater than the element it will skip that number using a continue statement, if the number is greater than i it will reassign i as that number, it will continue this loop untill all numbers have been checked, which will then return the final value of i.

3 Likes