Functions and Modules Answers¶
Module Exercises¶
Allow Zero Arguments¶
Make a script like our greetings.py file, but allow it to take zero arguments. When no arguments are given, it should say “Hello world!”
Answers
import sys
arguments = sys.argv[1:]
if __name__ == "__main__":
if arguments:
name = arguments[0]
else:
name = "world"
print("Hello {}!".format(name))
CLI Only¶
Make a module that prints “Hello world” when you use it from the command-line, but prints an error message when you try to import it. It should work like this:
$ python hello.py
Hello world
>>> import hello
This module can only be run from the command-line
For bonus points, make the module raise an error when importing instead of just printing a message. You can use this line to raise this error:
>>> raise ImportError("This module can only be run from the command-line")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: This module can only be run from the command-line
Answers
if __name__ == "__main__":
print("Hello world!")
else:
raise ImportError("This module can only be run from the command-line")
Add¶
Make a program add.py that takes two numbers and prints out the sum of these numbers.
$ python add.py 3 5.2
8.2
$ python add.py -7 2
-5.0
$ python add.py -2 -1
-3.0
Answers
import sys
print(float(sys.argv[1]) + float(sys.argv[2]))
Difference Between¶
Make a program difference.py that takes two numbers and prints the positive difference between these two numbers:
$ python difference.py 3 5
2.0
$ python difference.py 6 3.5
2.5
$ python difference.py -7 2
9.0
Answers
import sys
print(abs(float(sys.argv[1]) - float(sys.argv[2])))
Allow Unlimited Arguments¶
Make a script like our greetings.py file that takes any number of arguments. All arguments should be joined together by spaces and printed out.
Your script should work like this:
$ python greetings.py
Hello!
$ python greetings.py world
Hello world!
$ python greetings.py from planet Earth
Hello from planet Earth!
Tip
You may have noticed we did this in an example earlier, but you can get a list of all arguments with sys.argv[1:]. We’ll explain how this works in the next class.
Hint
Use str.join on the sys.argv list.
Answers
import sys
arguments = sys.argv[1:]
if __name__ == "__main__":
if arguments:
print("Hello {}!".format(" ".join(arguments)))
else:
print("Hello!")
Function Exercises¶
Hypotenuse¶
Make a function that returns the hypotenuse of a right triangle given the other two sides. Your function should work like this:
>>> get_hypotenuse(3, 4)
5.0
>>> get_hypotenuse(5, 12)
13.0
Hint: to get the square root of a number, raise it to the power of 0.5.
Answers
def get_hypotenuse(x, y):
return (x ** 2 + y ** 2) ** 0.5
To Celsius¶
Make a function that accepts a temperature in Fahrenheit and returns a temperature in Celsius.
>>> to_celsius(212)
100.0
Answers
def to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9
Is Leap Year¶
Make a function that takes a year and returns True if and only if the given year is a leap year.
- Leap years are years that are divisible by 4
- Exception: centennials (years divisible by 100) are not leap years
- Exception to exception: years divisible by 400 are leap years
You may find this pseudocode from Wikipedia helpful.
Answers
def is_leap_year(year):
if year % 4:
return False
elif year % 400 == 0:
return True
elif year % 100 == 0:
return False
else:
return True
Perfect Square¶
A perfect square is a number which is the square of an integer. For example 25 (5 * 5), 49 (7 * 7) and 81 (9 * 9) are all perfect squares.
Make a function that returns True if the given number is a perfect square.