Python
Python Operators
Operators are used to perform operations on data
Arithmetic Operators:
| Operator | Example | Answer |
|---|---|---|
| Addition(+) | a=1, b=2 print(a+b) | 3 |
| Subtraction(-) | a=1, b=2 print(b-a) | 1 |
| Multiplication(*) | a=2, b=3 print(a*b) | 6 |
| Division(/) | a=6, b=3 print(a/b) | 2 |
| Floor division(//) | a=17, b=2 print(a//b) | 8 |
| Modulus(%) | a=17, b=2 print(a%b) | 1 |
| Exponentiation | a=2, b=3 print(a**b) | 8 |
Assignment Operators: Assigns values to variables. Operators can also be combined such as += when assigning values
| Operator | Example | Answer |
|---|---|---|
| = | a=2 print(a) | 2 |
| += | a=2, a+=2 print(a) | 4 |
Comparison Operators: Compares two values
| Operator | Example | Answer |
|---|---|---|
| equal(==) | print(1==2) | false |
| not equal(!=) | print(1!=2) | true |
| greater than(>) | print(1>2) | false |
| less than(<) | print(1<2) | true |
| greater than or equal to(>=) | print(1>=1) | true |
| less than or equal to(<=) | print(2<=2) | true |
Logical Operators: Compares statements
| Operator | Example | Answer | Description |
|---|---|---|---|
| and | print((1==2) and (2==2)) | false | Both conditions true |
| or | print((1==2) or (2==2)) | true | One condition is true |
| not | print(not((1==1) and (2==2))) | false | Negation |
Membership Operators: checks for a sequence in object
| Operator | Example | Answer | Description |
|---|---|---|---|
| in | print(1 in (1,2,3)) | true | Checks for membership in a sequence |
| in | print(4 in (1,2,3)) | false | Checks for membership in a sequence |
| not in | print(4 not in (1,2,3)) | true | Checks for membership in a sequence |
Identity Operators: Compare the objects
| Operator | Example | Answer | Description |
|---|---|---|---|
| is | a=[‘p’,’q’] b=[‘p’,’q’] c=a print(a is b) | false | Compares the objects not the values |
| print(a is c) | true | Compares the objects not the values | |
| is not | print(a is not b) | true | Compares the objects not the values |
Bitwise Operators: Compare binaries
Bitwise operators are and (&) , or (|) , xor (^) , not (~) , Shift left (<<) , Shift right (>>)