首页 > 解决方案 > How do i return a string if a list is empty in python

问题描述

I'm fairly new to coding, but what this project is asking, is to complete the function so that if a list is empty, it returns the string "does not exist" but currently, it comes up with a bunch of errors. How do I go about adding a function within my lowest_number definition that returns a string if a list is empty (for example, list6)

def lowest_number(num_list):
  lowest = num_list[0]
  for x in num_list:
    if x < lowest:
      lowest = x
  return lowest
  

标签: pythonstringlist

解决方案


change the lowest_number to look like:

Adding if conditon to check the length of the list

def lowest_number(num_list):
  if (len(num_list) < 1): # change over here
    return "does not exist" # change over here 
  lowest = num_list[0]
  for x in num_list:
    if x < lowest:
      lowest = x
  return lowest


推荐阅读