2.5 Input statement

The input() statement in Python is used to take input from the user. When input() is called, the program will pause and wait for the user to type something and press Enter. The input entered by the user is returned as a string.

Syntax:

variable = input("Prompt message")
The variable is the name of the variable where the input value will be stored. Whereas "Prompt message" is a message that is displayed to the user, indicating that input is expected. Make sure to provide a clear and concise prompt message to guide the user on what input is expected.

Example 2.5.1

This program prompts the user to enter their name. It then greets the user by printing "Hello," followed by the name they entered.

name = input("Enter your name: ")
print("Hello " + name)
 

Please note that we could have achieved the same result using commas in the print statement. When you use commas in the print() function, it prints each argument separated by a space by default as displayed in Example 2.5.2. This method also automatically converts non-string arguments to strings.

Example 2.5.2

The output would be the same as in example 2.5.1, but we are using the comma to print each argument separated by a space by default.

This method is more concise and automatically handles spaces between arguments. It can handle non-string arguments without needing explicit conversion as we shuould see in section 2.6.

name = input("Enter your name: ")
print("Hello", name)

 


 

Exercise 2.5.1 - Write a Python program by first asking the user for their first name and then ask the user for their last name. Print "Hello" followed by the user's first name and last name on one line, separated by a space. You can use both approaches that are mentioned above.

You can refer to Output topic if you need help with the print() function.

Exercise 2.5.1 - Model Answer - Make sure to work out the exercise before checking the model answer.