【问题标题】:append random choice to list and print only random choice将随机选择附加到列表并仅打印随机选择
【发布时间】:2020-10-06 10:18:47
【问题描述】:

我真的是 python 新手,我正在尝试创建一个小型 ouija 游戏。

我有一个随机选择的数字(年龄)列表 我想将该随机选择附加到一个空列表并仅输出随机选择编号 但是,当我运行我的代码时,它会输出原始列表中的所有内容,但是 if else 似乎可以输出正确的文本,如下所述,但会列出原始列表中的每个数字

有人可以帮忙吗?

import random

#create list of random ages
age=["12,78,14,43,54,33,23,5,85,20,54,13"]

#user input
spirit2=input("Ask me how old I am: ")

#creat empty list of what will be the random age
agenum=[]

def checkage():

    #generate random age from the list age
    agespirit=random.choice(age)
    #append the random age to the to the agenum list
    agenum.append(agespirit)

    #print to terminal
    if "12"  in agespirit:
        print("I am only",agenum,"years old")
    else:
        print("I am",agenum,"years old")

checkage()

【问题讨论】:

    标签: python list random append


    【解决方案1】:

    您有一个包含单个字符串的列表,而不是包含多个字符串的列表:

    age=["12,78,14,43,54,33,23,5,85,20,54,13"]
    

    您可以通过print(len(age)) 确认。

    此列表包含一个大字符串。

    你想要的是这个:

    age=["12","78","14","43","54","33","23","5","85","20","54","13"]
    

    【讨论】:

    • 谢谢你,真不敢相信我忘了做这么简单的事情。现在工作!
    【解决方案2】:
    ages = [12,3,3,56,23,4]
    # list of no. = ages
    import random 
    a = input("Ask me no. : ") # asked the user about the no. he want
    b = []
    c = random.choice(ages) # here I chosea random no. from ages == c and then stored that no. in b
    b.append(c)
    print(b)
    if 12 in b:
      print(f'I am only {b} years old') # it was realy hard to get this output because of random function
    else:
      print(f'I am  {b} year old')
    # I hope this will help, I didn't create a function. 
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 2018-05-22
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2010-09-08
      相关资源
      最近更新 更多