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.
name = input(“Please enter your name: ”) print(“Hello”, name)
Please enter your name: Felix
In the example above, we used a simple input to greet the user.
testValue = int(input(“Please enter a number: “)) print(testValue * 2 – 3)
Please enter a number: 42
In the code above, the input needed to be cast to an integer to perform mathematical operations on it.
testValue = input(“Please enter names separated by commas: \n”) nameList = testValue.split(“, “) print(nameList)
Please enter names separated by commas: Violet, Victoria, Thomas, Alice, Mason
[“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.