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

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. 

 

Type Casting

Python offers two simple functions to specify a type of data and solve this problem -here they are: int() and float() 

Their names are self-commenting:

  • the int() function takes one argument (e.g., a string: int(string)) and tries to convert it into an integer; if it fails, the whole program will fail too (there is a workaround for this situation, but we'll show you this a little later
  • the float() function takes one argument (e.g., a string: float(string)) and tries to convert it into a float (the rest is the same).

This is very simple and very effective. Moreover, you can invoke any of the functions by passing the input() results directly to them. There's no need to use any variable as an intermediate storage. 

We've implemented the idea in the editor - take a look at the code. 

Can you imagine how the string entered by the user flows from input() into print()? 

Try to run the modified code. Don't forget to enter a valid number.

Check some different values, small and big, negative and positive. Zero is a good input, too. 

The input() function - prohibited operations

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

Description

The input() function - prohibited operations
No tags specified