【发布时间】:2014-11-17 14:01:46
【问题描述】:
这是我的代码
code
__author__ = 'Jared Reabow'
__name__ = 'Assignment 2 Dice game'
#Date created: 14/11/2014
#Date modified 17/11/2014
#Purpose: A game to get the highest score by rolling 5 virtual dice.
import random
#pre defined variables
NumberOfDice = 5 #this variable defined how many dice are to be rolled
def rollDice(NumberOfDice):
dice = [] #this is the creation of an unlimited array (list), it containes the values of the 5 rolled dice.
RunCount1 = 1 #This defines the number of times the first while loop has run
while RunCount1 <= NumberOfDice:
#print("this loop has run " , RunCount1 , " cycles.") #this is some debugging to make sure how many time the loop has run
TempArrayHolder = random.randint(1,6) #This holds the random digit one at a time for each of the dice in the dice Array.
dice.append(TempArrayHolder) #this takes the TempArrayHolder value and feeds it into the array called dice.
RunCount1 += 1 #this counts up each time the while loop is run.
return dice
rollDice(NumberOfDice)
dice = rollDice(NumberOfDice)
print(dice,"debug") #Debug to output dice array in order to confirm it is functioning
def countVals(dice,NumberOfDice):
totals = [0]*6 #this is the creation of a array(list) to count the number of times, number 1-6 are rolled
#print(dice, "debug CountVals function")
SubRunCount = 0
while SubRunCount < NumberOfDice:
totals[dice[SubRunCount -1] -1] += 1 #this is the key line for totals, it takes the dice value -1(to d eal with starting at 0) and uses it
#to define the array position in totals where 1 is then added.
#print(totals)
SubRunCount += 1
return totals
countVals(dice,NumberOfDice)
totals = countVals(dice,NumberOfDice)
print("totals = ",totals)
缩进可能有点错误,我是stackoverflow的新手。 如标题所述,我的问题是无论是否调用这两个函数都会运行,但如果调用它们将运行两次。
我在某处读到删除括号:
dice = rollDice(NumberOfDice)
原来是这样
dice = rollDice
会解决这个问题,在某种程度上它会做一些事情,但不是我想要的。 如果我执行上述操作,它会输出
<function rollDice at 0x00000000022ACBF8> debug
而不是运行函数,所以我很卡住。
我希望能详细解释发生了什么?
更新:我错误地调用了该函数两次。 我想我需要先运行它,然后才能使用它返回的输出,但在代码中使用时不会。
【问题讨论】:
-
你在哪里读到的?第一个版本使用单个参数
NumberOfDice调用rollDice,并将调用的结果(return值)分配给名称dice;第二个只是将函数本身分配到名称dice。
标签: python function python-3.x