The input () Function
To get input from the user in Python, you can use the intuitively named input function. For example, a game can ask for the user's name and age as input and use them in the game. The input function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped). Even if the user enters a number as input, it is processed as a string.
print("Tell me anything...")
anything = input()
print("Hmm...", anything, "... Really?")
The input statement needs to be followed by parentheses. You can provide a string to input() between the parentheses, producing a prompt message. For example 1:
name = input("Enter your name: ")
print("Hello, " + name)
Let's assume we want to take the age of the user as input.We know that the input() function returns a string. To convert it to a number, we can use the int or float () function: For example 2:
#Testing TypeError message
anything = input("Enter a number: ")
something = anything ** 2.0
print(anything, "to the power of 2 is", something)
---------------
Traceback (most recent call last):
File ".main.py", line 4, in <module>
something = anything ** 2.0 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'
The problem here is that we tried to square a string value accompanied by a float - not going to work
#Testing TypeError message
anything = float(input("Enter a number: "))
something = anything ** 2.0
print(anything, "to the power of 2 is", something)
------------------
Enter a number 4
4.0 to the power of 2 is 16
Last updated
Was this helpful?