2012-02-11 63 views
-2

我正在學習Python和我爲什麼要在函數的相關章節,我寫代碼之一:Python的功能不起作用

import random 

def roll(sides, dice): 
    result = 0 
    for rolls in range(0,dice): 
     result += random.randint(1, sides) 
    return result 

,但是,當我試圖進入功能,這出現

Traceback (most recent call last): 


File "<pyshell#16>", line 1, in <module> 
    roll() 
TypeError: roll() takes exactly 2 positional arguments (0 given) 
+0

「我在功能上的章」在什麼書? – 2012-02-11 02:16:05

+1

逐行瀏覽您的代碼。你認爲會發生什麼? – 2012-02-11 03:13:23

回答

1

您需要在()之間放入數字。像卷(3,1)

1

函數需要兩個參數,如

twoDice = roll(6, 2) 

nineCoinFlips = roll(2, 9) 
1
>>> import random 
>>> def roll(sides, dice): 
...  result = 0 
...  for rolls in range(0,dice): 
...   result += random.randint(1, sides) 
...  return result 
... 
>>> roll(6, 8) 
23 

你也可以設置默認值:

>>> import random 
>>> def roll(sides = 6, dice = 2): 
...  result = 0 
...  for rolls in range(0,dice): 
...   result += random.randint(1, sides) 
...  return result 
... 
>>> roll() 
10 
5

你的函數需要兩個參數。您需要爲sides傳遞一個值,另一個值爲dice

因此,你的函數調用合適的例子是這樣的:

roll(1,3) 

當然,有時候你希望你的函數有默認參數。換句話說,你希望能夠呼叫你的功能沒有任何明確的參數。爲此,可以在函數定義中添加參數的默認值。假設您希望該功能在默認情況下像普通模子一樣工作。所有你需要做的是這樣的:

def roll(sides = 6, dice = 1) 

有了這個功能,呼叫如roll(),將假定你傳遞6和1作爲參數。當然,你總是可以用參數調用你的函數,它會覆蓋默認值。

TL; DR:傳遞參數,定義默認參數或兩者。