Getting started
To write a new Python program, create a new next file in your favourite editor, type (or copy & paste) some Python code, then save it with a filename ending in
.py
. Open a terminal window, navigate to the directory where you saved the file, and type the name of the Python executable, followed by the name of your file. On most systems, the Python 3 executable is called python3
, so we will type:python3 myscript.py
Note: I will sometimes refer in these notes to a ‘script’, which is pretty much a synonym for ‘program’.
Wherever you see a box in the notes that is prefixed with
In[]
we are looking at Python code, which can be copied and pasted into a text file to run it.Printing and comments
To print some output to the screen in Python we use the
print()
function:print("hello!")
Notice that
- print is a function
- we write the name of the function, followed by a pair of brackets
- the stuff inside the brackets is the arguments to the function (sometimes called parameters)
- in this case we have one argument – the thing we want to print
- the text we want to print is inside double quotes (this is called a string)
- the line ends with a newline (carridge return, enter)
- the text shows up in different colours (syntax highlighting)
- a complete line like this is called a statement
If we want to leave a note for ourselves, we start the line with a #. This is called a comment. We will make extensive use of comments in the code samples throughout these notes. Often, we write a comment which describes what the next line will do when it is executed:
# this next line will print a greeting
print("hello!")
This is a good habit to get into!
Here are a few code samples that will cause stuff to be printed to the screen. Copy and paste them into text files and try running the code. The output for each code sample is displayed below the box.
In [26]:
print("hello!")
In [27]:
#this is a comment - it is for humans to read
print("hello again")
In [28]:
#we can prevent a statement from being run by putting a # at the start of the line
#print("hello again")
print("goodbye")
In [31]:
#we can use single quotes as well - sometimes this is easier
print('you say goodbye, I say hello')
#for instance, if we want to include a double quote in the output
print('you say "goodbye", I say "hello"')
In [32]:
#if we forget the quotes we will get an error
print(hello)
In [33]:
#if we forget the brackets we will also get an error
print 'Hello'
Variables
We can give a name to a string. The name is called a variable
name = 'Martin'
We can concatenate two strings (stick them together) with +
name = 'Mar' + 'tin'
In [34]:
# once we have created a variable, we can use it in print
name = 'Martin'
print(name)
In [35]:
# we can change a variable after we have made it
name = 'Martin'
print(name)
name = 'John'
print(name)
In [36]:
# we can use concatenation to make new strings which we can print
print('hello ' + 'world')
# we are not allowed to use spaces in variable names so use an underscore
first_name = 'Martin'
print('hello ' + first_name)
last_name = 'Jones'
# we can use a mixture of strings and variables
print('hello ' + first_name + last_name)
# that is not quite right, we need a space between first and last names
print('hello ' + first_name + ' ' + last_name)
In [37]:
# we can also store a new string in a variable and use it later
first_name = 'Martin'
last_name = 'Jones'
full_name = first_name + ' ' + last_name
print('hello ' + full_name)
Strings and functions
To get the length of a string we use
len('hello Martin')
we can also use a variable
len(first_name)
len()
is a function and the string that we give it is a parameter.
Another useful function is
str()
, which turns a number into a string.str(42)
In [38]:
# we can print the output of a function
print(len('hello'))
# or we can store it
name_length = len('Martin')
print(name_length)
In [39]:
# the output from len() is not a string - it is a number
# so python will complain if we try to use it like a string
print('your name is has this many letters: ' + len('martin'))
In [40]:
# we have to use str() to turn it into a number
name_length = len('Martin')
print('your name is has this many letters: ' + str(name_length))
In [41]:
# we can do everything in one go like this
# we use the output of len() as the input for str()
print('your name is has this many letters: ' + str(len('martin')))
# when we write it this way we have three consecutive close brackets at the end of the line
# make sure you have the same number of ( and )
Reading files
To open a text file, we use the
open()
function.file = open('myfile.name')
open()
takes one argument – the filename.The output (or return value) is an object that represents the file.
To read the contents of a file, use the
read()
method on the file object.contents = file.read()
This is slightly different to using a function. The read method belongs to the variable which holds the file object, so we write the name of the variable first, then a dot and the method name.
In [42]:
# open a file called input.txt in the current directory
file = open('input.txt')
# read the contents of the file and store them in a variable called contents
contents = file.read()
# print the contents
print(contents)
In [43]:
# note that we have to print the variable that holds the contents of the file
# if we try to print the file we don't get what we want
file = open('input.txt')
print(file)
In [44]:
# however, we can call read() and give it to print() right away
file = open('input.txt')
print(file.read())
In [45]:
# we will get an error if we try to open a file that doesn't exist
file = open('missingfile.txt')
Writing to files
The
open()
function is actually more complicated than described above.
We can use a second argument, which is a string describing what we want to do to the file.
In this case, we want to write to the file, and we want it to be a text file, so we use the string “wt”
file = open('output.txt', 'wt')
There is a
write()
method that is similar to the read()
methodfile.write('Hello Martin')
When we have finished writing to a file, we call the
close()
methodfile.close()
The
close()
method is interesting because it does not take any arguments, and we do not store the result. For small scripts, it’s not strictly necessary, but it is a good habit to get into.
In [46]:
# open an output file
file = open('output.txt', 'wt')
# write some text to it
file.write('Hello Martin')
# close the file
file.close()
In [47]:
# we can also append to an existing file by using a instead of w
file = open('output2.txt', 'at')
# every time we run this bit of code we will add a new line to the file
file.write("Hello again\n")
# the \n is a special combination of characters - it means start a new line
file.close()
In [48]:
# we can do all the string stuff we already know about in write()
first_name = 'Martin'
last_name = 'Jones'
file = open('output3.txt', 'wt')
file.write('hello ' + first_name + ' ' + last_name)
file.close()
A small program
Here is a program that reads a first name from one file and a last name from a second file. It then opens a third file and writes a greeting to it.
We need to use one more method in this program –
rstrip()
. This method removes characters from the right-hand end of a string. The argument is the character that we want to remove.
In this case we want to remove a newline from the end of the string so we call
first_name.rstrip('\n')
. Remember that ‘\n’ mean a newline.
If we left out the
rstrip
then we would have an unwanted newline in the middle of our output.
Rather than storing the result in a variable we use it straight away as part of the
print
statement.
Notice that
- we use a different variable name for each file that we open
- we have put in some blank lines to separate the different parts of the program
- there is no connection between the name of the variable firstnamefile and the filename firstname.txt. We could replace all instances of firstnamefilewith banana and the script would work just as well (but it would be harder to read!)
The line that does the writing is a little bit difficult to read – we will learn a better way of doing this in a future session
In [49]:
# here we read a first and last name from two different files
# then write a greeting to a third file
first_name_file = open('firstname.txt')
first_name = first_name_file.read()
last_name_file = open('lastname.txt')
last_name = last_name_file.read()
output_file = open('fullname.txt', 'wt')
output_file.write('hello ' + first_name.rstrip('\n') + ' ' + last_name + "\n")
output_file.close()
No comments:
Post a Comment