Prince-linux / python-learning

for learning Python
MIT License
1 stars 0 forks source link

Conversion with int() #6

Closed lcabrini closed 9 years ago

lcabrini commented 9 years ago

The int() function can be used to convert from other data types to integers, but only where this is possible.

Create a wiki page called Type Conversion, and add a section on Conversion to Integer. Try the following conversions (in the interactive python interpreter) and report the results in a table on the wiki page. Indicate what is returned, or ERROR if the conversion was not successful.

>>> int(4)
>>> int(-3.11)
>>> int("5")
>>> int("-7")
>>> int("5.68")
>>> int("five")
>>> int(4j)
>>> int("4 + 9 - 1")
>>> int("5x")

Using this create a program called avg.py that asks the user to enter ten numbers, then prints their average. Place the code in the folder src/average.

Prince-linux commented 9 years ago

My script works perfectly with the default python but when I run python3 and enter floating numbers I get an error output Why is it so? And pls help me out

Prince-linux commented 9 years ago

I have pushed it here on github . Kindly look at it and help me out

lcabrini commented 9 years ago

When you do a commit that relates to an issue but you don't want to close it, because it is not complete, then you can write refs #6 in the commit message. That adds a reference here on github.

lcabrini commented 9 years ago

Well, you cannot actually convert a string that represents a floating point number to an int directly. If you wish to do this, the correct way would be:

i = int(float("2.3"))

Beware however, that i will be 2, since the decimal part will be removed. Also notice that the conversion is supposed to be to int, so if the user enters a floating point number, that should be considered a wrong input.