微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么这不返回任何值?

如何解决为什么这不返回任何值?

我正在尝试制作二十一点游戏

一切正常,直到 if 和 elif 语句...

如果您在您的代码平台中尝试此代码,您将在 if 块中看到 'new_user_card' is none type..

这是为什么?

同样的 elif 块

提前致谢!

    import random
cards = [11,2,3,4,5,6,7,8,9,10,10]
 
def hand():
    user_cards = random.sample(cards,2) 
    print(f"Your cards are : \n {user_cards}")
    computer_cards = random.sample(cards,1)
    print(f"Computer's first card {computer_cards}")
    more = input("Do you want to draw another card? Type 'y' for yes and 'n' for no : ")
    if more == "y":
        new_user_card = print(random.choice(cards))
        user_cards.append(new_user_card)
        print(f"Your cards are : \n {user_cards}")
    elif more == "n":
        computer_new_card = print(random.choice(cards,1))
        computer_cards.append(computer_new_card)
        print(f"Computer's has been dealt the second card.\n Computer's cards are {computer_cards}")
    return user_cards
    return computer_cards
    
hand()

解决方法

print() 函数返回 None,这里您已将 print(random.choice(cards)) 的返回值分配给您的变量。

使用 new_user_card = random.choice(cards) 并添加 print(random.choice(cards)) 在单独的行上(如果需要)。

,

您正在使用 print 函数,该函数打印到标准输出,但返回 None。

去掉函数即可。

例如:

# this is wrong 
# new_user_card = print(random.choice(cards))
new_user_card = random.choice(cards)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?