2013-03-11 144 views
-1

我有一個程序來產生一個10到10之間的隨機數字列表,然後計算每個數字出現多少次,然後創建一個刪除重複項的新列表。我一直得到某些全局名稱沒有定義。我似乎對返回功能感到困惑。儘管我需要這種格式,所以我不能只在每個函數的末尾添加打印語句。任何幫助?蟒蛇返回功能

def main(): 
    """print output of program""" 
    firstList= [] 
    randomTen(firstList) 
    countInts(firstList) 
    removeDuplicates(firstList) 
    print(firstList) 
    print('The number of times one appears is', ones) 
    print('The number of times two appears is', twos) 
    print('The number of times three appears is', threes) 
    print('The number of times four appears is', fours) 
    print('The number of times five appears is', fives) 
    print(secondList) 


def randomTen(firstList): 
    """return list of ten integers""" 
    for num in range(1,11): 
     x= int(random.randint(1,5)) 
     firstList.append(x) 
    return firstList 


def countInts(firstList): 
    """count the number of times each integer appears in the list""" 
    ones= firstList.count(1) 
    twos= firstList.count(2) 
    threes= firstList.count(3) 
    fours= firstList.count(4) 
    fives= firstList.count(5) 
    return ones, twos, threes, fours, fives 

def removeDuplicates(firstList): 
    """return list of random integers with the duplicates removed""" 
    secondList=set(firstList) 
    return secondList 
+0

後你得到的追蹤和錯誤消息。 – 2013-03-11 16:42:09

+1

哪個全球名稱? – NPE 2013-03-11 16:42:12

+0

好吧,它說的一些,但我想象如果它意味着一,二,三,四,五和秒列表,但是正在停止在 – tinydancer9454 2013-03-11 16:44:32

回答

3

問題是你忽略了函數的返回值。例如,

countInts(firstList) 

應該讀

ones, twos, threes, fours, fives = countInts(firstList) 

沒有這一點,onesmain()不存在。

對於其他功能也是如此(除了randomTen(),除了返回firstList之外,還修改了它)。

1

NPE's answer是完全正確的,您需要將函數的返回值分配給局部變量。

這就是說,這裏有一點pythonic方式完成相同的任務。

from collections import Counter 
from random import randint 

nums = [randint(1, 5) for _ in range(10)] 
counts = Counter(nums) 
uniq_nums = set(nums) # or list(counts.keys()) 

顯示值做

print nums 
for word, num in (('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)): 
    print 'The number of times %s appears is %s' % (word, counts[num]) 
print uniq_nums 

它打印:

[4, 5, 1, 4, 1, 2, 2, 3, 2, 1] 
The number of times one appears is 3 
The number of times two appears is 3 
The number of times three appears is 1 
The number of times four appears is 2 
The number of times five appears is 1 
set([1, 2, 3, 4, 5])