Topics
Variable Declaration
To declare variables in Python:
# assign the integer value 3 to the variable a >>> a = 3 # assign the decimal value 4.0 to the variable b >>> b = 4.0 # assign the string '1' to the variable c >>> c = '1' # adding two numbers >>> a + b 7.0 # adding number and string (This is not allowed and will produce an error) >>> a + c
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'>
Data Type Conversion
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
Mathematical operations
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 |
Code Snippets
This section will contain some code snippets to show some practical use of the topic that you have learnt.
# Swapping of variable # --------------------- >>> a = 3 >>> b = 4 >>> a, b (3, 4) # doing the swap >>>a, b = b, a >>> a, b (4, 3) # values swapped # Checking for even number # ------------------------ >>> a = 6 # if the remainder of 'a' dividing by 2 is 0, 'a' is even number >> a % 2 == 0 True