Programming from zero

Write is_valid_port(n)

easyFunctions Must-do

Problem statement

Write a function is_valid_port(n) that returns True if n is a valid TCP port number (from 1 to 65535, inclusive) and False otherwise. Then print the result for 8080 and for 70000.

Examples

Example 1

Input: is_valid_port(8080)

Output: True

Example 2

Input: is_valid_port(70000)

Output: False

Explanation: 65535 is the highest possible port.

Hints

Approach

Optimal

A function is a named, reusable block of code. def is_valid_port(n): creates it, and n is a parameter, a placeholder for whatever value the caller passes in. The body computes the answer and hands it back with return. Here the comparison 1 <= n <= 65535 already produces True or False, so you can return it directly instead of writing an if/else. Returning a value, rather than printing inside the function, lets the caller decide what to do with it, such as skipping a bad entry in a config file.

Python
def is_valid_port(n):
return 1 <= n <= 65535
print(is_valid_port(8080))
print(is_valid_port(70000))

Follow-up questions

  • Make the function also return False when n is not an int, using isinstance(n, int).
  • Given a list of ports, print only the invalid ones.

Frequently asked questions

print shows a value on the screen and gives nothing back. return gives the value to the code that called the function, so it can be stored, compared, or used in an if. A function that only prints cannot be used in if is_valid_port(p):.

Port 0 is reserved; asking the OS to bind to port 0 means "pick any free port for me". It is not a port you would put in a config file, so this function treats it as invalid.