0

What is input for ENTER key?

tf_end=str(input("TF end: "))
tfend={"":7,'1':0,'2':1,'3':2,'5':3,'10':4,'15':5,'30':6,'1h':7}
while not any(x in tfend.keys() for x in tf_end):  
      tf_end=str(input("TF end: "))

Because I do above logic but "" is not equal to ENTER (cannot escape while loop). How to escape this while loop by using ENTER key?

3
  • Hint: list('') == [] and any([]) == False Commented Jun 12, 2021 at 23:12
  • Note, str(input(...)) is redundant. input always returns a str Commented Jun 12, 2021 at 23:50
  • @juanpa.arrivillaga might be a bad habit left over from Python 2. Commented Jun 13, 2021 at 1:46

1 Answer 1

1

When you only press Enter, input() returns the empty string. Your code doesn't work because any() of an empty iterable is False. Also note that it only happens to work for the multi-character keys because their first characters are also keys.

It looks like you're using any() by accident. Use if not tf_end in tfend instead.

I would make a few other changes too:

tfend = {'': 7, '1': 0, '2': 1, '3': 2, '5': 3, '10': 4, '15': 5, '30': 6, '1h': 7}
tf_end = None  # Sentinel value instead of a duplicate `input()`
while not tf_end in tfend:  # `.keys()` is implied
    tf_end = input("TF end: ")  # `str()` is redundant
Sign up to request clarification or add additional context in comments.

2 Comments

Cannot work..how to declare ENTER into list?
@uyin What do you mean?

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.