Python-Alternativen zu globalen Variablen
import random
#----------------------------------------------#
def main():
create_list_and_find_max_and_min(10)
the_smart_way()
#----------------------------------------------#
def create_list_and_find_max_and_min(n):
global my_array
my_array = []
n = input("How many numbers do you want in your array?:")
for i in range(n):
my_array.append(random.randint(1,n))
print "My array is:", my_array
#----------------------------------------------#
min = my_array[0]
for number in my_array:
if min > number:
min = number
print "The minimum value in the array is:", min
#----------------------------------------------#
max = my_array[0]
for number in my_array:
if max < number:
max = number
print "The maximum value in the array is:", max
#----------------------------------------------#
def the_smart_way():
# "This one uses the built-in Python functions for min/max..."
min_my_array = min(my_array)
max_my_array = max(my_array)
return min_my_array, max_my_array
#----------------------------------------------#
if __name__ == '__main__':
main()
Ich bin ziemlich neu in der Verwendung von Python. Ich habe allgemein gehört, dass die Verwendung globaler Variablen beim Programmieren eine schlechte Praxis ist. Gibt es also Alternativen zu dem, was ich hier versuche? Welches soll die Variable "my_array" innerhalb einer anderen Funktion verwenden? Vielen Dank!