Menu

Pseudocode

Input, Output and Type Conversion

Input is how a program gets data from the user, usually storing it in a variable. Output is how it shows a message or value back to the user. Pseudocode uses INPUT and OUTPUT statements to show these stages, with the processing steps in between, so the algorithm forms a complete solution to a problem.

Input and output in pseudocode

Some pseudocode styles put the prompt inside the INPUT statement; others use an OUTPUT statement to show the prompt first, then an INPUT statement to accept the response. In Python, input() shows a prompt and returns the typed text, while print() displays a message or value.

  • pagesText = input("How many pages did you read? ") stores the response in pagesText.
  • print(pagesText) displays that value.

For example, a program for a school running track might ask for the length of one lap and the number of laps, multiply them, then display the distance. The two input() calls gather the data, the multiplication is the processing, and print() reports the result.

lapText = input("Length of one lap in km: ")
lapsText = input("How many laps did you run? ")
lapLength = float(lapText)
laps = int(lapsText)
distance = lapLength * laps
print("Total distance in km: " + str(distance))

Output when the user types 0.5, 5:

Length of one lap in km: 0.5
How many laps did you run? 5
Total distance in km: 2.5

Why type conversion matters

In Python, anything typed at an input is text, even if it looks like a number. If you type 12, the program holds the characters 1 and 2, not the value twelve, so arithmetic on it does not work as expected. Type conversion changes a value from one data type to another.

FunctionConverts toUse it when
int()whole numbera count is used in a calculation
float()decimal numbera measurement is used in a calculation
str()texta number must be joined to a message

So laps = int(lapsText) turns typed text into a whole number you can multiply, and print("Total distance in km: " + str(distance)) turns a number into text so it can join a label.

A flow from two text inputs (lapText and lapsText) through conversion to a decimal and a whole number, multiplication to give 2.5, and output with the number turned back into text.

scoreText = input("Enter your quiz score: ")
score = int(scoreText)
bonus = score + 5
print("Your score with the bonus is " + str(bonus))

Output when the user types 17:

Enter your quiz score: 17
Your score with the bonus is 22

Practise this