Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 111 - 2632_CodeMind
P. 111

    Input and Output in Python

                      Python provides two commonly used functions input( ) and print( ) for input and output.

                      The input( ) Function

                      The  input( )  function  is  used  to  take  input  from  the  user  during  the  execution  of  a  program.
                      The general syntax of the input( ) function is as follows:

                      input([<prompt>])
                      Here, prompt is the string or message we wish to display on the screen. Example:

                          name = input("Enter your name: ")
                          >>> Enter your name: "John"
                      By default, Python considers the input as string even if you entered a number as input. You cannot
                      perform calculations on string. To perform calculations, you need to convert the string into integer
                      or floating-point value. To do so, Python provides following functions:
                      int():  It is used to change the input data value into integer. For example,
                            a = int(input("Enter a number "))

                      Now, the valid value entered is converted into integer value.
                      float():  It is used to change the input value into floating-point value. For example,
                              a = float(input("Enter a number "))

                      Now, the valid value entered is converted into floating-point value.
                      The print( ) Function

                      The print( ) function prints or sends the output to the standard output device, which is usually a
                      monitor. This function auto converts the items to strings, i.e., if you try printing a numeric value,
                      the print( ) function will automatically convert it into equivalent string and print it. The print( )
                      function also introduces spaces between items automatically.

                               Unlike Java and C++, Python does not use brackets to delimit code; but indentation
                               is mandatory with Python.

                      The general syntax of the print( ) function is as follows:
                      print ([<expression 1> , <expression 2>...])

                      For example:

                      print ("Python is easy")
                      Let's create a program to use the input( ) and print( ) functions.

                                        Imagine, comments in Python are secret messages from a wise mentor. What advice or
                                        tips would you leave in your code for future programmers to discover?

                          110    Premium Edition-VI

| 106 107 108 109 110 111 112 113 114 115 116 |