mardi 3 avril 2018

Hour of Python Trinket Number of Things challenge

I was doing the "Number of Things" challenge on the Hour of Python Trinket website (https://hourofpython.trinket.io/python-challenges#/string-challenges/number-of-things-challenge) and was able to follow a tutorial on The Clever Programmer youtube channel to help.

The challenge creates a sentence which pluralizes depending on the [0] int in the list. In the [1] slot, the string "trinket" would be returned as "trinkets" adding an 's' at the end.

To take it a step further, I wanted to add a line that would see a word that ends in 's' (in my example 'boss') and add 'es' instead of 's'. I tried using an elif statement after the first if statement but it keeps appending "s". I would like the first statement to say "There are 5 bosses"

I'm a novice learning Python now. Please be gentle haha.

# Make a function how_many that, given a list of a number
# and a thing name, returns a grmmatically correct sentence
# describing the number of things.
#
# >>> how_many([5, "trinket"])
# There are 5 trinkets.
# >>>> how_many([1, "king"])
# There is 1 king.


def how_many(the_list):
  # Add code here that returns the answer
  dg = str(the_list[1])
  if the_list[0] > 1:
    return "There are " + str(the_list[0]) + ' ' + the_list[1] + 's'
  elif dg[-1] == "s":
    return "There are " + str(the_list[0]) + ' ' + the_list[1] + 'es'
  else:
    return "There is " + str(the_list[0]) + ' ' + the_list[1]

# Add print statements here to test what your code does:"""
print how_many([5, "boss"])
print how_many([1, "king"])

______

Prints: There are 5 bosss There is 1 king

Aucun commentaire:

Enregistrer un commentaire