Plurals, If Statement Python
So many questions.. At the moment my code is calculating the cost, number of adults and children. If the user only inputs 1 child I want it to print child, not children. serviceTy
Solution 1:
Use x if ... else y
construction:
defchildren_str(number):
return"{} {}".format(number, 'child'if number == 1else'children')
for i inrange(3):
print children_str(i)
Output:
0 children
1 child
2 children
you can generalize this function:
defpl(number, singular, plural=None):
if plural == None:
plural = singular + 's'return"{} {}".format(number, singular if number == 1else plural)
print (pl(1, 'child', 'children')) # 1 adultprint (pl(2, 'child', 'children')) # 2 childrenprint (pl(1, 'adult', 'adults')) # 1 adultprint (pl(2, 'adult')) # 2 adultsprint (pl(1, 'adult')) # 1 adultprint (pl(5, 'adult', 'adults')) # 5 adults
Solution 2:
If you want the plural and singular to be more general you may consider to use inflect, an python package
Then the conversion will looks like this:
import inflect
conversion_engine = inflect.engine()
defmain():
for count inrange(4):
print format_plural_singular("child",count)
print format_plural_singular("adult",count)
printdefformat_plural_singular(noun,quantity):
return conversion_engine.plural_noun(noun,quantity)
Solution 3:
You can write the print statement like this:
print("That is " + formatCurrency(rare) + " for rare choice for " + str(noAdult) +
(" adult"if noAdult==1else" adults") + " and " + str(noChild) +
(" child"if noChild==1else" children") + ". Enjoy!")
Solution 4:
defpluralize(singular, plural):
deffn(num):
return"{} {}".format(num, singular if num==1else plural)
return fn
children = pluralize("child", "children")
adults = pluralize("adult", "adults")
seniors = pluralize("senior", "seniors")
then
children(0) # => "0 children"
children(1) # => "1 child"
children(2) # => "2 children"
and
def participants(num_seniors, num_adults, num_children):
items = [
(num_seniors, seniors),
(num_adults, adults),
(num_children, children)
]
items = [fn(n) for n,fn in items if n >0]
# joinlast pair of items with "and"
items[-2:] = [" and ".join(items[-2:])]
# joinall preceding items with ","
return ", ".join(items)
participants(1, 2, 1) # => "1 senior, 2 adults and 1 child"
participants(0, 1, 4) # => "1 adult and 4 children"
Solution 5:
I came here looking for a very basic solution that followed a simple rule to add s if the count is more than 1. You can use Python's f-string form to do a simple inline if-statement in the f-string.
print(f"That is {formatCurrency(rare)} for rare choice for {noAdult}
adult{'s'if noAdult != 1else''} and {noChild}
child{'ren'if noChild != 1else''}. Enjoy!"
)
Post a Comment for "Plurals, If Statement Python"