字典真/假错误

时间:2016-04-01 00:24:54

标签: python python-3.x

我试图让用户更改字典的值,我的字典如下:

   d = {'gary:' : 'B','john:': 'C',}

每当我为nameedit输入输入' gary:'(用分号加数)时,为什么变量将始终为true,但无论如何,它都会将值读为none并且永远不会到达字母等级(inpu)的第二个输入

    nameedit = str(input("Which student do you wish to edit the grade of?"))  
    why = print(nameedit in d)
    if why == None:
        print("That student doesn't exist")
    else:
        inpu = str(input("Enter new letter grade: A,B,C,D,F,"))
        d[nameedit] = inpu 
        print(d)          

我还尝试了一些变体,例如如果nameedit == True:和具有相同问题的else,print语句将产生True,但它将继续执行else语句。我还在d:

中尝试了一个elif nameedit
  why = print(nameedit in d)
    if nameedit in d == True:
        inpu = str(input("Enter new letter grade: A,B,C,D,F,"))
        d[nameedit] = inpu 
        print(d)            
    else:
        print("That student doesn't exist")

,但无济于事。是否无法获取print语句正在读取的值?我的最终目标是简单地检查名称是否在字典中,如果是,继续,如果它不是,停止

python v 3.5

4 个答案:

答案 0 :(得分:0)

使用:

why = nameedit in d
if why:
    inpu = str(input("Enter new letter grade: A,B,C,D,F,"))
    d[nameedit] = inpu 
    print(d)     
else:
    print('Does not exists')

答案 1 :(得分:0)

nameedit in d返回TrueFalse,永不返回None。包裹在print(总是返回None)只是荒谬的。

删除print包装,并将测试更改为if not why:或只是将测试移入条件本身:

nameedit = input("Which student do you wish to edit the grade of?")
if nameedit not in d:
    print("That student doesn't exist")
else:
    d[nameedit] = input("Enter new letter grade: A,B,C,D,F,")
    print(d)

我删除了不必要的str换行(input已经在Py3中返回str,以及不必要的中间本地人。

答案 2 :(得分:0)

print()只是将输出放到屏幕上;它不会返回打印的内容。如果您要将why分配给nameedit in d 的结果并打印它;分开来做:

why = nameedit in d
print(why)

另外,if ...看到...True。使用if ... == True查看是否... == True == True。这是多余的。就这样做:

why = nameedit in d
print(why)
if why:
    inpu = input("Enter new letter grade: A,B,C,D,F,")
    d[nameedit] = inpu 
    print(d)            
else:
    print("That student doesn't exist")

我还删除了input(...)到字符串的转换。它已经返回一个字符串,因此转换是多余的。

答案 3 :(得分:0)

使用就像:

if why in d:

if why not in d:

您不需要使用两个字符串。此外,您可以通过get获得价值:

d = {'gary:' : 'B','john:': 'C',}

name = str(input("Which student do you wish to edit the grade of?\n"))

value = d.get(name, None)

if not value:
    print("That student doesn't exist: {0}: [1}".format(name, value))
else:
    value = str(input("Enter new letter grade: A,B,C,D,F \n"))
    d[name] = value.upper()
    print(d)