成人快手

Input and output

Programs require to be input. This data is used (processed) by the program, and data (or ) is output as a result.

Data input

are written to solve problems. To solve a problem, a program needs data input and data, or information, output.

Data can be input in different ways:

  • Written directly into the program. This is called hard coding.
  • By the user when the program is running.
  • From a file or other source when the program is running.

Consider this (3.x) program for calculating the perimeter of a square:

side_length = 5
perimeter = side_length * 4
print(perimeter)

The data in the variable 鈥榮ide_length鈥 has been hard coded, ie it has been written directly into the program. If we wanted to change this data, we would have to go back and change the program.

It is usually best to avoid hard coding as much as possible because it is difficult and time-consuming to rewrite a computer program just to change a single value.

Consider this alternative Python (3.x) program:

side_length = input("Type in the side length: ")
side_length = int(side_length)
perimeter = side_length * 4
print(perimeter)

This time, the data for the variable 鈥榮ide_length鈥 is input by the user when the program is running. The statement 鈥榠苍辫耻迟鈥 is used to tell the computer that the user must enter some data before the program can continue.

Data output

Once data has been processed, programs often need to output the data they have generated. In Python, the 鈥榩谤颈苍迟鈥 statement is used to output data.

Consider this Python (3.x) program for calculating the perimeter of a square:

side_length = input("Type in a side length: ")
side_length = int(side_length)
perimeter = side_length * 4
print("The perimeter of the square is: ")
print(perimeter)

This program uses the 鈥print鈥 statement to:

  • Display a message explaining what information is being output. Text is placed within quotes.
  • Output the contents of the variable 鈥榩erimeter鈥. Variables are not placed within quotes.

The print statement uses brackets to surround the data to be printed.