首页 > 解决方案 > 如何在 Python 中将随机生成的变量保存到程序中?

问题描述

在我的代码中,我对其进行了设置,以便它将随机分配一个 1-15 的值给玩家。我想知道如何“保存”相同的值,以便可以在游戏的其他部分使用它来确定整个游戏中的事件和其他内容。

仅供参考,我在前面的代码中导入了 tkinter、time 和 random。下面的代码也可以正常工作。

print(name + "now gets different points assigned their characteristics.")
print("Characteristic strength is based out of 15.")
print("i.e. 14/15 INTELLIGENCE")
time.sleep(3)

print(name + "'s INTELLIGENCE, ATHLETIC ABILITY, CREATIVITY, COMMUNICATIONS, and LOGIC.")
time.sleep(3)

print("Intelligence")
print(random.choice(intelligence))
time.sleep(2)

print("Athletic Ability")
print(random.choice(athletic_ability))
time.sleep(2)

print("Creativity")
print(random.choice(creativity))
time.sleep(2)

print("Communications")
print(random.choice(communications))
time.sleep(2)

print("Logic")
print(random.choice(logic))
time.sleep(2)

标签: pythonvariablessave

解决方案


您可以设置范围数量的列表,然后将其分配给一个值并保存以供以后使用。

import random

intelligence_levels = list(range(1,16,1)) # function range params are start, stop , step where stop number does not included in the list

player_int = random.choice(intelligence_levels)

randomized = []

randomized.append(player_int)

推荐阅读