python - 如何让用户名成为计算机可以使用和读取的变量?
问题描述
这个项目非常简单。它要求用户输入一些数字,用它们进行一些数学运算,然后将其吐出。但是,我希望用户可以选择保存他们的结果值,命名它,然后能够将该变量用作数字值。例如:如果用户输入1 2 3
并决定将它们相加,他们会得到6
. 然后,用户决定调用他们的 sum var
。我希望用户可以输入var 7 8
等于6 7 8
because var = 6
。另外,这是我的第一个 Python 项目,所以如果这个问题看起来不寻常,我深表歉意。
我想出了如何将用户输入的结果记录为变量。这显示在该#Save
部分下方。numbers
接受浮点数或整数,因此字符串无法通过(如果我错了,请纠正我。)问题之一是我不知道如何让 Python “记住”循环之间用户变量的值。我也不知道如何numbers
接受所说的用户变量作为数字。
#Loop
repeat = True
while repeat:
#Input
directions = print("Type in some numbers. Use spaces to indicate multiple numbers. Integers, decimals, and negatives are accepted.")
numbers = [float(x) or int(x) for x in input().split()]
print(numbers)
choice = input("Do you wanna choose between '+', '*', '-', or '/' ? Note that values will be subtracted or divided in order that they appear in the list")
#Math
#Addition
if choice == '+':
_sum = sum(numbers)
print(_sum)
#Multiplication
elif choice == '*':
one = 1
for x in numbers:
one *= x
print(one)
#Subtraction
elif choice == '-':
if len(numbers) > 0:
diff = numbers[0] - sum(numbers[1:])
print(diff)
#Division
elif choice == '/':
self = numbers[0]
for x in numbers[1:]:
self /= x
print(self)
#Saves
save = input("Do you wanna save the value of the result you just got? Type in 'yes' or 'no'")
if save == 'yes':
result = input("Is your result a sum, product, difference or a quotient? Use '+', '*', '-', or '/' to answer")
if result == '+':
rename = input("Give your result a name:")
user_sum = globals()[rename] = _sum
elif result == '*':
rename = input("Give your result a name:")
user_pro = globals()[rename] = one
elif result == '-':
rename = input("Give your result a name:")
user_dif = globals()[rename] = diff
elif result == '/':
rename = input("Give your result a name:")
user_quo = globals()[rename] = self
#Kill
kill = input("To kill this program type in 'kill' To continue just press enter")
if kill == 'kill':
repeat = False
解决方案
您可以使用 dict 来存储变量名称和值。dict 将键映射到值,因此它应该完全按照您的意愿工作。
声明一个字典:variables = {}
.
在字典中设置键/值:variables[var_name] = var_value
.
检查 dict 是否包含键:var_name in variables
.
从字典中的键获取值:(variables[var_name]
如果没有键则抛出 KeyError var_name
)或variables.get(var_name)
(如果没有键则返回 None var_name
)。
您可以在https://www.w3schools.com/python/python_dictionaries.asp中阅读有关 Python dicts 的更多信息
推荐阅读
- python - 需要帮助:无法以条形图的 x 刻度获取日期时间
- file - Xamrin Forms:如何读取存储在设备外部存储中的文件的详细信息?
- powershell - 有没有办法确定exe是32位还是64位?
- gradle - 无法解析配置 ':runtime' 的所有文件。找不到 org.grails:grails-datastore-core:7.0.2
- python - 具有最近邻的 Scipy 仿射变换
- javascript - 使用 Google Analytics 的 Firebase 项目在超过 24 小时后未显示任何数据
- python - 如何修复 discord.py 中的“未解决的引用‘消息’”?
- pandas - 当布尔表达式中至少一个变量为 NaN 时,在数据帧中保留 NaN
- computer-vision - 这种在pytorch中计算top-5准确率的方法正确吗?
- c# - 如何在 C# 中订阅 snmpclient(打印机)