Lesson 13: input() | Learn and Practice with HolyPython.com (original) (raw)

Lesson 13: Python input() function

input() function is very simple and straightforward. It allows getting user’s input in string format. This is how it works:

1-) Type your message inside input(), this will be displayed to the user.

2-) And user will be shown a message or asked a question accordingly.

3-) After that, whatever they enter will be the value of your variable.

Let’s see some examples:

Function 1: input()

input() function lets you get input from the user of your program.

Used Where?

When user(s) input is needed. The reason can be acquiring information, selection, comment, answer etc.

Syntax do(s)

  1. Enter the message or question you want to show your user inside the input() function's parenthesis.

Syntax don't(s)

  1. Don't forget to type your message inside quotation marks inside the input() function.
    i.e.: input("message here")

Example 1: Simple input example

name = input("Please enter your name.")
print(name)

>>> Please enter your name… (Joe)
Joe

  1. After the first line is executed, the user will see the message: “Please enter your name.” and they will have a chance to type on the screen.

  2. After they hit enter, whatever they typed as a response to your message gets assigned to the namer variable we crated above.

3)When the second line is executed, print function prints out namer’s value (user’s input) as a string.

Tips

1- In summary, what you type inside input() is the message shown to the user. And what value gets assigned to the input object is the input user provides as a response to the message they see.

2- Input returns a string.

Example 2: What type of data does input function return?

age_r = input("What's your age?")
print(age_r)
print(type(age_r))

Example 3: Input program with dictionary

### Birthday Checker
birthday_list={'mom': '1/5/1862', 'dad': '5/20/1860',
'son': '8/12/1930', 'sister': '10/15/1885'}

answer=input("Family member please")

if answer in birthday_list:
    print("{}'s birthday is {}".format(answer.capitalize(), birthday_list[answer]))
else: 
    print("No record")

>>> Family member please …. (mom)

Mom’s birthday is 1/5/1862

Input function potential use cases

It’s just a little example to demonstrate what can possibly be achieved using Python’s input function. What other examples come to your mind? Here are some ideas:

So many ideas come to mind with this sympathetic useful Python function.

Next lesson will be another useful Python function range which is used to create ranges of numbers.

“Have you installed Python yet?”

Having Python setup on your computer can expedite the learning experience and help you gain the real life skills in a non-simulation environment. Installing Python can have different nuances that can be confusing for everyone. We compiled a complete tutorial about the best and most convenient Python installing practices Check it out by clicking the button below.