首页 > 解决方案 > 如何让用户名成为计算机可以使用和读取的变量?

问题描述

这个项目非常简单。它要求用户输入一些数字,用它们进行一些数学运算,然后将其吐出。但是,我希望用户可以选择保存他们的结果值,命名它,然后能够将该变量用作数字值。例如:如果用户输入1 2 3并决定将它们相加,他们会得到6. 然后,用户决定调用他们的 sum var。我希望用户可以输入var 7 8等于6 7 8because 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

标签: pythonpython-3.x

解决方案


您可以使用 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 的更多信息


推荐阅读