python zádrhel

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

Zamčeno
funnyman
nováček
Příspěvky: 33
Registrován: 23 bře 2013 14:25

python zádrhel

Příspěvek 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
Uživatelský avatar
domitea
Tvůrce článků
Příspěvky: 1971
Registrován: 24 čer 2009 19:46
Bydliště: Královehradecký kraj
Kontaktovat uživatele:

Re: python zádrhel

Příspěvek od domitea »

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: 20 srp 2008 14:02
Bydliště: Brno
Kontaktovat uživatele:

Re: python zádrhel

Příspěvek od CZechBoY »

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: 23 bře 2013 14:25

Re: python zádrhel

Příspěvek 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
Zamčeno

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