Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

The input() function with an argument

The input() function can do something else: it can prompt the user without any help from print().

We've modified our example a bit, look at the code:

anything = input("Tell me anything...")
print("Hmm...", anything, "...Really?")

Note:

  • the input()  function is invoked with one argument - it's a string containing a message
  • the message will be displayed on the console before the user is given an opportunity to enter anything
  • input() will do its job

The variant of th einput() invocation simplifies the code and makes it clearer. 

The result of the input() function 

We've said it already, but it must be unambiguously stated once again: the the result of the input() function is a string.

A string containing all the characters the user enters from the keyboard. It is not an integer or a float. 

This means that you mustn't use it as an argument of any arithmetic operation, e.g., you can't use this data to square it, divide it by anything, or divide anything by it. 

anything = input("Enter a number: ")
something = anything ** 2.0
print(anything, "to the power of 2 is", something)

The input() function - prohibited operations

Look at the code in the editor. run it, enter any number, and press Enter. 

What happens? 

Python should give you the following output: 

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 last line of the sentence explains everything - you tried to apply the ** operator to 'str' (string) accompanied with 'float'

This is prohibited. 

This should be obvious - can you predict the value of "to be or not to be" raised to the power of 2? 

We can't. Python can't either. 

Have we fallen into a deadlock? Is there a solution to this issue? Of course there is. 

 

The input() function with an argument

David Khieu
Module by David Khieu, updated more than 1 year ago

Description

The input() function with an argument
No tags specified