Skip to main content
 首页 » 编程设计

python之我们可以让 python 从 raw_input() 内置函数中获取变量而不是字符串吗

2025年05月04日11zfyouxi

我想知道是否可以让 python raw_input() 为我获取变量调用。

我的理解是,raw_input() 接受其中写入的任何注释并将其转换为字符串,很像 %r,它只是打印我输入的所有内容理解为格式化的 Debug模式字符串。

但是如果我们尝试转换这样的东西:

test1 = int(raw_input("Please write some number:>  ")) 
print test1 * 100 

如果我们输入 100,下一行将对其执行计算功能,这是我非常有兴趣实现的东西,但是以这种方式:

这不是错误的尝试,而是给出我想要什么的一般概念

a = "I will like some candies" 
b = "I will like some chocolates" 
c = "I will rather die but have fried chicken"  
test2 = raw_input("Please write the variable name you want to print" 

如果这是 python 接受输入的方式,例如当输入为 a 时,我们将打印 a 等等 b 和 c 等

在 python 中有没有一种方法可以让程序以变量而不是字符串的形式从我们这里获取输入。任何转换?

提前感谢大家的帮助...

请您参考如下方法:

不,正如您所说,raw_input 返回一个字符串。如果您想根据用户输入返回相关结果,最好的方法是使用字典将您的变量名映射到它们的值:

my_dict = {'a': "I will like some candies" 
           'b': "I will like some chocolates" 
           'c': "I will rather die but have fried chicken" } 
 
test2 = raw_input("Please write the variable name you want to print" 
warning = "Please choose one of the aforementioned choices (a, b, c)" 
print my_dict.get(test2,warning)