Session 1: Hello World#
Introduction#
It’s traditional when learning a new language that the first program you write prints out “Hello World!” when run; so that’s where we are going to start too.
In fact, by the end of this session you will have seen three different ways you can do this in Python.
Why more than one? Because it’s part of the philosophy of Python that there is nearly always more than one way to do something, and the “best” one will depend on the circumstances.
Task 1#
In a terminal window, navigate to your
PHAR2062/Session 1 - Hello World
folder.Type:
python
and then press the return (↲) key. You should see something close to this:
Python 3.12.5 (main, Oct 9 2024, 11:27:36) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>>
prompt means that Python is ready and waiting for you to type something.
Type:
print('Hello World!')
and then - once you have checked that you have typed exactly what is written here - press the return key. You should see:
Hello World!
>>>
If so - Congratulations, you have just written and run your first Python program! If something else happened, ask for some help.
You will see that after doing what you asked, Python has gone back to showing you the
>>>
prompt - it’s ready for you to give it more instructions. Type:print('Python is fun')
(and then press return - from now on we won’t bother to say that). You should see:
Python is fun
>>>
I’m sure you are beginning to get the picture. Over to you - try getting Python to print out some more messages. The main thing to be careful about is that you always enclose your message in quotes (
'
).OK, but you will see we are stuck in a bit of a loop - how do we escape from Python once we are finished?
Type:
exit()
. You will see Python has shut down and you are now back at your standard terminal prompt.
Analysis#
The way you have used Python in this example is through what is known as a “Read, Execute, Print, Loop” or REPL. You type in a line of Python code, it gets executed (run), if there is anything that should be printed out it is, and then it loops back to waiting for you to type the next line of code (unless you have typed exit()
).
Let’s analyse that line of code you first wrote: print('Hello World!')
.
A line of code like this is often called a statement. print
is a Python function. You can tell this because it’s immediately followed by an open bracket ((
). Everything after the open bracket, up to the matching closing bracket ()
) is information that the function will work with - in this case the text 'Hello World'
.
This piece of information that the function print
works with is called an argument to the function. Although it’s two words, it’s only one piece of text, the beginning and end being marked by the quotes ('
) characters. Notice that although it’s vital that you wrap your message with quotes characters, they are not part of the message, so these don’t appear in what is printed to the screen.
Every Python function must have brackets, but it doesn’t have to take arguments - so you can see that exit()
is also a Python function.
Task 2#
Using Python via the REPL is quick, but fairly obviously very limited and rather awkward. Let’s look at another approach to getting Python to output ‘Hello World’.
Open your text editor, and create a file that contains just one line of text:
print('Hello World')
. Save this file in thePHAR2062/Session 1 - Hello World
folder with the namehello.py
, then close the editor.Back in your terminal window make sure you are still in the
PHAR2062/Session 1 - Hello World
folder, and type:
python hello.py
You should see a familiar message appear.
Re-open the file
hello.py
in your text editor, and add a secondprint()
statement below the first one, with a message of your choice. Maybe something like:
print('Hello World!')
print('Python is fun')
Save the file, then re-run the Python program. You should see each print statement in your Python program produces a message on a new line.
Re-open
hello.py
and change it so that your two messages are separate arguments to a singleprint()
function, i.e., something like:
print('Hello World!', 'Python is fun')
Notice the comma (,
) separating the two arguments to the print function - don’t miss this out!. Save the file and re-run the program - what happens?
Re-open the file, and edit it as follows:
message = 'Hello World!'
print(message)
Save the file and re-run it - look familiar?
Analysis#
Writing Python statements into a file (e.g. script.py
) and then getting python to execute it (python script.py
) is a much more useful way to create and run programs - in fact you will probably not use the REPL approach again in this course.
You have also seen that you can give the print()
function more than one argument if you like, (in which case the messages are written out on the same line, rather than each one on a new line). The fact that many Python functions can take variable numbers of arguments is an important concept you will see much more of in the future.
Finally, in the last example we have stepped up a gear, and introduced the concepts of targets, objects, and assigment statements. Let’s look at this:
The statement message = 'Hello World!'
is an assignment statement - you know that because of the equals sign (=
) between the left-hand side - the target - and the right hand side - the object. In effect, assignment statements allow the programmer to give helpful names to things that exist in the Python world.
In this case, the statement creates a target called message
that is in effect shorthand for 'Hello World!'
. In the next line, the argument to the print()
function is message
, rather than'Hello World!'
, but the result is the same. Notice that in the print()
function the target message
does not have quotes round it, this indicates it is a target, not the actual text itself.
So if you had written:
thing = 'Hello World!'
print(thing)
You would have got exactly the same result (try it!).
The name you give to a target is up to you (with some limitations - there are a few ‘reserved words’ in Python that you can’t use - more on this later).
Task 3#
Open your text editor, and create a file that contains just one line of text:
Hello World!
(note no quotes). Save this file in thePHAR2062/Session 1 - Hello World
folder with the namegreeting.txt
, then close the editor.Re-open
hello.py
and replace all the lines in it with the following Python statements:
datafile = open('greeting.txt')
message = datafile.read()
datafile.close()
print(message)
Save the file then re-run the Python program - you have probably guessed what the result will be?
Analysis#
So let’s dig in to the statements in this version of the code, because there’s some new stuff.
Looking at the first line: datafile = open('greeting.txt')
you can probably work out that in here we have both an assignment statement (because of the =
) and a function (because of the ()
). The function is called open
and it takes one argument - the name of a file. What is it doing on the right-hand side of an assigment statement?
OK…
The two functions we have looked at up to now - print()
and exit()
- are actually rather unusual ones, because in most cases functions don’t just take in arguments, they also give back (return) something (an object) as a result. The open()
function returns a type of Python object that can then be used to access the contents of the file (much more on this later).
So the statement on the first line creates a target called datafile
that is shorthand for the ‘file-wrangling’ object that can access the contents of ‘greeting.txt’.
The second line is a similar-looking assignment statement: message = datafile.read()
. It’s probably fairly obvious what’s happening here - the contents of the file ‘greeting.txt’ are being extracted and assigned to message
.
The function bit is different though - what’s with the dot (.
)? It means that the read()
function ‘belongs’ to the datafile
object. Thats why the read()
function doesn’t take any arguments to tell it what file to read the contents of - that must be datafile
. Functions that ‘belong’ to objects are called methods, and this type of logic is one of the principles of Object Oriented Programming, which Python uses a lot.
In the third line we are introduced to another method of the datafile
object - close()
. Dealing with files in Python is a bit like dealing with books in a library - open()
is not just about opening the book, it’s about getting it off the shelf in the first place. So when you have finished read()
ing the file, the close()
method is not just about closing the book, it’s about putting it back on the shelf so the next person can read it. Failure to close()
a file once you have finished with it is bad practice and can lead to errors!
So this is our third approach to the ‘Hello World’ task - what’s the point of this one?
In the previous case, if you wanted to change the greeting, you had to edit the file containing the Python code. In this third case, if you want to change the greeting, you just have to edit a small text file (try it!). More generally, it’s an example of separating the data the program will work on from the details of the code itself, which is an important concept in data science.
Task 4#
You have seen now how the print()
function allows Python to talk to you - but how do you talk to Python?
Edit
hello.py
so it lookls like this:
filename = input('Name of greeting file:')
datafile = open(filename)
message = datafile.read()
datafile.close()
print(message)
Save the file then re-run the Python program.
Analysis#
Here we introduce a new function, input()
. This function takes one argument, which is some text - a prompt - that is written to the screen, after which Python waits for input from you. Whatever you type in is what the function returns, which you can see from the first line is in this case assigned to the target filename
. This target can then be used as the argument to open()
in the next line.
The advantage of this version of your Python program is that now nothing in the code is ‘hard wired’. Before, the message to be printed had to be contained in a file called ‘greeting.txt’, but now it can be in a file called whatever you like.
Programming Challenge
Write a program that asks the user what their name is, and then prints: Hello X, welcome to Python!
(where X is the name).
Click here if you get stuck!
name = input('Hello! What is your name? ')
print('Hello ', name, ' welcome to Python!')
Summary#
In this workshop you have:
Seen how you can interact with Python directly via REPL - but not useful very often, in practice.
Seen how you can write simple text files that are Python programs, and run them.
Seen how you can get Python to read in data from external files.
Seen how you can get Python to read in data from the command line.
Concepts and vocabulary you have been introduced to include:
statements
functions
methods
arguments
assignment statements
targets
objects
Object Oriented Programming
reserved words
prompts