Skip to content
Laviyx Learn

Try

Python Functions Practice

Practise writing functions with parameters, return values and default arguments.

Beginner3 problemsUpdated

Review first: Functions

  1. 1.Temperature converter

    Beginner

    Write a function to_fahrenheit(celsius) that returns the temperature in Fahrenheit. Print the result for 0, 37 and 100.

    Show hint

    The formula is celsius * 9 / 5 + 32. Remember to return the value.

    Show solution
    Python
    def to_fahrenheit(celsius):
        return celsius * 9 / 5 + 32
    
    for c in [0, 37, 100]:
        print(c, "->", to_fahrenheit(c))
    Output
    0 -> 32.0
    37 -> 98.6
    100 -> 212.0
  2. 2.Greeting with a default

    Beginner

    Write make_greeting(name, greeting="Hello") that returns a string like Hello, Asha!. Call it once with only a name and once with the greeting "Welcome".

    Show hint

    Build the string with an f-string and return it; print outside the function.

    Show solution
    Python
    def make_greeting(name, greeting="Hello"):
        return f"{greeting}, {name}!"
    
    print(make_greeting("Asha"))
    print(make_greeting("Ravi", "Welcome"))
    Output
    Hello, Asha!
    Welcome, Ravi!
  3. 3.Longest word

    Beginner

    Write a function longest_word(words) that returns the longest string in a list. If two words are equally long, return the first one.

    Show hint

    Keep track of the best word so far and replace it only when you find a strictly longer one.

    Show solution
    Python
    def longest_word(words):
        best = words[0]
        for word in words[1:]:
            if len(word) > len(best):
                best = word
        return best
    
    print(longest_word(["sql", "python", "java", "golang"]))
    Output
    python

    "python" and "golang" both have 6 letters. Because we only replace best when a word is strictly longer, the first one wins. Python's built-in max(words, key=len) behaves the same way.