How to get input from user in python ?

Developers often need to interact with the user, either to get data or to get result.Python provides us a built-in function for reading keyboard input.

How to get input from user in python ?

Developers often need to interact with the user, either to get data or to get result.Python provides us a built-in function for reading keyboard input.

 

input ()

This function first takes the input from the user then it stores this value as a character string, the default type of the input () function is string and in the following examples you will see how to change this type.

If you want to get input from the user, we should use the input function.

n = input ("Please enter your first name: ")
ln = input ("Please enter your last name: ")
print (n, ln)

Then the output will be :

Enter your first name : Walid

Enter your last name : Jadla

Walid Jadla

If you want to add two numbers by using user input :

x = int (input ("Enter first number: "))

y = int (input ("Enter second number: "))

print (x + y)

Then the output will be :

Enter first number: 25

Enter second number: 20

45

I used int before the input because to add two integers we need to declare the data type if not, it would have jointed the two numbers instead than adding, see the example :

a = input ("Enter first number: ")

b = input ("Enter second number: ")

print (a + b)

Then the output will be :

Enter first number: 25

Enter second number: 20

2520

as you can see without being declared as int, it took the output as a string and concatenated the output rather than adding.

 

If you want to add two floats :

a = float (input ("Enter first number: "))

b = float (input ("Enter second number: "))

print (a + b)

Then the output will be :

Enter first number: 4.92

Enter second number: 3.65

8.57

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0