Monday, 13 April 2020

Giving Input and Printing output in Python

We compared python's code to that of C++ and Java. If you remember, both C++ and Java required some additional header files (similar to modules in python) to get some user input, while in python all it took was just one line.

Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard.
  • raw_input ( prompt )
  • input ( prompt )
1.raw_input ( ) : This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store. For example –
s = raw_input('-- ')
--Monty Python's Flying Circus
"Monty Python's Flying Circus"

input ( ) : This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python. For example –

x=input("enter your number--")
print("you have entered..",x)

The output will be like this

How the input function works in Python :
  1. When input() function executes program flow will be stopped until the user has given an input.
  2. The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional.
  3. Whatever you enter as input, input function convert it into a string. if you enter an integer value still input() function convert it into a string. You need to explicitly convert it into an integer in your code using typecasting.

 Printing output in Python 

To output your data to the screen, use the print() function. You can write print(argument) and this will print the argument in the next line when you press the ENTER key.

Example program to pint addition of two numbers

x = input("Type a number: ")
y = input("Type another number: ")

sum = int(x) + int(y)

print("The sum is: ", sum) 



Post a Comment

Note: only a member of this blog may post a comment.

Find Us On Facebook

python tutorial


C Programming


Java Tutorial


Data Structures


MS Office


Database Management