首页 > 解决方案 > 在 python 中执行代码时可以创建新变量吗?

问题描述

你可以在 python 脚本打开时创建新变量吗?

例如,如果您有无限选择,您可以为每个选择创建一个新变量吗?就像如果您选择 answer1 它将创建一个新变量 choise1 = answer1,然后如果您选择 answer3 之后它将创建一个新变量 choise2 = answer3,并且只要您愿意,无需在其中创建变量手写代码。

提前致谢,如果问题有点令人困惑,我真的不知道该怎么说 100%

标签: python

解决方案


使用循环和字典来创建无限变量。这是我写的一些快速代码。我希望它能让你走上正轨!

variables = {}

while True:
    choice = input('Enter a choice: ')
    answer = int(input('Enter an number: '))

    variables[choice] = answer

    next_ = input('Continue? (y/n) ')
    if next_.lower() == 'n':
        break


print(variables)

推荐阅读