We've all been there, I believe one good way to get better at this would be first to analyze the problem and find a pattern in the data your program expects. One pattern that's noticeable is:
- The user always inputs a string (because "22hr, 2m, 4d" are alpha-numeric values)
- A valid input would always have numbers and alphabets (hr, m, s, d) in it
- A valid input would always start with a number
These are some of the patterns you can bring out from the problem. Now for the solution:
- validate your input starts with a number ( you can make other validations at the top)
if amount[0].isnumeric():
# remaining logic here
This eliminates the need to keep repeating yourself on every elif
- Next, set a list of dictionaries of allowed alphabetical characters, their unit and their numerical value
timeOptions = [
{ 'shortcode': 'm', 'unit': 'minutes', 'value': 60 },
{ 'shortcode': 's', 'unit': 'seconds', 'value': 1 },
{ 'shortcode': 'hr', 'unit': 'hours', 'value': 3600 },
{ 'shortcode': 'd', 'unit': 'days', 'value': 86400 },
]
- Next filter the numerical values from the string
number = ''.join(filter(str.isdigit, amount))
- Filter the alphabet values from the string
shortcode = ''.join(filter(str.isalpha, amount))
Finally from your dictionary, find the dictionary entry whose shortcode property matches the unit from the user's input. For this, you can use list comprehension
timeValue = [x for x in li if x["shortcode"] == shortcode ][0] # refactor to check list length before attempting to access the first item
finally, you can do whatever you want with the user's input and the timeValue
dictionary.
amount = amount * timeValue["value"]
unit = timeValue["unit"]
The entire program might look like this:
if amount[0].isnumeric():
timeOptions = [
{ 'shortcode': 'm', 'unit': 'minutes', 'value': 60 },
{ 'shortcode': 's', 'unit': 'seconds', 'value': 1 },
{ 'shortcode': 'hr', 'unit': 'hours', 'value': 3600 },
{ 'shortcode': 'd', 'unit': 'days', 'value': 86400 },
]
number = ''.join(filter(str.isdigit, amount))
shortcode = ''.join(filter(str.isalpha, amount))
timeValue = [x for x in li if x["shortcode"] == shortcode ]
if len(timeValue):
return False
else:
timeValue = timeValue[0]
amount = amount * timeValue["value"]
unit = timeValue["unit"]