Joseph_Wesleyan
Joseph_Wesleyan

Reputation: 35

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?

Upvotes: 0

Views: 66

Answers (3)

Sarthak Rout
Sarthak Rout

Reputation: 137

Define:

def s(val):
        if val > 1:
            return "s"
        return ""

And use it as:

print(f"{days} Day{s(days)}

Upvotes: 1

Paul M.
Paul M.

Reputation: 10809

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'
>>> 

Upvotes: 2

Hunter
Hunter

Reputation: 315

Use:

if days > 1:
    suffix_day = 'days'
elif days == 0:
    suffix_day = 'days'
else:
    suffix_day = 'day'

then use:

print(f'{days} {suffix_day})

Upvotes: 1

Related Questions