Stránka 1 z 1

python zádrhel

Napsal: 14 čer 2013 16:51
od funnyman
Ahoj, mám funkci, která přidává čísla do listu. pak chci ten list vytisknout, vracím tedy seznam příkazem return. ono to ale nefunguje. prosím o vysvětlení.

Kód: Vybrat vše

def tadyto(number):
    i = 0
    numbers = []
    while i < number:
        print "At the top is", i
        numbers.append(i)
   
        i += 1
        print "Numbers now:", numbers
        print "At the bottom i is", i
    print numbers
    return numbers
   
tadyto(5)
print numbers

Kód: Vybrat vše

tom@tom:~/python$ python ex33.py
At the top is 0
Numbers now: [0]
At the bottom i is 1
At the top is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
[0, 1, 2, 3, 4]
Traceback (most recent call last):
  File "ex33.py", line 16, in <module>
    print numbers
NameError: name 'numbers' is not defined

Re: python zádrhel

Napsal: 14 čer 2013 20:09
od domitea
Proměnná numbers existuje pouze v rámci funkce…

Re: python zádrhel  Vyřešeno

Napsal: 15 čer 2013 00:27
od CZechBoY
musel bys výsledek tý funkce přiřadit k proměnné numbers

Re: python zádrhel

Napsal: 19 čer 2013 13:47
od funnyman
Díky!

Jelikož zapomínám, napíšu si sem řešení:

Kód: Vybrat vše

def tadyto(number):
    i = 0
    numbers = []
    while i < number:
        print "At the top is", i
        numbers.append(i)
   
        i += 1
        print "Numbers now:", numbers
        print "At the bottom i is", i
    print numbers
    return numbers
   
cisilka = tadyto(5)
for num in cisilka:
    print num