All programs no matter how simple or complex involves three essential processes, these processes are:
- input
- processing
- output
Anything that goes on inside a program in a broad sense tries to help the program accomplish one of the above processes. Every time you are interacting with any computational device like your mobile phone, one (or more) of the above process is happening at any given time. For example when you tap an icon on your smart phone, you are giving input to the phone, which it processes in order to give you the needed output, in this case the output might be opening, or closing an application.
The three processes are actually the building blocks of computing and any programming language in existence, in one way or another, supports each of them. In this article we will explore the basics of each of the above processes, in the scope of Python programming. Input and output used together are usually given the acronym I/O to avoid redundant repetition.
Input
While it is possible for a simple program to work with it's pre-existing data to accomplish it's intended purpose, programs which are intended to perform a task beyond educational or simple testing , requires a lot of interaction from the user during it's runtime
Python language offers very user friendly and straightforward support for input (as well as output) , this is in contrast with some other languages like C++ and C where you will need to sort of 'import' the I/O utilities from the standard namespace before you can use them.
The input() function
The most basic way to get data during runtime in a Python Program is by using the input() function, this function is one of the standard functions which comes 'ready for use' with the Python interpreter. When this function is encountered, the Python program pauses to wait for user to enter data from the keyboard, the data entered can then be used immediately or saved in the programs scope for later use.
The function takes one optional argument , which is the prompt/message that will appear before the requested input:
input(prompt)
The prompt can be used to direct the user on what input is required.
Following is an example of the input() function in action:
username = input("Enter your name:")
The above program will show the prompt message , then wait for the user to type something from the Keyboard. The following snippet shows using the input function interactively:
fname = input("Enter your first name:")
//Enter your name:John _
lname = input ("Enter your last name:")
//Enter your last name: Doe _
name = fname + lname
print("your name is {}".format(name))
//your name is John Doe
The data collected by the function is always of the str type and if the data is intended to be of other types, one will have to explicitly turn the data into the relevant data type . For example if we get age from the user, we might want to turn the value entered into the int type. We can do this as follows
age = input("Enter you age:")
age = int(age)
and even more concisely:
age = int(input("Enter your age:"))
If we get from the input full names of the user separated by a blank, we might want to turn the data into a Python tuple type:
name = tuple(input("Enter your full name:").split())
//Enter your full name: John Smith Doe
print(name)
//('John', 'Smith', 'Doe')
Reading data from a file.
We can fetch data from a file or files existing in the computer for use inside the program's operation . It is common for programs to save data in a file and then read that data during another session. We will look at how we can read data existing in a simple text file from a python program.
You can create a file and name it data.txt for demo and then save the following data in it.
Berlin: Germany
Tokyo: Japan
Nairobi: Kenya
Moscow: Russia
Denver: America
Helsinki: Finland
Bogota: Colombia
Manilla: Philippines
Oslo: Norway
file = open("data.txt", "r")
cities = {}
for line in file.read().splitlines():
city, country = line.split(": ")
cities[city] = country
file.close()
The above program will read the file, then iterate through the file line by line, splitting it where it encounters the ": " separator, then save each city as the key and the country as the value in the dictionary named cities. The data can then be used inside the program for various operations. You can view the dictionary's content by using the print() function
print(cities)
{'Berlin': 'Germany', 'Tokyo': 'Japan', 'Nairobi': 'Kenya', 'Moscow': 'Russia', 'Denver': 'America', 'Helsinki': 'Finland', 'Bogota': 'Colombia', 'Manilla': 'Philippines', 'Oslo': 'Norway'}
I made the example simple in order to stick to the topic, you can check more about working with files in Python here
There are other more advanced ways that we can input data to the program during it's runtime, this includes loading data from a database , getting data from the internet , Using GUIs and many others.
Processing
Processing is where the actual logic of a program goes.This is where the program manipulates the data present in it's runtime, to come up with the intended output at a given time.
This phase involves things like , comparing data, evaluating logical relations in the data, combining or splitting data , looping e.tc . At this phase the data available to the program is made useful and relevant in pushing the program closer to accomplishing the task at hand.
While programming languages like Python offers some well structured I/O systems, the processing part is mostly implemented by the programmer and varies from program to program, it will even vary between programs that solves the same task, a language only offers utilities which the programmer can use to implement the programs logic. These utilities includes loops such as for and while loops, branching such as if , elif and else blocks, logical evaluators such as and, or ,not and many others, literally anything which cannot be used to add extra data in the program's scope or output program's processed values, is a part of Python's processing utilities.
Output
When instructions in a program are processed, the program will want to send the results to the user, or save the data for another session or maybe for use by other programs. There are many ways that a Python program can achieve this, it can display the values on the console, write them in a file, insert them in a database, send the data to a GUI or maybe output the values through the computer's loudspeaker(s).
The print() function
The most basic output method for a Python program is displaying the data to the console by using the builtin print() function. The simplest print() function syntax is as follows:
print(value)
I said simplest because the function can take "unlimited" values of mixed types to display to the console,
print(*values)
print(1, "John", [2,4,7,3])
1 John [2, 4, 7, 3]
The print function also takes, other arguments which are:
- sep - Indicates the separator for outputs spanning multiple lines
- end - The value to be printed after all the objects are printed.
- file - Specifies the file where the output goes, default is the console.
- flush - Flushes the stream/file if set to True.
print(1, "John", [2,4,7,3], sep= "\n")
1
John
[2, 4, 7, 3]
Even though the print function is not the most suitable output method for production applications, It forms one of the most useful debugging tools in Python for any program whether small or large.
Writing data to a file
A Python program can write processed values to a file. In the following example we write the cities from a Python dictionary to a file named data.txt.
cities = {'Berlin': 'Germany', 'Tokyo': 'Japan', 'Nairobi': 'Kenya', 'Moscow': 'Russia', 'Denver': 'America', 'Helnsiki': 'Finland', 'Bogota': 'Colombia', 'Manilla': 'Philippines', 'Oslo': 'Norway'}
file = open("data.txt","w")
for city in cities:
file.write("%s: %s\n"%(city,cities[city]))
file.close()
The above program will write in the file each city and the country separated with a ": ". You can check more on files here