Search code examples
pythonpython-3.xfunctionstring-formattingconditional-formatting

Conditional Formatted Strings in Python


def secondCalculator(days, hours, minutes, seconds):
days = int(input("Days: ")) * 3600 * 24
hours = int(input("Hours: ")) * 3600
minutes = int(input("Minutes: ")) * 60
seconds = int(input("Seconds: "))

allSec = days + hours + minutes + seconds

if days == 1:
    print(f"{days} Days,{hours} Hours, {minutes} Minutes, {seconds} Seconds are equal to {allSec} seconds.")

#### same use of if, for hours, minutes and seconds.

If user enters secondCalculator(0,1,2,5) Output should be: 0 Day, 1 Hour, 2 Minutes, 5 Seconds is equal to 3725 seconds.

When user enters 1 day, it should be printing "day" not "days", same goes for hour, minutes, second. The things is making it with an if is doable yes but i thought maybe there are easier ways to do it.

How can i make it put the "s" suffix depending on the entered number by the user. Can we implement conditional string formatting for it?


Solution

  • Something like this possibly? Might make sense to wrap it in a function:

    >>> days = 1
    >>> f"day{('s', '')[days==1]}"
    'day'
    >>> days = 2
    >>> f"day{('s', '')[days==1]}"
    'days'
    >>>