有没有办法通过迭代创建变量?

寄生虫先生9445

所以我试图为在线二十一点程序编写代码,但我在编程时遇到了麻烦,因为我需要使用从列表中随机抽取的最多 11 个变量进行计算。现在,我对该部分的代码是:

while user_card_total_one <= 21:
    user_move = input("Would you like to stand or hit? ")
    user_move = user_move.lower()
    if user_move == "stand":
        break
    elif user_move == "hit":
        user_card_three = random.choice(deck)
        deck.remove(user_card_three)
        a_or_an_one = " a "
        if user_card_three == 8 or user_card_three == "Ace":
            a_or_an_one = " an "
        print("You were dealt" + a_or_an_one + str(user_card_three) + ".")
        if type(user_card_three) == str and user_card_one != "Ace":
            user_card_one = 10
        if user_card_three == "Ace":
            user_card_total_one = user_card_total_one + 1
            user_card_total_two = user_card_total_two + 11
            if user_card_total_two > 21:
                print("Your card total is " + str(user_card_total_one) + ".")
            else:
                print("Your card total is " + str(user_card_total_one) + " or " + str(user_card_total_two) + ".")
        else:
            user_card_total_one = user_card_total_one + user_card_three
            user_card_total_two = user_card_total_two + user_card_three
            print("Your card total is " + str(user_card_total_one) + ".")
        if user_card_total_one > 21:
            print("Unfortunately, you busted and lost.")
            print("The dealer has collected your bet.")
            bust = True
            break
    else:
        print("Sorry, thats not a valid input, please try again.")

现在,我可以多次编写此代码,以便考虑用户决定执行的操作,但代码中唯一的更改将是变量名称。我想知道是否有某种方法可以使这个for循环成为变量name依赖于 i循环我尝试使用字典:

card = {
    1: "Ace",
    2: "King",
    3: 2
}
card = 1
for i in range (10):
    print(card[card])
    card = card+1

但这似乎没有帮助。这是我必须使用蛮力的东西,还是我缺少的更简单的方法?

编辑:抱歉,我在第二部分使用了一些错误的代码,现在已更新

肖恩·拉米雷斯

我相信您想在字典中的键命名中使用迭代器?这看起来怎么样?

length=10
cardDict=dict()

for i in range(length):
    objectname = "Card "+str(i)
    cardDict[objectname]="number "+str(i)
print (cardDict)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有没有办法创建全局 CSS 变量?

有没有办法通过声明组成其键值对的变量来创建字典?

有没有办法从python中的迭代输出实例化变量?

有没有办法让迭代器变量大于某物而小于某物?

有没有办法在 Tkinter 中迭代地创建和垂直打包按钮?

有没有办法迭代整数范围?

有没有办法确保循环迭代不同?

有没有办法通过spring-boot访问通过KSQL(kafka)创建的表?

有没有办法通过变量从对象中获取信息?

有没有办法通过 JMeter 中的 csv 文件传递用户定义的变量?

有没有办法在c#中通过名称访问变量的引用

有没有办法通过给定的字符串获取变量

有没有办法通过变量设置NLog记录器的最小级别?

有没有办法通过Monit配置传递环境变量

有没有办法通过foreach语句传递变量/ $ _POST?

有没有办法通过div id传递php变量?

有没有办法在视图创建期间通过数据绑定读取视图属性?

有没有办法通过kotlin-extensions更改自动创建的视图的名称?

有没有办法通过 API 调用创建 Pusher App?

有没有办法针对通过克隆节点创建的项目分配唯一的ID?

有没有办法压缩通过 php 创建的 html 输出?

有没有办法通过API创建Facebook事件,因为图形API不再可用

有没有办法通过JavaScript从innerText创建单个单词的数组?

有没有办法通过 boost::process::spawn 记录进程创建的输出?

有没有办法在Swift中仅通过JSON部分创建对象?

有没有办法通过网页创建和编辑信封?

有没有办法通过Android应用程序创建键盘宏?

有没有办法通过 for 循环创建数组元素?

有没有办法通过 Youtrack API 使用非标准模板创建项目?