An Introduction to Python For Undergraduate Engineers/Numeric Data Types

From Wikibooks, open books for an open world
Jump to: navigation, search

In python, values can be saved as one of several different numeric data types. The main types that you will encounter to start with are integer values (whole numbers) and floating-point values. Note that python always rounds down to the nearest whole number when using integers. (This is due to be changed in python version 3). When you enter a value into python it will automatically decide what data type it is, so for example:

Typing 8 will create an integer value. Typing 8.0 will create a floating point value.

From thereon, python will treat that value as either an integer of floating (decimal) number.


You can convert between them using the int() and float() functions. For example:

   my_variable = 8    #Creates a variable and assigns it the integer value 8
my_variable_float = float(my_variabe) #Creates a new variable with a floating point value of 8.0

Notice that after a # symbol, the python interpreter ignores everything until the next line. This allows you to put comments in your code reminding you of what each line in your program is doing.

Rounding Numbers[edit]

The built in function round() will round a number up or down to the nearest whole number, for example:

   round(3.5) will return the answer 4.