Skip to main content
Programming from zero

Functions theory + first problem: write is_valid_port(n)

easyFunctions Must-do

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.

flowchart LR A["input: 8080"] --> B["is_valid_port(n)"] --> C["returns: true"] classDef input fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef func fill:#FEF3C7,stroke:#D97706,color:#92400E classDef output fill:#D1FAE5,stroke:#059669,color:#065F46 class A input class B func class C output

A valid port is a whole number from 1 to 65535.

Common mistake: working out the answer but forgetting to return it.

◈ DIAGRAM
Wrong:
def is_valid_port(n):
n >= 1 and n <= 65535

The 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:

TEXT
8080: valid
0: invalid
65535: valid
70000: invalid

Approach

Define the function, then call it inside a loop:

  • Python: def is_valid_port(n): with the body indented, and return sends the answer back.
  • Java: static boolean isValidPort(int n) states the type it gives back (boolean) and the type of its input. The word static just lets main call it directly, and you can ignore it for now.
  • C++: bool isValidPort(int n) works the same way, and the function must be written above main so main knows 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")