Handling Input and Output in Python


 Most of the programs we write depend on input/data from the user. Once our program processes this data, we deliver the output back to the user. A program may or may not need an input but will have some form of output (display a message to the user, store the result in the text file, etc). After all, that’s the whole purpose of writing a program.

 

 

Displaying Messages - One Variable

 

In the flowchart, we use a reserved word (“write”) and an oblique parallelogram to depict the output of the program.  

  

 

The two arrows (top and bottom) show that this piece is a part of a larger flowchart. This part of the flowchart shows that users will see the value of the variable finalAmount on the screen.


Python provides a command to do the same.
print(finalAmount) . 

This will show the value of the variable finalAmount on the screen.


We can output the value of a variable or a fixed string or a combination. 


1. message = “Hello world”
2. print(message)


In line 1 we have declared a variable called message and initialized (setting initial value) it to “Hello World”. When the second line is run through the processor, it will throw a message on the screen to the user. The user will read 🡪 Hello World.


Alternatively, we can put a fixed string (enclosed in a double-quote or single quote) and show it to the user. 
print(“Hello World”) will show the same output.


It is important to remember to put your message in quotes. Trying to print(Hello World) will show an error because Python won’t be able to understand what Hello and World are.


It is also possible to use another character instead of a space to join variable values when using the print statement. 


If you wish to customize the separator character, you need to use a value for argument sep as shown here: 


print("Morning", "Evening", "Night", sep = "#") 
will show


Morning#Evening#Night

No comments:

Post a Comment