Input and Output

There are forms of output we’ll look at. (1) Output to the console, and (2) output to a file.

The way we output information to the console is the print function.

print("hello world")

We can print out variables like so.

x = 30
print("The value of the variable is ", x)

The constant string portion of the output is confined within the quotations; the variable goes after the comma, outside the quotes.

This method can get a tad cumbersome if we have many variables.

x = 30
y = 60
z = 90
print("The value of the first variable is ", x, "the value of the second is", y, "the value of the third variable is ",z)

A much easier way to write this is using a print format. Decide where you want to variable, and replace it with curly braces {}. After the quotes, write .format() with the variables inside the parenthesis.

x = 30
y = 60
z = 90
print("The value of the first variable is {} the value of the second is {} the value of the third variable is {} ".format(x,y,z))

Accepting input is done using the “input” function.

x = input("Enter an integer: ")
print("You entered ", x)

Alternatively, we might not want to be working with the console. Maybe we want to read or write from a file.

That can be done like so.

First, we wish to open a file. To do this, we use the open function.

f = open("FILE PATH","MODE")

The open function takes two arguments: the location of the file and the mode in which we wish to open the file in.


There are three main modes we should be familiar with.

a) “r” — Read mode. Use this if you only wish to read the contents of a file, and not write anything.

b) “w” — Write mode. This will erase the contents of the file and allow you to write new content to it.

c) “a” — Append mode. This is used when we wish to append new information to the end of a file without erasing its existing contents.

Once we’ve opened our desired file in the mode we need, we can perform the appropriate task.

Let’s try reading from a file — this is going to make use of “iteration”, which I cover in the next section. Be sure to read that (CLICK HERE) before moving on, to better understand what’s going on.

f = open("text.txt","r")
for line in f:

I open the file text.txt in read-only mode and use a for-loop to print it out. Note that the last thing we should always do is close the file.

Next, let’s try writing to this file.

f = open("text.txt","w")
f.write("This is a new line!")

That’s it!

Next, we’ll look at the many data structures Python provides us with.