Variables and Data Types¶
To declare variables in Python:
>>> a = 3 # assign the integer value 3 to the variable a >>> b = 4.0 # assign the decimal value 4.0 to the variable b >>> c = '1' # assign the string '1' to the variable c >>> a + b # adding two numbers 7.0 >>> a + c # adding number and string (This is not allowed and will produce an error)
Commonly used data types include int, float, str and bool. To determine the datatype of a variable:
>>> a = 3 >>> type(a) <type 'int'> >>> b = 4.0 <type 'float'> >>> c = 'hello' >>> type(c) <type 'str'> >>> d = True >>> type(d) <type 'bool'>
Conversion between Data Types¶
Use the following functions for conversion between data types: float(x),int(x), str(x)
>>> a = 5 # int >>> b = float(a) # convert to float >>> b 5.0 >>> c = str(a) # convert to string >>> c '5' >>> d = int(4.6) # convert to int, take note of the round down >>> d 4
For numbers, the usual mathematical rules apply. You can use any of the following operations: *, /, +, - on numbers. Take note of the division operator.
>>> 1/2 # returns integer value 0 >>> 1/2.0 # returns decimal value 0.5
Take note of the following operations on string
>>> '1' + '2' # concatenation instead of addition '12' >>> '1' * 5 # This is valid in Python '11111'
Summary of Mathematical Operators
Symbols Operations Examples Outputs + Addition a = 1+2 3 - Subtraction a = 2-1 1 * Multiplication a = 2*2 4 / Division a = 5.0/2 2.5 // Truncating Division a = 5.0//2 2.0 % Modulo a = 5%2 1 ** Power a = 5**2 25
Ready for some practice? Test your understanding at PySchools: Variables and Datatypes.