Python | User Input and Output

One way of making your program more interactive is to allow users to enter data then perform operations based on the users input.

Two of the very important built-in functions in Python that allow us to enter data in our program then display it after we have done some processing are input() and print().

name = input('Your name: ')
#After you press “Enter” you will be prompted to enter your name
Your name: Dan
age = input('Your age: ')
#After you press “Enter” you will be prompted to enter your name
Your age: 40
print('Congratulations',name,',','you are now',age,'years old')
Congratulations Dan , you are now 40 years old

Python user input output

Ok, what have we done here!?

We declared a variable named name. Its value is whatever the user types in the input field (in our case, the user’s name).
Next, we declared another variable named age. It’s value is whatever the user types in the input field (in our case, the user’s age).
Next, we use the function print() to print on the screen a customized message that contains the data inputed by the user.

Note:
I have used raw_input() function when I declared the variable name and the input() function when I declared the variable age. That is because in my version of Python the raw_input() function reads every input as a string and input() function actually uses raw_input() function and then tries to convert the input data to a number using eval().

Another fast example can be:

number_one = input('your first number: ')
your first number: 5
number_two = input('your second number: ')
your second number: 6
answer = number_one * number_two
print(answer)
30

Python user input output

Leave a Reply