Python 返回与随机整数对应的给定名称

Python 返回与随机整数对应的给定名称,python,random,Python,Random,披露:我是一个Python(和编码)婴儿。我刚刚开始CS,我正在尽我最大的努力,但我正在努力。这是一个家庭作业问题。我根据随机生成的整数(从0到3)分配一套卡片套装,s.t.0=黑桃,1=红桃,2=梅花,3=钻石 以下是我得到的: def random_suit_number(): ''' Returns a random integer N such that 0 <= N < 4. ''' pass def get_card_suit_string_from_n

披露:我是一个Python(和编码)婴儿。我刚刚开始CS,我正在尽我最大的努力,但我正在努力。这是一个家庭作业问题。我根据随机生成的整数(从0到3)分配一套卡片套装,s.t.0=黑桃,1=红桃,2=梅花,3=钻石

以下是我得到的:

def random_suit_number():
    ''' Returns a random integer N such that 0 <= N < 4. '''
    pass

def get_card_suit_string_from_number(n):
    ''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    pass
def random_suit_number():

''返回一个随机整数N,因此0您基本上只想返回名称,所以只需返回
“黑桃”或“梅花”
。基本上,在获得随机数后,只需将其值与0、1、2和3进行比较,然后返回“Clubs”

只需将值与dict中的名称进行映射:

def get_card_suit_string_from_number(n):
   ''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    n = random_suit_number()
    return {
        0: 'Spades',
        1: 'Hearts',
        2: 'Clubs',
        3: 'Diamonds',
    }.get(n)

你很接近。您可以按如下方式展开函数

def get_card_suit_string_from_number(n):
    ''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
    n = random_suit_number()

    if n == 0: 
        return 'Spades'
    elif n == 1:
        return 'Hearts'
    elif n == 2:
        return 'Clubs'
    elif n == 3:
        return 'Diamonds'
    else:
        return None

勇气!据我所知,你的第一个函数实际上是正确的

关于第二个问题:

def get_card_suit_string_from_number(n):
''' Returns the name of the suit that corresponds to the value n, or None if n is an invalid number. '''
由于n在声明中的函数名后面的括号中给出,这意味着它已经在函数中定义。事实上,它是给函数的输入,因此您不需要自己分配它,尽管函数的调用者可能会像您在这里所做的那样分配它:

    n = random_suit_number() #not needed
if子句是好的,您希望检查有效数字,但有效数字是0,1,2,3。您可以在[0,1,2,3]中制定条件
n

    if n == 0: #put the correct condition here
从函数返回值的方法是通过return语句(就像您对函数1所做的那样)。实际上,您需要两个返回语句,一个在if语句的第一个分支中,另一个在您还必须创建的else分支中。看一下字典,根据n分配正确的西装串

        #define dict
        get_card_suit_string_from_number(n) = 'Spades' #change to return statement
    #add else branch with second return

祝你好运,你就快到了

您不能为函数调用指定值。您应该只返回值,即
返回“Spades”
。感谢您如此全面耐心地引导我完成思考过程!这一切在解释时似乎都很明显……欢迎来到stackoverflow,很高兴我能帮上忙!别忘了投票给那些对你的问题有想法的好人;)
        #define dict
        get_card_suit_string_from_number(n) = 'Spades' #change to return statement
    #add else branch with second return