Menu Close

Python input() Method

In Python, it is often useful to be able to take inputs from the user. These can be used for testing whether an algorithm works, or for simple programs without a guided user interface.
The syntax for an input is below:

var = input(“message”)

The default value type for these inputs are strings, however they can be cast to other datatypes such as integers or lists.

Example 1:

name = input(“Please enter your name: ”)
print(“Hello”, name)

Input:

Please enter your name: Felix

Output:

Hello, Felix

In the example above, we used a simple input to greet the user.

Example 2:

testValue = int(input(“Please enter a number: “))
print(testValue * 2 – 3)

Input:

Please enter a number: 42

Output:

81

In the code above, the input needed to be cast to an integer to perform mathematical operations on it.

Example 3:

testValue = input(“Please enter names separated by commas: \n”)
nameList = testValue.split(“, “)

print(nameList)

Input:

Please enter names separated by commas:
Violet, Victoria, Thomas, Alice, Mason

Output:

[“Violet”, “Victoria”, “Thomas”, “Alice”, “Mason”]

In the example above, we use an escape character to have the input values inserted in the line below. We are also able to use the split() method to turn one input value into multiple.

Posted in Embedded Programming Language, Python

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!