【问题标题】:Save/Store a randomly generated value保存/存储随机生成的值
【发布时间】:2021-01-25 10:43:06
【问题描述】:

我有一个非常简单的代码,可以从列表中随机选择一个音乐键。

我如何存储该值,以便程序从那时起就知道所选的键?

import random
majorkeys = ['A major', 'Bb major', 'B major', 'C major', 'Db major', 'D major', 'Eb major', 'E major', 'F major',
             'Gb major', 'G major', 'Ab major']
minorkeys = ['A minor', 'Bb minor', 'B minor', 'C minor', 'Db minor', 'D minor', 'Eb minor', 'E minor', 'F minor',
             'Gb minor', 'G minor', 'Ab minor']
allkeys = majorkeys + minorkeys

#Lydia - in reference to Lydian Mode.
print("""
Hey there, my name is Lydia,
I'm here to help you start a song!
    """)

knownkey = (input("Do you know what key you would like to start with? "))

if knownkey == "no":
    print("\nLet me help you get this song off the ground! Try start with:")
    print(random.choice(allkeys))
else:
    print("That's a great starting point! Nice Work!")

confirmkey = (input("Are you happy to continue with this key? "))
while confirmkey == 'no':
    print("No worries! Lets do:")
    print(random.choice(allkeys)+" instead!")
    confirmkey = (input("Are you happy to continue with this key? "))

if confirmkey == "yes":
    print("Great!")

【问题讨论】:

  • 您可以在打印之前简单地将值分配给变量。

标签: python python-3.x random


【解决方案1】:

你必须像这样将它保存到一个新变量中:

chosenKey = random.choice(allkeys)

然后当你需要打印它时使用:

print(chosenKey)

【讨论】:

  • 当我在此语句之后运行 print(chosenKey) 时。它提供了一个不同的随机生成的。
  • 但是你的代码中还有print(random.choice(allKeys))吗?如果这样做,您首先打印一个随机选择的键,然后选择另一个,最后显示第二个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多