Python: Input and Output
This article focuses on two built-in functions input()
and print()
to perform Input and output tasks in Python.
Python: Input -
We have the input()
function in Python which is used to take the input from the user. This function always reads the data from the keyboard in the form of String format. We have to convert that string type to our required type by using the corresponding type casting methods.
The syntax for input()
is:
input( "prompt" )
where prompt is the string we wish to display on the screen. It is optional.
Here, we can notice that the entered number 250
is a string, Not a number. We can check the datatype of a number using type()
function.
To convert this into a number we can use int()
or float()
functions of python.
How to read multiple values from the keyboard in a single line:
Example 1:
Note: split() function can take space as a separator by default . But we can pass anything as a separator.
While entering the two numbers above enter the first number give space and then enter the second number, as the split() function is passed with no separator.
Example 2:
Here, we have passed the comma(, ) as a separator to the split() function, therefore while entering the 3 float numbers they must be separated by a comma as shown above.
Python: Output -
We use the print()
function to output data to the standard output device (screen).
An example of its use is given below.
- print() without any argument, prints newline character.
2. If both arguments are String type then + operator acts as the concatenation operator.
3. If one argument is a string type and the second is any other type like int then we will get an error.
To remove the above error we have to convert the datatype of 24 from integer to string.
4. If both arguments are number types then the + operator acts as an arithmetic addition operator.
5. print() with variable number of arguments.
Note: By default output values are separated by space.If we want we can specify a separator by using the “sep” attribute
6. print() with the “end” attribute.
Let’s see what happens if don't use “end” in print()
After every print statement, we jump to the next line.
Because the default value for the end attribute is “\n”, which is nothing but a new line character.
If we want to output in the same line with space.
Here we have come to the end of this part. I hope you have found the article useful.❤