Functions theory + first problem: write is_valid_port(n)
Problem statement
A function is a named block of code you write once and use many times. You define it once, then call it whenever you need it. It takes inputs, called parameters, and sends an answer back with return. Instead of copying the same port check into ten places, you write is_valid_port(n) once and call it ten times.
A valid port is a whole number from 1 to 65535.
Common mistake: working out the answer but forgetting to return it.
Wrong:def is_valid_port(n): n >= 1 and n <= 65535The line computes True or False and then throws it away. The function hands back nothing (None in Python), so if is_valid_port(port): is never true. In Java, a missing return is a compile error. In C++ it is worse, because the program may still build and behave unpredictably.
Your task: write a function is_valid_port(n) that gives back whether n is a valid port. Then check the ports 8080, 0, 65535 and 70000, printing <port>: valid or <port>: invalid for each.
Expected output:
8080: valid0: invalid65535: valid70000: invalidApproach
Define the function, then call it inside a loop:
- Python:
def is_valid_port(n):with the body indented, andreturnsends the answer back. - Java:
static boolean isValidPort(int n)states the type it gives back (boolean) and the type of its input. The wordstaticjust letsmaincall it directly, and you can ignore it for now. - C++:
bool isValidPort(int n)works the same way, and the function must be written abovemainsomainknows it exists.
Python programmers write names like is_valid_port. Java and C++ programmers usually write isValidPort. Same idea, different habit.
DSA connection: functions are the building block of recursion, where a function calls itself.
def is_valid_port(n):
return n >= 1 and n <= 65535
for port in [8080, 0, 65535, 70000]:
if is_valid_port(port):
print(f"{port}: valid")
else:
print(f"{port}: invalid")