uyin
uyin

Reputation: 19

Python input() for ENTER

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?

Upvotes: 0

Views: 559

Answers (1)

wjandrea
wjandrea

Reputation: 33145

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

Upvotes: 1

Related Questions