Python Alternatives to Global Variables

后端 未结 3 1948
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:29

    Here is how I would do this:

    import random  
    
    #----------------------------------------------#
    def main():
        # note that input can be dangerous since it evaluates arbitrary code
        n = int(raw_input("How many numbers do you want in your array?: "))
        my_list = [random.randint(1, n) for _ in range(n)]
        find_max_and_min(my_list)  
        the_smart_way(my_list)
    #----------------------------------------------#
    def find_max_and_min(seq):
        print "My array is:", seq
        #----------------------------------------------#
        min_num = seq[0] # Don't want to use same names as bultins here
        for number in seq:
            if number < min_num:
                min_num = number
        print "The minimum value in the array is:", min_num
        #----------------------------------------------#
        max_num = seq[0]
        for number in seq:
            if number > max_num:
                max_num = number
        print "The maximum value in the array is:", max_num
    #----------------------------------------------#
    def the_smart_way(seq):
        # "This one uses the built-in Python functions for min/max..."
        # No need for temp variables here
        print min(seq), max(seq)
    #----------------------------------------------#
    if __name__ == '__main__':
        main()
    

提交回复
热议问题