-1

I have

term = input("Enter a variable name")  #choose the term (i.e.,day,week,month)

and in my code there is a section as below

date.term

I like users can input 'month' or 'year' and the code can function as

date.month

or

date.year

How can I do this. Thank you in advance for your time and help.

Samtry
  • 35
  • 4

1 Answers1

1

Use if statements to read the user input:

if term == 'day':
   # something using date.day
elif term == 'month':
   # something using date.month
elif term == 'year':
   # something using date.year
else:
   print(f'Invalid term: "{term}"')

Alternatively, if you trust the user input, you could use exec():

exec(f'print("date.{term}")')
Ari Cooper-Davis
  • 3,374
  • 3
  • 26
  • 43