Python - Input and Output


You can use the raw_input() and print statements to get input from the keyboard and output data to the screen. We can use print to print a string of characters (called a string) enclosed within quotation marks to the screen. The quotation marks tell Python that a string is enclosed and the marks themselves are not displayed by the print statement. In the following program all three strings are printed on separate lines.


 
     
      print "One if by land."
      print "Two if by sea."
      print  "Three if by both."
      raw_input("Press enter to exit.")
      

The output of the above program will look like this:

One if by land.
Two if by sea.
Three if by by both.


If you want the lines to print all on the same line you must use the a comma after the first two lines. Thus the following code prints everything as one line of text.



      print "One if by land,",
      print "two if by sea,",
      print  "three if by both??"


The output:

One if by land, two if by sea, three if by both??

To get input from the user we use the raw_input() statement. For example, if you want have someone enter their age you can prompt for it by adding text to raw_input(). Enclose the text of your prompt with quotation marks and place it inside the parentheses something like this: raw_input("Please enter your age: ").

Before we actually get our input we first need to declare a variable in which to store the input. We declare a variable simply by chosing a name for it that is not reserved by Python for commands. Let's declare a variable with the name "age". We get our input by assigning it to the variable "age" as follows:


	age = raw_input("Please enter your age: ")
	
We have just declared a variable called "age" that will hold an the string value entered from the key board. Now we can use our variable to hold user input.


	age = raw_input("Please enter your age: ")
	print "You are",
	print age,
	print "years old."
     

(Using variables will be covered in more detail in the next section. )