...
Operator | Description | Example |
---|---|---|
+ | plus | 10 + 3 = 13 |
- | minus | 10 - 3 = 7 |
* | multiply | 10 * 3 = 30 |
/ | divide - returns float | 10 / 3 = 3.333 |
// | divide (whole number) | 10 // 3 = 3 |
% | modulus - remainder of division | 10 % 3 = 1 |
** | exponent | 10 ** 3 = 1000 |
+=, *=, ... | Augmented Assignment Operators | x+=3 = x=x+3 |
Comparison Operators
Operator | Description |
---|---|
> | Greater than |
>= | Greater than or equal |
< | Less than |
<= | Less than or equal |
== | Equal |
!= | Not Equal |
Logical Operators
Operator | Description | Example |
---|---|---|
and | logical and | price =20 print( price >10 and price < 30 ) |
or | logical or | price =20 print( price >10 or price < 30 ) |
not | price = 20 print (not price >10) |
If Statements
If statements use indentation instead of curly brackets in Java.
Code Block |
---|
temperature = 25 if temperature > 30: print("It's a hot dat") print("Drink plenty of water") elif temperature > 25: print("It's a nice day") else: print("It's a cold day") print("Done") |
While Loops
While loops use indentation instead of curly brackets in Java.
Code Block |
---|
i=1 while i<=1_000: print(i) i=i+1 |
Notice in the above example we used an underscore to make reading the integer 1000 easier to read.
Lists
Lists are indexed starting at 0.
Code Block |
---|
names = ["Bob", "Sam", "John"]
print (names[0])
names [1] = "Samantha"
# to get second last element
print (names[-2])
# subset of list from 0 to 3 but excluding the end index 3.
# does not change original list
print (names[0:3]) |
List Methods include append, insert, etc..
Code Block |
---|
names = ["Bob", "Sam", "John"]
names.insert(1,"Barbara")
names.append("Tom")
print (names)
print ("Sam" in names)
print (len(names)) |
For Loops
Code Block |
---|
numbers = [1,2,3,4,5]
for item in numbers:
print(item) |
Range Function
A range function creates a list up to but not including the stop value supplied.
range(start, stop, step)
Parameter | Description |
---|---|
start | Optional. An integer number specifying at which position to start. Default is 0 |
stop | Required. An integer number specifying at which position to stop (not included). |
step | Optional. An integer number specifying the incrementation. Default is 1 |
Code Block |
---|
numbers = range(1,5)
for number in numbers:
print(number)
# Output:
1
2
3
4 |
Tuples
Tuples are just like lists but are immutable (can not be changed). Use round brackets to define a tupple.
Code Block |
---|
numbers = (1,2,3,4) |
Cheat Sheet
References
Reference | URL |
---|---|
Python for Beginners - Learn Python in 1 Hour | https://www.youtube.com/watch?v=kqtD5dpn9C8 |
Python Cheat sheet for hackers and developers | https://hakin9.org/python-cheat-sheet-for-hackers-and-developers/ |
...