Taking user input in python

To get input from the user, we need to use the input function.

a = input("Enter your first name: ")
b = input ("Enter your last name: ")
print(a, b)

#Output
Enter your first name: Aman
Enter your last name: Kharwal
Aman Kharwal

To add two numbers by taking user input:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a + b)

#Output
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 otherwise, it would have joint the two numbers rather than adding, for example:

a = input("Enter first number: ")
b = input("Enter second number: ")
print(a + b)

#Output
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(joint) the output rather than adding.

To add two floats:

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(a + b)

#Output
Enter first number: 4.92
Enter second number: 3.65
8.57

Previous||Next Chapter

Leave a Reply