Skip to content

Exercises

6.1 — Write two functions to_fahrenheit(c) and to_celsius(f) for converting between celsius and fahrenheit degrees respectively. The functions should return the converted value.

6.2 — Write a function, is_even(n), that test if a number is even and returns a Boolean. Use the function in an if statement to test a number read from the user and print whether it is even or not.

6.3 — Write a function, largest(), that takes one or more numbers and returns the largest. Do not use the built-in max(). Use it on different combination of inputs, including inputs containing ties.

6.4 — Write a function, greet(name, times=1), that prints the greeting times times (default once). Call it using different combination of arguments: default, positional and keyword arguments.

6.5 — Write a function, initials(full_name), that returns the initials, capitalized. Then write main() that reads a name from the user and prints their initials to the screen.

6.6 — Write a function, password_strength(pw), that takes a string and returns "weak", "medium", or "strong" based length and whether it contains a digit. However, if the password consists of only digits, it should be reported as "weak".

6.7 — Write a function, fibonacci(n), that returns the nth fibonacci number. Write another function, fibonacci_series(n) that uses fibonacci(n) and returns first n fibonacci numbers.

Hints
  • 6.3 — start largest = a; compare against b and c, updating; return largest.
  • 6.4 — a for _ in range(times): loop inside the function.
  • 6.5 — split the name into individual words, the take the first character in each word.
  • 6.6 — use any(c.isdigit() for c in pw) to check for the presence of digits.

Coding challenge — Unit converter

  1. Write the following unit conversion functions are pure functions, each with a docstring and a return (no print inside):
    1. c_to_f
    2. f_to_c
    3. km_to_miles
    4. miles_to_km
    5. kg_to_lb
    6. lb_to_kg.
  2. Write a main() that shows a menu, reads the user's choice and a value, then calls the right function, and prints a nicely formatted result (rounded to 1 decimal places).
  3. Display the menu in an infinite loop until the user chooses "quit" to end the program.

Example usage:

Select an option below:

1. Celsius to fahrenheit
2. Fahrenheit to Celsius
3. Kilometers to miles
4. Miles to kilometers
5. Kilograms to pounds
6. Pounds to kilograms
7. Quit

> 1

Enter a temperature in Celsius: 100

100.0 C = 212.0 F

Select an option below:

1. Celsius to fahrenheit
2. Fahrenheit to Celsius
3. Kilometers to miles
4. Miles to kilometers
5. Kilograms to pounds
6. Pounds to kilograms
7. Quit

> 7

Goodbye!