Python如何将用户输入的整数存入字典以便后续调用?
修正后的可运行代码
# 分开定义两个不同用途的字典,避免重名覆盖 input_dict = { 'a': int(input("type number here:")), 'b': int(input("type number here:")) } prompt_dict = { 'Correct': 'you are correct', 'Incorrect': 'you are incorrect' } # 直接从字典取值计算和 total = input_dict['a'] + input_dict['b'] if total == 3: print(prompt_dict['Correct']) else: print(prompt_dict['Incorrect'])
关键修改说明
- 拆分了重名的字典:原来两次定义
Dict会导致前面的输入存储字典被后面的提示字典覆盖,这里分别命名为input_dict(存储用户输入)和prompt_dict(存储提示文本),避免冲突 - 直接把输入逻辑写进字典值的位置,不需要提前声明空的
a、b变量,后续需要调用输入值的时候直接取input_dict['a']、input_dict['b']即可 - 修正了赋值符号错误:原来的
sum == a + b是比较运算,改成=赋值即可,另外建议不要用sum作为变量名,这是Python内置函数的名称,容易导致后续冲突,这里换成了total - 修正了代码缩进问题,删除了不必要的前置缩进
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

