Saturday, October 5, 2024
Google search engine
HomeLanguagesInput and Output in Python

Input and Output in Python

In this article, we will see different ways in which first we can take input from users and second show output to them.

How to Take Input from User in Python

Sometimes a developer might want to take user input at some point in the program. To do this Python provides an input() function.

Syntax:

input('prompt')

where prompt is an optional string that is displayed on the string at the time of taking input.

Example 1: Python get user input with a message

Python3




# Taking input from the user
name = input("Enter your name: ")
 
# Output
print("Hello, " + name)
print(type(name))


Output:

Enter your name: GFG
Hello, GFG
<class 'str'>

Note: Python takes all the input as a string input by default. To convert it to any other data type we have to convert the input explicitly. For example, to convert the input to int or float we have to use the int() and float() method respectively.

Example 2: Integer input in Python 

Python3




# Taking input from the user as integer
num = int(input("Enter a number: "))
 
add = num + 1
 
# Output
print(add)


Output:

Enter a number: 25
26

How to take Multiple Inputs in Python :

we can take multiple inputs of the same data type at a time in python, using map() method in python.

Python3




a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)


Output : 

Enter the Numbers : 2 3 4
The Numbers are :  2 3 4

How take inputs for the Sequence Data Types like List, Set, Tuple, etc.

In the case of List and Set the input can be taken from the user in two ways.

  1. Taking List/Set elements one by one by using the append()/add() methods.
  2. Using map() and list() / set()  methods.

Taking List/Set elements one by one 

Take the elements of the List/Set one by one and use the append() method in the case of List, and add() method in the case of a Set, to add the elements to the List / Set.

Python3




List = list()
Set = set()
l = int(input("Enter the size of the List : "))
s = int(input("Enter the size of the Set  : "))
print("Enter the List elements : ")
for i in range(0, l):
    List.append(int(input()))
print("Enter the Set elements : ")
for i in range(0, s):
    Set.add(int(input()))
print(List)
print(Set)


Output :

Enter the size of the List : 4
Enter the size of the Set  : 3
Enter the List elements : 
9
0
1
3
Enter the Set elements : 
2
9
1
[9, 0, 1, 3]
{9, 2, 1}

Using map() and list() / set() Methods 

Python3




List = list(map(int, input("Enter List elements : ").split()))
Set = set(map(int, input("Enter the Set elements :").split()))
print(List)
print(Set)


Output :

Enter List elements : 3 4 8 9 0 11
Enter the Set elements :34 88 230 234 123 
[3, 4, 8, 9, 0, 11]
{34, 230, 234, 88, 123} 

Taking Input for Tuple 

We know that tuples are immutable, there are no methods available to add elements to tuples. To add a new element to a tuple, first type cast the tuple to the list, later append the element to the list, and again type cast list back to a tuple.

Python3




T = (2, 3, 4, 5, 6)
print("Tuple before adding new element")
print(T)
L = list(T)
L.append(int(input("Enter the new element : ")))
T = tuple(L)
print("Tuple After adding the new element")
print(T)


Output :

Tuple before adding new element
(2, 3, 4, 5, 6)
Enter the new element : 35
Tuple After adding the new element
(2, 3, 4, 5, 6, 35)

How to Display Output in Python

Python provides the print() function to display output to the standard output devices. 

Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False

Returns: It returns output to the screen.

Example: Python Print Output

Python3




# Python program to demonstrate
# print() method
print("GFG")
 
# code for disabling the softspace feature 
print('G', 'F', 'G')


Output

GFG
G F G

In the above example, we can see that in the case of the 2nd print statement there is a space between every letter and the print statement always add a new line character at the end of the string. This is because after every character the sep parameter is printed and at the end of the string the end parameter is printed. Let’s try to change this sep and end parameter.

Example: Python Print output with custom sep and end parameter

Python3




# Python program to demonstrate
# print() method
print("GFG", end = "@")
 
# code for disabling the softspace feature 
print('G', 'F', 'G', sep="#")


Output

GFG@G#F#G

Formatting Output

Formatting output in Python can be done in many ways. Let’s discuss them below

Using formatted string literals

We can use formatted string literals, by starting a string with f or F before opening quotation marks or triple quotation marks. In this string, we can write Python expressions between { and } that can refer to a variable or any literal value.

Example: Python String formatting using F string

Python3




# Declaring a variable
name = "Gfg"
 
# Output
print(f'Hello {name}! How are you?')


Output: 

Hello Gfg! How are you?

Using format()

We can also use format() function to format our output to make it look presentable. The curly braces { } work as placeholders. We can specify the order in which variables occur in the output. 

Example: Python string formatting using format() function

Python3




# Initializing variables
a = 20
b = 10
 
# addition
sum = a + b
 
# subtraction
sub = a- b
 
# Output
print('The value of a is {} and b is {}'.format(a,b))
 
print('{2} is the sum of {0} and {1}'.format(a,b,sum))
 
print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,
                                                                         value_b = b,
                                                                         sub_value = sub))


Output:

The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10

Using % Operator

We can use ‘%’ operator. % values are replaced with zero or more value of elements. The formatting using % is similar to that of ‘printf’ in the C programming language.

  • %d – integer
  • %f – float
  • %s – string
  • %x – hexadecimal
  • %o – octal

Example:

Python3




# Taking input from the user
num = int(input("Enter a value: "))
 
add = num + 5
 
# Output
print("The sum is %d" %add)


Output:

Enter a value: 50
The sum is 55

RELATED ARTICLES

Most Popular

Recent Comments