使用in
运算符:
encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):") in ('d', 'D') else 'e'
或者,您可以将输入转换为小写并将其与“d”进行比较:
encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):").lower() == 'd' else 'e'
最后,如果要确保它们输入 e 或 d,可以将其包装在 while 循环中:
while True:
encrypt = raw_input("Encrypt or decrypt a file (E/d):")
# Convert to lowercase
encrypt = encrypt.lower()
# If it's e or d then break out of the loop
if encrypt in ('e', 'd'):
break
# Otherwise, it'll loop back and ask them to input again
编辑:要回答你的第二个问题,我猜你可以使用 lambda 吗?
file_text = (lambda default, inp: default if inp.lower() == default else inp)("a.txt", raw_input("File name(a.txt):"))
虽然,这显然有点迟钝,也太“聪明”了一半。