How to take input in Python?

PythonServer Side ProgrammingProgramming

Programs are written to solve a specific problem of a user. Thus, the program must be such which can interact with the user. This means that a program must take input from the user and perform the task accordingly on the input which user provides.

The method to take input is different for different datatypes. We’ll discuss how to take input for various datatypes as well as how to take array input from the user.

String Input

The input() method is used to take string input from the user.The user can enter numeric value as well but it will be treated as a string. The program can contain any logic or operation to be performed on the string entered by the user ,but in example, we’ll simply print the string which the user enters.

Example

print("Enter a string")
a=input()
print("The string entered by user is",a)

Output

Enter a string
TutorialsPoint
The string entered by user is TutorialsPoint

The above example upon execution, prints the message “Enter a string” on the output screen and lets the user enter something. When input() function executes, the program flow will be stopped until the user gives some input. After entering the string, the second print statement executes.

Integer Input

The integer input can be taken by just type casting the input received into input(). Thus, for taking integer input, we use int(input()) . Only numerical values can be entered by the user, else it throws an error.

Example

print("Enter a number")
a=int(input())
print("The number entered by user is",a)

Output

Enter a number
10
The number entered by user is 10

Float Input

The float input can be taken by type casting input received in input() .We’ll use float(input()) to take float input. The user can enter integer or float values but the value will be treated as float.

Example

print("Enter a number")
a=float(input())
print("The number entered by user is",a)

Output

Enter a number
2.5
The number entered by user is 2.5

Take Input as Array of Integers

We may at times, need to take an array as input from the user. There is no separate syntax for taking array input.

Example

print("Enter no. of elements")
a=int(input())
print("Enter",a,"integer elements")
array=[]
for i in range(a):
   array.append(int(input()))
print("Array entered by user is",array)

Output

Enter no. of elements
5
Enter 5 integer elements
1
2
3
4
5
Array entered by user is [1, 2, 3, 4, 5]

In the above example, the size of the array is taken as input from the user. Then the array is declared and using for loop, we take further elements input from the user and append those in the array.

For taking string array input, we can use input() instead of int(input()) inside for loop.

raja
Published on 10-Mar-2021 13:57:19
Advertisements