如何解决为什么这不返回任何值?
我正在尝试制作二十一点游戏
一切正常,直到 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 举报,一经查实,本站将立刻删除。