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#For stringstr=input()# For integersn=int(input())# For floating or decimal numbersn=float(input())
2. Taking Multiple Inputs:Multiple inputs in Python can be taken with the help of themap() andsplit() 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# For Stringsx,y=input().split()# For integers and floating point# numbersm,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# For Input - 4 5 6 1 56 21# (Space separated inputs)n=list(map(int,input().split()))print(n)
Output:
[4, 5, 6, 1, 56, 21]
4. Taking Fixed and variable numbers of input:
Python3# Input: geeksforgeeks 2 0 2 0str,*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:
Python3lst=['geeks','for','geeks']foriinlst:print(i)
Output:
geeksforgeeks
2. Output on the same line:end parameter in Python can be used to print on the same line.
Example 1:
Python3lst=['geeks','for','geeks']foriinlst:print(i,end='')
Output:
geeksforgeeks
Example 2:Printing with space.
Python3lst=['geeks','for','geeks']foriinlst: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:
Python3print('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:
Python3val="Hello"print(f"{val} World!!!")