Arithmetic Operators
+ Addition |
print(3 + 5) # 8 |
- Subtraction |
print(8 - 6) # 2 |
* Multiplication |
print(1 + 2 + 3 * 3) # 12 |
/ Division |
print(8 / 4) # 2 |
% Mod (the remainder after dividing) |
print(9 % 2) # 1 |
** Exponentiation |
print(3 ** 2) # 9 |
// Divides and rounds down to the nearest integer |
print (16 // 3) # 5 |
Logical Operators
and
Evaluates if all provided statements are True |
5 < 3 and 5 == 5 # False |
or
Evaluates if at least one of many statements is True |
5 < 3 or 5 == 5 # True |
|
not 5 < 3 # True |
Data Structures
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
print(months[0]) # January
print(months[1]) # February
print(months[7]) # August
print(months[-1]) # December
print(months[25]) # IndexError: list index out of range
|
|
|
Assignment Operators
x = 3 y= 4 z=5 |
x, y, z = 3, 4, 5 |
+= Addition Assignment |
a += 1 # a = a + 1 |
-= Subtraction Assignment |
a -= 3 # a = a - 3 |
*= Multiplication Assignment |
a = 4 # a = a 4 |
/= Division Assignment |
a /= 3 # a = a / 3 |
%= Remainder Assignment |
a %= 10 # a = a % 10 |
**= Exponent Assignment |
a **= 10 # a = a ** 10 |
Strings
my_string = 'this is a string!' |
my_string2 = "this is also a string!!!" |
this_string = 'Simon\'s skateboard is in the garage.' |
print(first_word + ' ' + second_word) >> Hello There |
print(len(first_word)) >> 5 |
print(first_word * 5) >> HelloHelloHelloHelloHello |
index into strings >> first_word[0] >> H, first_word[1] >> e |
|
|
Comparison Operators
== Is Equal To |
3 == 5 # False |
!= Not Equal To |
3 != 5 # True |
> Greater Than |
3 > 5 # False |
< Less Than |
3 < 5 # True |
>= Greater Than or Equal To |
3 >= 5 # False |
<= Less Than or Equal To |
3 <= 5 # True |
Strings methods
len(), returns the length of an object, like a string |
print(len("ababa") / len("ab")) >> 2.5 |
type(), check the data type of any variable |
print(type('Hello')) >> str |
'sebastian thrun'.islower() |
True |
'Sebastian Thrun'..count('a') |
2 |
'Sebastian Thrun'..find('a') |
3 |
'Sebastian Thrun'..rfind('a') |
7 |
animal = "dog" action = "bite" print("Does your {} {}?".format(animal, action)) |
Does your dog bite? |
"The cow jumped over the moon.".split() |
['The', 'cow', 'jumped', 'over', 'the', 'moon.'] |
"The cow jumped over the moon.".split(' ', 3) |
['The', 'cow', 'jumped', 'over the moon.'] |
"The cow jumped over the moon.".split('.') |
['The cow jumped over the moon', ''] |
"The cow jumped over the moon.".split(None, 3) |
['The', 'cow', 'jumped', 'over the moon.'] |
|