2

I have a menu that will return 'e' unless the input is d or D. I would like to do it without making another variable and doing it on one line

encrypt = 'd' if (raw_input("Encrypt or Decrypt a file(E/d):") == ('d' or 'D')) else 'e'

[Edit] Ok here is a harder one

How can I do the same for this

file_text = 'a.txt' if (raw_input("File name(a.txt):")=='a.txt' else [What I typed in]
2
  • 6
    Why one line? It makes your code harder to understand for most people Commented Apr 3, 2012 at 19:49
  • @BryanOakley It looks too drawn out if it is encrypt = raw_input("Encrypt or Decrypt a file(E/d):" if encrypt != 'd' or encrypt != 'D': encrypt != 'e' I also like to look for unusual and different ways to do programing Commented Apr 3, 2012 at 20:19

2 Answers 2

3

Use the in operator:

encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):") in ('d', 'D') else 'e'

Alternatively, you can just convert the input to lowercase and compare it to 'd':

encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):").lower() == 'd' else 'e'

Finally, if you want to ensure that they enter e or d, you can wrap it up in a while loop:

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

Edit: To answer your second question, you can use a lambda for it I guess?

file_text = (lambda default, inp: default if inp.lower() == default else inp)("a.txt", raw_input("File name(a.txt):"))

Although, this is clearly a bit obtuse and too "clever" by half.

Sign up to request clarification or add additional context in comments.

3 Comments

You can also try raw_input("...").lower() == 'd'.
I was thinking the same thing, but I figured I'd try staying closer to the original snippet.
@AlexVidal I dont like loops for simple yes or no inputs. Instead I like to check the input if non-default [do stuff] else its the default
1

Not really meant seriously but another 1-line solution (I don't think it's readable):

encrypt = {'d':'d','D':'d'}.get(raw_input("Encrypt or decrypt a file (E/d):"), 'e')

At least it's short. Sometimes a dictionary is actually useful for similar situations (if there are more choices).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.