【问题标题】:Returning variable from function and printing said variable从函数返回变量并打印所述变量
【发布时间】:2015-08-19 11:49:55
【问题描述】:

在下面的代码中,我运行了一个二十一点游戏,我想用一个函数计算任何一手牌(用户或庄家的)。当我运行代码时没有出现错误,但是当我调用该函数时,不会打印总手牌值。它只是说“这为您提供了总计:”并且数字为空白。见以下代码:

user_name = input("Please enter your name:")

print ("Welcome to the table {}. Let's deal!".format(user_name))

import random

suits = ["Heart", "Diamond", "Spade", "Club"]

ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

deck = [(suit, rank) for rank in ranks for suit in suits]

random.shuffle(deck,random.random)

user_hand = []

dealer_hand = []

user_hand.append(deck.pop())

dealer_hand.append(deck.pop())

user_hand.append(deck.pop())

dealer_hand.append(deck.pop())

def handtotal (hand):

    total = 0

    for rank in hand:

        if rank == "J" or "Q" or "K":

            total += 10

        elif rank == 'A' and total < 11:

            total += 11

        elif rank == 'A' and total >= 11:

            total += 1

        elif rank == '2':

            total += 2

        elif rank == '3':

            total += 3

        elif rank == '4':

            total += 4

        elif rank == '5':

            total += 5

        elif rank == '6':

            total += 6

        elif rank == '7':

            total += 7

        elif rank == '8':

            total += 8

        elif rank == '9':

            total += 9

    return total

    print (total)

print ("Your current hand is {}".format(user_hand))

print ("This provides you with a total of:")

handtotal(user_hand)

【问题讨论】:

  • 请注意,if rank == "J" or "Q" or "K": 不会按照您的想法行事,请参阅 this question

标签: python function variables printing cumulative-sum


【解决方案1】:

print(total) 放在return total 之后没有多大意义,因为return 会导致函数立即终止并且不计算return 语句后的任何行*。相反,请尝试将 print 放在函数定义之外:

print ("This provides you with a total of:")

print(handtotal(user_hand))

*(try-except-finally 块存在一些极端情况,但大多数情况下都是如此。)

【讨论】:

    【解决方案2】:

    首先回答您的问题:

    没有打印的原因是因为您在打印之前返回了手牌的价值,因此永远不会进入您的打印语句。

    return total #Stops the function
    
    print (total) #Never gets reached
    

    为什么会这样?

    一个简单的思考方法是,一旦你'返回'一个值,你基本上已经告诉 python
    “这就是答案,不需要做任何其他事情,你有你想要的”
    你直接放的任何东西在 return 语句将永远运行之后。

    有多种方法可以解决这个问题:
    A) 将 print 语句移到 return 上方:

    print (total)
    
    return (total)
    

    B) 你只需去掉 print 语句并引用函数的值(这是总数,因为这是返回的值)

        return total
    
    print ("Your current hand is {}".format(user_hand))
    
    print ("This provides you with a total of:" + str(handtotal(user_hand)))
    

    您可以只使用 str() return 语句,但我假设您希望能够在某个时候将该值与经销商的值进行比较。

    现在谈谈您的代码中当前最大的三个问题:

    1st. 您正在使用输入名称。
    -这是非常糟糕的做法,因为用户必须知道他们应该在答案周围加上引号以表示它是一个字符串。

    Please enter your name:russell
    Traceback (most recent call last):
      File "/test.py", line 1, in <module>
        user_name = input("Please enter your name:")
      File "<string>", line 1, in <module>
    NameError: name 'russell' is not defined
    

    解决方案:改用 raw_input()。
    - 这将为您将答案转换为字符串。

    第 2. 行:

    if rank == "J" or "Q" or "K":
    

    不对照“J”、“Q”和“K”检查 rank 的值

    这实际上意味着是:rank == “J” 或是“Q”真实或者是“K”真实

    因为“Q”和“K”是非空字符串,Python 将它们视为 True,这意味着现在您的值将始终为 20,因为无论如何第一个 if 语句将始终为真。

    你真正想要的是:

    if rank in {"J","Q","K"}
    

    但这也行不通,因为:

    3rd. 只是说:

    for rank in hand:
    

    不会让它查看​​排名的实际值。它仍然会查看整个元组。
    例如
    rank = ('Diamond', '7')
    rank != '7'

    解决方案:您实际上想要反转所有 if 语句并使用 'in':

        if "J" in rank or "Q" in rank or "K" in rank:
    
            total += 10
    
        elif 'A' in rank and total < 11:
    
            total += 11
    
        elif 'A' in rank and total >= 11:
    
            total += 1
    
        ...
    


    附言这也只是因为在黑桃、钻石、梅花或红心等词中没有大写字母 A、K、Q 或 J,否则该花色总是会得到这张牌的价值,而不管实际价值如何。但在这种情况下,这不是问题。

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 2017-09-23
      • 2017-12-07
      相关资源
      最近更新 更多