A quick cheat sheet on Python

This is not a complete python 3 tutorial. This just quick note to remember the python 3 syntax.

Python Data Type:

NameTypeDescription
IntegerintNumbers such as 100,200,1337
StringsstrMore than one characters such as “Cyber”
BooleansboolLogical Value: True or False
Floating PointfloatNumbers with decimal point such as: 1.1
ListslistSequence of objects: [“Cyber”,10]
DictionariesdictValue pairs: {“key1″:”Cyber”,”key2″:”Red”}
SetssetCollection of unique objects: {“test”,”test1″}
TuplestupOrdered secquence of objects: (1,”Cyber”)

String

Here is the example of String indexing and slicing:

>>> string= "onetwothree"
>>> string[1]
'n'
>>> string[1:]
'netwothree'
>>> string[2:]
'etwothree'
>>> string[2:5]
'etw'
>>> string[2:5:7] # Start:Stop:Step Size
'e'
>>> 

Format String

>>> print("This is {}".format(string))
This is one two three

>>> print("This is {1}".format(string))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Replacement index 1 out of range for positional args tuple

>>> print("This is {0}".format(string))
This is one two three

>>> print("This is {0}".format(string,string))
This is one two three

>>> print("This is {0} {1}".format(string,string))
This is one two three one two three

>>> print("This is {0} {1}".format(a='One',b='Two'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Replacement index 0 out of range for positional args tuple

>>> print("This is {a} {b}".format(a='One',b='Two')) #Assign Variable for the Format
This is One Two

>>> string.split() #Convert a string to List
['one', 'two', 'three']

>>> print(f'hmmm {test}')
hmmm testing
>>> 
>>> print(f"Here it is %s"%(string))
Here it is TEST
>>> print(f"Here it is %s" %(string))
Here it is TEST
>>> print(f"Here it is {string}")
Here it is TEST

>>> 

Variables

Assign data types a variable to reference later. Variable name cant contain special charcters except _

var1 = "String" #String 

var2 = 1337 # Integer

var3 = True # Boolean

var4 = 1337.1 #Float

var5 = ["Cyber","World", 1337]

var6 = {"key1":"value1","key2":"value2"} #Dictionaries

var7 = {"Test1","Test2"} #Sets

var8 = (1,"Cyber") #Tuples

Python Operators

OperatorDescriptionExampl
==Check If two operands are equal(1==2) is not true
!=Check two operands are not equal(1 != 2) is true
>If the value of left operand is greater than right operand1>2 False
<if the left operand’s value is less than right operand value1<2 True
>=If the value of left operand is greater than right operand or equal1>=2 False
<=if the left operand’s value is less than right operand value or equal1<=2 True
andLogical and check if both is true(1==1) and (3=3) True
orLogical or check if any of operands is true(1==1) or (3==4) True
notLogical not check if the given operand is truenot (1==1) False

Conditional

if (1==1) or (2=1):
    print("Condition is True")

elif (2==2) and (3==3):
    print("Condition is True")

else:
    print("Nothing match?")

Lists

  • Lists are ordered Sequence
  • It supports indexing and slicing lists = [“Cyber”,1337] lists = [“Cyber”,1337]
    lists
    [‘Cyber’, 1337]
    lists[0]
    ‘Cyber’
    lists[:1]
    [‘Cyber’]
    lists[1:]
    [1337]li = [1,2,3]
    lists+li
    [‘Cyber’, 1337, 1, 2, 3]lists[0] = ‘Cyber World’
    lists
    [‘Cyber World’, 1337]lists[0].upper()
    ‘CYBER WORLD’

Nested List:

>>> lists
['Cyber World', 1337]

>>> listing = [1,2]

>>> lists.append(listing)

>>> lists
['Cyber World', 1337, [1, 2]]

>>> lists[2]
[1, 2]

>>> lists[2][0]
1

Useful Available method:
list.append(x): Add an item to the end
list.insert(i,x): insert an item to given postion.
list.remove(x): Remove the first item from the list whose value is equal to x
list.clear(): Remove all items from the list.
list.reverse(): Reverse the elements of the list in place.

Dictionaries

It is key and value pair. Use dictionary when need to retrive value by key name.

dicto = {'key':'val1','key1':'val2'}
print(dicto['key1'])

Tuples

Tuples is immutable, mean, we can’t change or modify Tuples

>>> tupl = (1,2,3)
>>> tupl[0]
1

Loop

For Loop

Looping through list:

list1 = [1,2,3]
for n in list1:
    if n==2:
        print("Loop rach the"+str(n))
    else:
        print('Wtf')

listing = 0

for n in list1:
    listing += listing+n

print(listing)

Looping through a string:

strange = "This is strange"

for s in strange:
    print(s)

Looping through the Dictionary:

d = {'key1':1,'key2':2}
for key,value in d.items():
    print(key)
    print(value)

While Loop

Loop until y=False

>>> y = True
>>> while y:
...     print(x)
...     if x == 10:
...             y=False #Or break statement
...     x += 1
... 
0
1
2
3
4
5
6
7
8
9
10

More to update!!!

Complete Example

#!/usr/bin/python3 
import os
import requests
import socket

def banner():
    print("\nConsider the user input as While Loop\n\n")
    print("\n1. Hello world\n2. Data type\n3. Variables\n4. Operators\n5. Conditional\n6. Loop\n7. Functions\n8. Lists\n9. Tuples\n10. Dictionaries\n11. File i/o\n12. Dir Brute force\n13. Port scan\n14. What Next?\n")
    while True:
        try:

            choice=input("\nSelect something(Only numeric): ")

            if int(choice)==99:
                print("\nExiting...")
                break
            else:
                print("\n")
                conditional(int(choice)) 
        except ValueError:
            print("Not a valid number!\nType 99 to exit!\n")
        except KeyboardInterrupt:
            print("\n\nThanks for your hard work!!!\n\n")
            break

def hello():
    print("Hello Redtm")

def datatype():

    typ='''
    Integer(Ex: 1,2,3 etc) = int
    Strings(Ex: "redtm") = str
    Booleans(True/False) = bool
    float(1.1) =float
    Lists(Ex: ["hello",20]) = list
    Dictionaries(Ex: {"Key":"Value"} = dict
    Sets(Ex: {"hello","redtm"} = set
    Tuples(Ex:(1,"redtm") = tup

    '''
    print(typ)

def variables():

    #Declare variables
    hello="Hello redtm"
    pro=1337
    fl=1337.00
    print("\""+hello+"\""+" is an string variable")
    print("Are you a "+ str(pro)+"?")
    print("This is floating point "+str(fl))
    print("You know strings work like an array? We can get a char from string by index number such as:\n")
    print("hello="+hello)
    print("If we want to get the first char, and reference it like hello[1], we get:"+ hello[1])


def ops():
    print("Some python 3 operators:")
    ops= '''
        ==  | Two operands are equal\n
        !=  | Not Equal\n
        >   | Left is greater than Right\n
        <   | Left value is less than Right value\n
        >=  | Left is greater than or equal to Right\n
        <=  | Left is less than or equal to right\n
        and | If both value is true\n
        or  | If any operands is true\n
        not | if given operand is true\n
        '''
    print(ops)

def conditional(number):

    if number==1:
        hello()
    elif number==2:
        datatype()
    elif number==3:
        variables()
    elif number==4:
        ops()
    elif number==5:
        print("We are already here\n")
    elif number==6:
        loop()
    elif number==7:
        print("We are always using the function")
    elif number==8:
        lists()
    elif number==9:
        tuples()
    elif number==10:
        dictionary()
    elif number==11:
        myfile()
    elif number==12:
        dir()
    elif number==13:
        port_scanner()
    elif number==14:
        what_next()
    else:
        print("What the hell are you doing?")

def loop():
    l=["White hat","Black hat","Grey Hat"]
    c=len(l)

    print("Example of for loop:\n")
    for y in l:
        print(y)

    print("\n Example of While Loop:\n")
    a=1
    while a<c:
        print(str(a)+". "+l[a])
        a+=1

def function():
    print()

def lists():
    print("Using list we can store multiple value in single variables. List can be changed, Appended, or be deleted!")
    #Declaring list

    pentest_methods=["Planning", "Information Gathering", "Vulnerability Assessment", "Exploitation","Reporting",5]
    print("\nWe can consider pentest in "+str(pentest_methods[5])+" stages:\n")
    pentest_methods.pop(5)
    c=1
    for methods in pentest_methods:

        print(str(c)+". "+methods)
        c+=1
    print("\nSome methods can be used such as:\n")
    mtd='''
    list.append(x)\n
    list.insert(x)\n
    list.remove(x)\n
    list.clear()\n
    list.pop(i)\n
    list.count()\n
    '''
    print(mtd+"\n more can be found at: https://docs.python.org/3/tutorial/datastructures.html")


def tuples():
    #Tuple methods
    #t.count(x)
    #t.index(x)

    ofs=("Pentesting","vulnerability assessment","Exploit dev",3)
    print("We have declared a tuple called 'ofs'\n")
    print("There are "+str(len(ofs))+" items in the tuple whereas "+str(ofs[3])+" is an integer value\n")

    print("Tuples almost same as the Lists. Only difference is Tuples can not be changed as the Lists!\n")
    print("Declare tuple: tu=(\"Pentest\",\"Vulnerability Assessment\",\"Exploit Dev\",3)")

    print(str(ofs[3])+" Offsec fields examples are:\n")

    for x in ofs:
        print(x)



def dictionary():
    items={
        "hacker":"A computer genius",
        "vulnerability":"Weakness in computer system",
        "tired":"Never give up"
    }

    print("You should "+items["tired"])
    while True:
        inp=input("Guess some key from the dict: ")
        print(items.get(inp))
        if inp=="x":
            break
    #Change item: dict[key]=value
    # Add item: dict[new_key]=value
    # Remove Item: dict.pop[key]=value

#File Handling
def myfile():
    print("To work with a file, we first need to open specified file with open() function\n")

    mode='''
        "r" = Read - Only to read the file\n
        "w" = Write - Only to write the file\n
        "a" = Append - Append something to the file\n
        "x" = Create - Create the file if not exist\n
    '''
    print("But you need to specify the file opening mode:\n"+mode)
    print("\nLet's do some testing")

    print("Our working directory:"+os.getcwd())
    if (os.path.exists("test.txt")!=True):
        print("Creating test.txt first")
        os.system("touch test.txt")

    f=open("test.txt","a+")
    inpr=input("Type to write: ")
    f.write(inpr)

    print("\nThe content in the file:\n")
    f.seek(0,0)
    print(f.read())

    f.close()


    print("\nMore about file i/o: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\n")

def dir():
    with open("words","r") as w:
        for a in w:
            wrd=a.replace("\n","")
            target="https://rednode.com/"+wrd
            rq=requests.get(target)
            print(target+"\t\t"+str(rq.status_code))


def port_scanner():

    #AF_INET=Protocol
    #SOCK_STREAM=Type Of communication is TCP

    common_ports=(80,443,3306,3389,22)
    for port in common_ports:
        ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        op=ss.connect_ex(("localhost",port))
        if(op==0):
            print(str(port)+" - Open")

        ss.close()    

def what_next():
    print("1. Learn Class and more about network programming.\n2. Access Database using Python.\n3. Learn basic of Regular Expression.\n4. Do multithreading.\n5. Work with modules.\n") 
banner()