Python Alternatives to Global Variables

后端 未结 3 1957
Happy的楠姐
Happy的楠姐 2020-12-16 05:00
import random  

#----------------------------------------------#
def main():  
    create_list_and_find_max_and_min(10)  
    the_smart_way()
#---------------------         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 05:11

    Functions do things to objects and then return results. You want to keep functions dead-simple and perform all of your logic and processing outside of the function. This will remove the need for global variables and will make your code much, much easier to read.

    That being said, here is how I would attack your problem:

    import random  
    
    def random_list(n=None):
      n = n or int(raw_input('How many numbers do you want in your list? '))    
    
      return [random.randint(1, n) for i in range(n)]
    
    if __name__ == '__main__':
      my_list = random_list(10)
      minimum, maximum = min(my_list), max(my_list)
    
      print 'My list is ', my_list
      print 'The minimum value in the list is ', minimum
      print 'The maximum value in the list is ', maximum
    

提交回复
热议问题