Я вижу, вы не понимаете, как функции работают, поэтому я добавил комментарии ваш код, чтобы объяснить немного, но я предлагаю вам прочитать Python tutorial about functions и wiki article далее, чтобы получить понимание.
Кроме того, я пропустил много деталей, чтобы не перегружать объяснение. Важным является то, что в вашем примере неизменяемы (т. Е. Целое число, i
) и изменяемый (т. Е. Список, list1
в вашем примере) в Python, и в зависимости от этого поведение будет другим.
def num(f):
#Here the argument you pass to the function is named 'f'
#and you don't use it
#The next line uses 'list1', that is defined in global scope
#since you didn't redefined this name inside the function
#Variable 'i' is also the one in global scope for same reasons
list1.append(i)
#Here you return 'list1', though you don't use this value
#further in your program. Indeed, you would not write a return
#statement the function would return 'None' as the return value
return list1
#Here you define 'list1' in global scope, and it will be used
#inside 'num' function, even without providing it as the argument
list1 = []
#Here you define 'i' in global scope, and it will be used
#inside 'num' function
i = 1
#Here you print 'i' and 'list' from global scope
print "Now list1 is %s and i is %d" % (list1, i)
#Here you call 'num' function and 'list1' provided as argument
#is assigned to 'f' inside the function, but you didn't used it and
#and instead used names from global scope - that's why it works in
#this way (however it is wrong use of function)
#With 'list1.append(i)' the 'list1' is modified in place so it
#doesn't matter if it is returned or not
num(list1)
#As to 'num' return value, it will be the same value as 'list1', but
#you don't use it here, to use it it needs to be assigned with '=' to
#some variable, i.e. 'list2=num(list1)', though in fact 'list1' and 'list2'
#will be the same all the time due to Python internals, but let's skip the
#details of this.
#You can see that the value returned is not 'None' - add the
#following line here:
print(num(list1))
#and run your program, the output will show you that it's a list returned.
#then remove the 'return' line in your function and run program again
#the output here will show, that is's 'None' that was returned.
Так, чтобы исправить очевидную ошибку в функции:
def num(f):
f.append(i)
return f
, но я до сих пор используется в глобальном масштабе, а не передается в качестве аргумента, так даже лучше:
def num(f_var,i_var):
f_var.append(i_var)
return f_var
Хотя список будет изменен на месте, и вам действительно не нужно возвращать его в вашем конкретном примере, поэтому:
def num(f_var,i_var):
f_var.append(i_var)
list1=[]
i=1
num(list1,i)
будет работать.
У вас пока не получилось создать функцию. Значения вводят функцию с параметрами и оставляют ее с помощью 'return'.Не используйте глобальные переменные в вашей функции, поэтому в этом случае это означает, что не используйте 'list1' в функции, эта строка должна быть' f.append (i) '. Конечно, 'i' также должен быть параметром этой функции. – Matthias