Different Input and Output Techniques in Python3
Last Updated :
10 Nov, 2022
An article describing basic Input and output techniques that we use while coding in python.
Input Techniques
1. Taking input using input() function -> this function by default takes string as input.
Example:
Python3
str = input ()
n = int ( input ())
n = float ( input ())
|
2. Taking Multiple Inputs: Multiple inputs in Python can be taken with the help of the map() and split() methods. The split() method splits the space-separated inputs and returns an iterable whereas when this function is used with the map() function it can convert the inputs to float and int accordingly.
Example:
Python3
x, y = input ().split()
m, n = map ( int , input ().split())
m, n = map ( float , input ().split())
|
3. Taking input as a list or tuple: For this, the split() and map() functions can be used. As these functions return an iterable we can convert the given iterable to the list, tuple, or set accordingly.
Example:
Python3
n = list ( map ( int , input ().split()))
print (n)
|
Output:
[4, 5, 6, 1, 56, 21]
4. Taking Fixed and variable numbers of input:
Python3
str , * lst = input ().split()
lst = list ( map ( int , lst))
print ( str , lst)
|
Output:
geeksforgeeks [2, 0, 2, 0]
Output Techniques
1. Output on a different line: print() method is used in python for printing to the console.
Example:
Python3
lst = [ 'geeks' , 'for' , 'geeks' ]
for i in lst:
print (i)
|
Output:
geeks
for
geeks
2. Output on the same line: end parameter in Python can be used to print on the same line.
Example 1:
Python3
lst = [ 'geeks' , 'for' , 'geeks' ]
for i in lst:
print (i, end = '')
|
Output:
geeksforgeeks
Example 2: Printing with space.
Python3
lst = [ 'geeks' , 'for' , 'geeks' ]
for i in lst:
print (i,end = ' ' )
|
Output:
geeks for geeks
3. Output Formatting: If you want to format your output then you can do it with {} and format() function. {} is a placeholder for a variable that is provided in the format() like we have %d in C programming.
Example:
Python3
print ( 'I love {}' . format ( 'geeksforgeeks.' ))
print ( "I love {0} {1}" . format ( 'Python' , 'programming.' )
|
Output:
I love geeksforgeeks.
I love Python programming.
Note: For Formatting the integers or floating numbers the original method can be used in the {}. like ‘{%5.2f}’ or with the numbers, we can write it as ‘{0:5.2f}’. We can also use the string module ‘%’ operator to format our output.
4. Output using f strings:
Python3
val = "Hello"
print (f "{val} World!!!" )
|
Please Login to comment...