python zádrhel Vyřešeno

Místo pro dotazy a rady ohledně programovacích jazyků (C++, C#, PHP, ASP, Javascript, VBS..) a tvorby webových stránek

Moderátor: Mods_senior

funnyman
nováček
Příspěvky: 33
Registrován: březen 13
Pohlaví: Muž
Stav:
Offline

python zádrhel

Příspěvekod funnyman » 14 čer 2013 16:51

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

Reklama
Uživatelský avatar
domitea
Tvůrce článků
Level 4.5
Level 4.5
Příspěvky: 1971
Registrován: červen 09
Bydliště: Královehradecký kraj
Pohlaví: Muž
Stav:
Offline
Kontakt:

Re: python zádrhel

Příspěvekod domitea » 14 čer 2013 20:09

Proměnná numbers existuje pouze v rámci funkce…

Uživatelský avatar
CZechBoY
Master Level 9.5
Master Level 9.5
Příspěvky: 8813
Registrován: srpen 08
Bydliště: Brno
Pohlaví: Muž
Stav:
Offline
Kontakt:

Re: python zádrhel  Vyřešeno

Příspěvekod CZechBoY » 15 čer 2013 00:27

musel bys výsledek tý funkce přiřadit k proměnné numbers
PHP, Nette, MySQL, C#, TypeScript, Python
IntelliJ Idea, Docker, Opera browser, Linux Mint
iPhone XS
Raspberry PI 3 (KODI, Raspbian)
XBox One S, PS 4, nVidia GeForce NOW

funnyman
nováček
Příspěvky: 33
Registrován: březen 13
Pohlaví: Muž
Stav:
Offline

Re: python zádrhel

Příspěvekod funnyman » 19 čer 2013 13:47

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


Zpět na “Programování a tvorba webu”

Kdo je online

Uživatelé prohlížející si toto fórum: Žádní registrovaní uživatelé a 4 hosti