A simple Python “hello world” program that introduces fundamental programming concepts:

  • printing
  • standard streams
  • functions
  • function arguments
  • string concatenation
  • type hinting
  • default argument values
  • Python modules

The concepts introduced in this Python hello world program apply to practically all other programming languages.

Prerequisite:
Python Installation

Python hello world

A “hello world” program is a simple program meant to illustrate the basics of a language’s syntax.

The key to any command-line “hello world” program is to utilize a programming language’s I/O functions to visibly print a string to STDOUT.

Python has a library of built-in functions which are part of the interpreter and require no additional imports.

Of these built-ins, the print() function is Python’s primary I/O function. By default it prints to STDOUT. In more sophisticated usage, it can be given an argument to a file-descriptor to specify other targets to write to, including other standard streams.

One-line hello

The simplest hello.py script needs only this one line:

print("hello world!")

Run from file

To run our one-liner from an actual file, save the code to a file called hello.py, open a console, navigate to the directory you saved under, and run:

python hello.py
hello world!

Interpreter

Now run this code using the Python interpreter. The Python interpreter is a console-application that allows you to write code and see its output right away.

This rapid feedback loop is a powerful tool which is not only excellent for learning and experimentation, but real-world debugging and problem-solving.

Open the Python interpreter by opening a console and typing python at the prompt:

python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Run the one-liner in the Python interpreter:

print("hello world!")
hello world!

Creating a function

Next, let’s encapsulate our one-liner into a function:

# define a reusable function
def hello_world():
    print("hello world!")

By encapsulating our code into a function, our code becomes reusable. This is a concept is of great significance in software engineering as it allows programmers to decompose complex problems into discrete units and create effective systems of abstraction to handle complicated tasks.

If you update hello.py with the above code and run it, you will not get any output:

python hello.py
 

This is because we have defined our function, but we have not given Python and the computer any instructions to run the function.

When a function is defined, it is stored in memory, but the computer will not execute the function logic until it is called.

Rephrased, functions must be called, otherwise they are stored in memory but never executed.

All we have done thus far is define the function; now we must call it. Update hello.py with the following code:

# define a reusable function
def hello_world():
    print("hello world!")

# call our function
hello_world()

Now when you re-run hello.py, you will see the expected output:

python hello.py
hello world!

Functions with arguments

What if you wanted a more versatile function that could say hello to various nouns?

We can achieve this using function arguments. Let’s update the code in hello.py:

# function for saying hello to some noun
def hello(noun):
    print("hello " + noun + "!")

# call our function with the noun "awesome world"
hello("awesome world")

Go ahead and run the hello.py file from the command-line. You should see:

python hello.py
hello awesome world!

Concatenation

Here, noun is a function argument. The argument noun is a variable that is being passed into the function. We are then concatenating the data passed in the variable noun with the string "hello " followed by the character "!".

Concatenate means: to link things together.

Note the space at the end of "hello " before the closing quotes: if we did not have that space, then the noun would run into the word “hello”.

Type Hinting

Python offers programmers the ability to specify what the type of an argument to a function ought  to be. This is called “type hinting”.

Type hinting is a syntax for clarity and convenience; unlike in strongly typed programming languages, there are no runtime errors if an argument does not adhere to the typing specified in the function definition.

In other words, Python type hinting and will not produce errors if you pass in arguments that do not adhere to the type hints. They are entirely for clarity.

We can add a type hint to our hello(noun) function by updating the definition like so:

# function for saying hello to some noun
# the argument noun should be a string
def hello(noun: str):

Adding type hints to function definitions not only increases clarity of code, but confers certain other advantages, such as allowing editors to perform static analysis on code.

Default Argument Values

If we wanted to make our simple hello(noun) function callable without specifying a noun, we could specify a default argument value for noun to use when no argument is provided:

# function for saying hello to some noun
# the argument noun should be a string
# if no argument is given, noun defaults to "world"
def hello(noun: str = "world"):
    print("hello " + noun + "!")

# call our function with the noun "awesome world"
hello("awesome world")

# call our function with no argument
hello()

Go ahead and run this updated hello.py from the command-line. You should see the following output:

python hello.py
hello awesome world!
hello world!

Importing modules

Our hello.py script should look something like:

# function for saying hello to some noun
# the argument noun should be a string
# if no argument is given, noun defaults to "world"
def hello(noun: str = "world"):
    print("hello " + noun + "!")

# call our function with the noun "awesome world"
hello("awesome world")

# call our function with no argument
hello()

If we have another module import.py in the same directory as hello.py, we can perform a relative import without having to create a package and define an __init__.py file:

Vernacular: a file containing Python code for import is known as a module.

# import everything from hello.py 
# hello.py must be in Python path or same directory
from hello import *

# execute our imported hello() function
hello("imported world")

When you run this import.py file, notice how the calls to hello("awesome world") and hello() are also imported and run:

python import.py
hello awesome world!
hello world!
hello imported world!

To fix this, we have two choices. The simplest choice is to limit our import to only the hello() function:

# import only the hello() function from hello.py 
# hello.py must be in Python path or same directory
from hello import hello

# execute our imported hello() function
hello("imported world")

This will output:

python import.py
hello imported world!

Check if script was run from command-line

if __name__ == "__main__"

Python offers a mechanism for modules to check whether they are being imported or run as a script:

if __name__ == "__main__":

This is a conditional if-statement which checks whether the __name__ of the current module is "__main__" which happens when the module is being executed directly as a script from the command-line.

Let’s use this in hello.py to have it intelligently suppress the logic in its top-level namespace, namely the hello("awesome world") and hello() calls.

# function for saying hello to some noun
# the argument noun should be a string
# if no argument is given, noun defaults to "world"
def hello(noun: str = "world"):
    print("hello " + noun + "!")

# only print if this is a script called from command-line
if __name__ == "__main__":
    # call our function with the noun "awesome world"
    hello("awesome world")

    # call our function with no argument
    hello()

Now let’s go back to import.py and revert to importing everything using the wildcard *:

# import everything from hello.py 
# hello.py must be in Python path or same directory
from hello import *

# execute our imported hello() function
hello("imported world")

This time, you should see:

python import.py
hello imported world!

Import best practice

The recommended best practice is to explicitly name everything you are importing from another module rather than relying on the wildcard *. The reasoning for this is twofold:

  1. You may inadvertently call code that prints or behaves in a way you don’t want
  2. You are unnecessarily polluting the namespace of the module you are importing into, in this case hello.py

To clarify the point about polluting the namespace: this becomes more significant when you begin to have files with many imports from many different libraries. It may be entirely possible for two different libraries to have the same functions.

If you mistakenly import both of the same-name functions from both libraries using wildcards *, one will overwrite the other in the importing module’s namespace. This may lead to unintended behaviour and bugs!

Hence, the best practice is to be as clear-cut and explicit as you can.

Ready for more?
Computer Science Fundamentals – Variables and Data


Leave a Reply

Your email address will not be published. Required fields are marked *