0% found this document useful (0 votes)
19 views

Python For Beginners - A Practic - Daniel Correa - Part33

Uploaded by

Kabir West
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
19 views

Python For Beginners - A Practic - Daniel Correa - Part33

Uploaded by

Kabir West
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 3
mation in plain text files (txt) or comma-separated value files (CSV), among others. int, float, and str functions The int function allows us to convert a number or a text to int type. The float function allows us to convert a number or text to float type. The str function allows us to convert a value to str type. To all of the above functions, we must pass the value to convert in parentheses (as an argument). The value passed as an argument must be a valid value to convert. For example, we can execute the code int("3") since the text sent as an argument contains a valid value to convert to int. However, we cannot ex- ecute int("Hello") since “Hello” cannot be represented numerically and, therefore, cannot be converted to int. The following code shows how to correct the code to “calculate half of the age” so that it does not throw an error. In this case, we use the int function to convert the value collected by the input function to int type. In this case, line 2 can be executed since it will perform a division between int values, which is valid. And finally, half of the age will be calculated and printed (see execution in Figure 6-3). Code and execute 1. age =int(input("Enter your age: ")) 2. halfAge = age/2 3. print(halfAge) Enter your age: 21 16.5 Figure 6-3. Execution of the previous code. The following code shows the differences when con- verting values received by the input function into different data types. Line 1 shows how to receive the father’s age from the keyboard (as there is no conver- sion, the variable fatherAge will be of type str). Line 2 shows how to receive the mother’s age from the key- board (as there is a conversion, the variable mother- Age will be of type int). Line 3 shows how to receive the father’s height from the keyboard (as there is a conversion, the variable fatherHeight will be of type float). Finally, the type and value of each variable are printed on the screen (see Figure 6-4). Code and execute fatherAge = input('Enter age: ") motherAge = int(input("Enter age: ")) fatherHeight = float(input("Enter height: ")) print(type(fatherAge)) print(type(motherAge)) print(type(fatherHeight)) print(fatherAge) print(motherAge) PO OR ee oe print(fatherHeight) Enter age: 30 Enter age: 29 Enter height: 179.3 30 29 179.3

You might also like