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

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. 

More about input() and type casting

Having a team consisting of the trio input() - int() - float() opens up a lot of new possibilities. 

You'll eventually be able to write complete programs, accepting data in the form of numbers, processing them and displaying the results. 

Of course, these programs will be very primitive and not very usable, as they cannot make decisions, and consequently are not able to react differently to different situations. 

This is not really a problem, though; we'll show you how to overcome it soon. 

Our next example refers to the earlier program to find the length of a hypotenuse. Let's rewrite it and make it able to read the lengths of the legs from the console. 

Check out the editor window - this is how it looks now. 

The program asks the user twice for both legs, lengths, evaluates the hypotenuse and prints the result. 

Run it and try to input some negative values. 

The program - unfortunately - does not react to this obvious error. 

Let's ignore this weakness for now. We'll come back to it soon. 

Note that in the program that you can see in the editor, they hypo variable is used for only one purpose -t save the calculated value between the execution of the adjoining line of code. 

As the print() function accepts an expression as its argument, you can remove the variable from the code.

Just like this: 

leg_a = float(input("Input first leg length: "))
leg_b = float(input("Input second leg length: "))
print("Hypotenuse length is", (leg_a**2 + leg_b**2) ** .5)

Type casting

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

Description

Type casting
No tags specified