我正在研究一个随机事实生成器,该生成器采用一个随机生成的数字(在本例中为1 -10)并将该数字分配给一个告诉用户随机事实的字符串输出。
到目前为止,这是我能够将所有代码组合在一起的全部内容:
#Greeting
a = "Hello, who am I speaking to?"
print("Welcome, " + input(a) + "!" + " Lets see what fact you rolled...")
#Random Number Generator
import random
for x in range (1):
randomNumber = random.randint(1, 10)
print(randomNumber)
#Loop function
def check_val(randomNumber, title, answer):
while True:
if input(randomNumber) == title:
print(answer)
break
else:
print("I dont know.")
#Facts
def fact():
randomNumber, answer = {}, {}
randomNumber[1] = ([1])
answer[1] = "Fact1"
randomNumber[2] = ([2])
answer[2] = "Fact2"
randomNumber[3] = ([3])
answer[3] = "Fact3"
randomNumber[4] = ([4])
answer[4] = "Fact4"
randomNumber[5] = ([5])
answer[5] = "Fact5"
for k in randomNumber:
check_val(randomNumber[k], k, answer[k])
fact()
运行此代码时,我得到以下输出:
你好,我在跟谁说话?j 欢迎光临,j!让我们看看你的事实... 5 [1]
我无法获取该随机整数(5)并将其分配给随机事实#5。
关于如何将这些随机整数分配给可用输出的任何想法?
答案 0 :(得分:2)
嘿,您在这里有很多事情要做,您可以使用list
来简化事实,以存储您的事实,这是您可以借鉴的更好格式。
如@JonClements所述,我们可以使用random.randrange(len(facts))
,如果我们想更改列表中的事实数量,这将使我们的代码更具适应性。
import random
while True:
name = input("\nHello, Who am I speaking to?\n")
print(f"\nWelcome, {name}! Lets see what you rolled..."
facts = [
'Fact one',
'Fact two',
'Fact three',
'Fact four',
'Fact five',
'Fact six',
'Fact seven',
'Fact eight',
'Fact nine',
'Fact ten'
]
selection = random.randrange(len(facts))
print(facts[selection])
答案 1 :(得分:0)
#Greeting
a = "Hello, who am I speaking to?"
print("Welcome, " + input(a) + "!" + " Lets see what fact you rolled...")
#Random Number Generator
import random
for x in range (1):
randomNumber = random.randint(1, 10)
print(randomNumber) <--- your printing 5
#Loop function
def check_val(randomNumber, title, answer):
while True:
if input(randomNumber) == title: <--- answer argument which were passed was [1] remember so it asks you to write something with the text [1]
print(answer)
break
else:
print("I dont know.")
#Facts
def fact():
randomNumber, answer = {}, {} <--- your 5 nol longer exist because you now overwrote it with a dict
randomNumber[1] = ([1])
answer[1] = "Fact1"
randomNumber[2] = ([2])
answer[2] = "Fact2"
randomNumber[3] = ([3])
answer[3] = "Fact3"
randomNumber[4] = ([4])
answer[4] = "Fact4"
randomNumber[5] = ([5])
answer[5] = "Fact5"
for k in randomNumber: <--- # now it's iterating over the dict, and since you wrote 1 first that is most likely to be the one it finds first in the memory though there no order here
check_val(randomNumber[k], k, answer[k])
fact()