Reputation: 51
I've recently taken to learning list comprehension and have found it extremely useful. However, I just now ran into the fact that I apparently cannot chain if statements with inputs - not sure what the syntax on this is. For example, this previous dictionary-append code I had made works fine (in which the if else clause is only to make it add \n into the statement when the first input has passed:
key = list(
str(input(f"Please enter a Key for value {x + 1}: "))
if x == 0
else str(input(f"\nPlease enter a Key for value {x + 1}: "))
for x in range(3))
However, when writing a code to append the date to a list through comprehension I learned that I cannot just write:
date = list(str(input('Please enter the year: '))
if x == 0 str(input('Please enter the year: '))
elif x == 1 else str(input('Please enter the day: '))
for x in range(3))
So I'm just wondering how to write:
date = []
for i in range(3):
if i == 0:
date.append(str(input("Please enter the year: ")))
elif i == 1:
date.append(str(input("\nPlease enter the month: ")))
else:
date.append(str(input("\nPlease enter the day: ")))
Using list comprehension.
Upvotes: 0
Views: 94
Reputation: 27018
Here are two methods. In my opinion, the loop is better if only because it's more readable. I have no doubt that others will disagree but here goes anyway:
date = []
for t in ['year', 'month', 'day']:
v = input(f'Please enter the {t}:')
date.append(v)
print(date)
date = [input(f'Please enter the {t}:') for t in ['year', 'month', 'day']]
print(date)
Upvotes: 1