这段代码的语义错误是什么

时间:2019-03-25 04:50:26

标签: python semantics

我有这段代码,其中包含一些我找不到的语义错误。第一行无法告诉我们什么是掷硬币。 1000次翻转是数学上不可能的1000条尾巴。当值应介于1到6之间时,骰子掷0。两个骰子结果仅告诉我们该函数,而10个骰子结果中也包含零。

import random
import numpy as np

def flipacoin():
    #This function flips a virtual coin and returns "Heads" or "Tails"
    coin = random.randint(1, 2) #returns a 1 or a 2
    if coin == 1:
        coin = "Heads"
    elif coin == 2:
        coin = "Tails"

def flipNcoins(n):
    #This function flips a coin a number of times (n flips total) and returns a string stating results.
    total_heads = 0
    total_tails = 0
    for i in range(n):
        if flipacoin() == "Heads":
            total_heads += 1
        else:
            total_tails += 1
    return "Heads " + str(total_heads) + ", Tails " + str(total_tails)


def rolladie():
    #This function rolls a virtual die and returns a number between 1 and 6.
    die = random.randint(0,6)
    return die

def rolltwodice():
    #This function rollstwo virtual dice and returns a tuple of the two values.
    die1 = rolladie()
    die2 = rolladie()
    return die1, die2

def rollNdice(n):
    #This function rolls n virtual dice and returns an array of roll values between 1 and 6.
    rolls = np.zeros((n,))
    for i in range(n):
        die = rolladie()
        rolls[i] = die
    return rolls

1 个答案:

答案 0 :(得分:1)

coin = "Heads"将局部变量coin设置为"Heads"。它不会返回它。 return "Heads"将(或等效地,在功能末尾的return coin)。假定未在结束前执行return的任何函数都将返回NoneNone显然不是"Heads",因此您累积了1000 total_tails

random.randint(0,6)将数字从0滚动到6,而不是1到6。因此,使用random.randint(1,6)代替。

我不明白您所说的“两个骰子的结果只是告诉我们有关功能”的意思。