Skip to content

Instantly share code, notes, and snippets.

@MillerAdulu
Last active September 24, 2019 15:49
Show Gist options
  • Save MillerAdulu/da2d531185d1b10fbd68e14850ed796b to your computer and use it in GitHub Desktop.
Save MillerAdulu/da2d531185d1b10fbd68e14850ed796b to your computer and use it in GitHub Desktop.

Introduction to Python

Visit: bit.do/websec-gist for links to resources


Variables

  • Variables are containers for storing data values.

  • Unlike other programming languages, Python has no command for declaring a variable. It's created the moment a value is first assigned to it.

Example

x = 5
y = "Angie"
print(x)
print(y)

  • Variables do not need to be declared with any particular type and can even change type after they have been set.

Example

x = 4 # x is of type int
x = "Angie" # x is now of type str
print(x) 
  • String variables can be declared either by using single or double quotes

Example

x = "Angie"
# is the same as
x = 'Angie'

  • Variable names should adhere to the following rules:

    • can have a short name (like x and y) or a more descriptive name (age, carname, total_volume)

    • Start with a letter or the underscore character

    • Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

    • Are case-sensitive (age, Age and AGE are three different variables)

    • Cannot start with a number

  • Python allows you to assign values to multiple variables in one line

Example

x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

  • The Python print statement is often used to output variables.

  • To combine both text and a variable, Python uses the + character

Example

x = "awesome"
print("Python is " + x) 

  • The + character can also be used to add a variable to another variable

Example

x = "Python is "
y = "awesome"
z =  x + y
print(z)
  • For numbers, the + character works as a mathematical operator

Example

x = 5
y = 10
print(x + y) 

  • Combining a string and a number results in an error

Example

x = 5
y = "John"
print(x + y)
  • In addition, strings can be interpolated using the f string formatter

Example

x = "Angie"
print(f'I am { x }')

  • Global variables are those created outside of a function and can be used both inside and outside of a function

Example

x = "awesome"
def myfunc():
  print("Python is " + x)
myfunc()

  • If a variable with the same name inside a function is created, it will be local, and can only be used inside the function. The global value remains unchanged.

Example

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x) 

  • The global keyword can be used to create a global variable inside a function

Example

def myfunc():
  global x
  x = "fantastic"


myfunc()

print("Python is " + x) 

  • To change the value of a global variable inside a function, refer to the variable by using the global keyword

Example

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x) 

Data-Types

  • Python has the following data types built-in by default, in these categories:
Type Example
Text str
Numeric int, float, complex
Sequence list, tuple, range
Mapping dict
Set set, frozenset
Boolean bool
Binary bytes, bytearray, memoryview

  • The data type of any object can be gotten by using the type() function

Example

x = 5
print(type(x))
  • The data type is set when you assign a value to a variable

Conditional statements

They perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. They are handled by if statements in Python.

Example

If Statements
# Declare these variables
a = 9

b = 0

if(a):
    print('value a is available')
if (a > b):

    print('a is greater than b') 

If else statements

c = 2
d = 5

if(c > d):

    print('c is greater than d')

else:

    print('d is greater than c')

Elif statements

num = 10

if (num == 0):

  print('Number is Zero')
  
elif (num > 5):

  print('Number is greater than 5')
  
else:
  print('Number is smaller than 5')

Nested If statements

number = 5

if (number > 0):

  print('number is positive')

  if (number < 10):
    
    print('number is less than 10')

Functions

Example

def my_function():
  print("Hello from a function")

my_function()
def my_function():
  print("Sample Function")

my_function()

Classes and objects

Python is an “object-oriented programming language.” This means that almost all the code is implemented using a special construct called classes. Classes are used to keep related things together.

Example

To create a class, use the keyword class

class Person:
  x = 5

The class person can then be used to create objects as follows:

p1 = Person()
print(p1.x)

The __init__() function

All classes have the __init__() function which is always executed automatically when the class is being instantiated.

This function can be used to assign values to object properties, or other operations that are necessary when the object is being created.

Example
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)
print(p1.name)
print(p1.age)

Objects can also contain methods.

Example

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def my_func(self):
    print(f"Hello! My name is { self.name }")

p1 = Person("Angie", 16)
p1.my_func()

The self parameter

It's a reference to the current instance of the class and is used to access variables that belong to the class.

It doesn't have to be named self but it has to be the first parameter of any function in that class.


Example

class Person:
  def __init__(a, name, age):
    a.name = name
    b.age = age

  def myfunc(b):
    print("My name is " + b.name)

p1 = Person("Angie", 16)
p1.myfunc()

# Modify Objects
p1.age = 40

# Delete properties
del p1.age

Creating modules

What is a module?

Consider a module as a to be a form of a library. It is a file having a set of functionality you can use in your application.


Example

Define Module
# greetingsmodule.py

import platform

def greeting(name):
   print("Hello, " + name)

# Variables in Module

person1 = {
 "name": "John",
 "age": 36,
 "country": "Norway"
}

def checkplatform():
    x = platform.system()
    print(x)

Use Module

The module can be used by using the import statement

# Use a Module

import greetingmodule

# Re-naming a Module
# Create an alias for mymodule called mx:

import greetingmodule as md 

# Import From Module

# You can choose to import only parts from a module, by using the from keyword.

from greetingmodule import person1

print (person1["age"])

greetingmodule.greeting("Jonathan")

a = md.person1["age"]
print(a)

md.checkplatform()

Exception handling

This is the process of responding to unexpected events when a computer program runs.

The try, except and finally block is used to handle exceptions: ● try tests a block of code that may contain errors ● except handles the error(s) ● finally runs irregardless of whether errors exist or not. Mostly used to clean up


Example

try:
  print(x)

except:
  print("something went wrong")

finally:
  print("The try except is finished")

File handling

  • Includes creating, reading, updating and deleting files.

  • The key to handling files is to use the “open()”. Which takes in 2 parameters, the filename and mode.

  • The mode can be:

    • x - Create

    • r - Read

    • w - Write

  • The read() function is used to read a file.

  • There are 2 ways to write to a file:

    • Append ("a") - Adds to the end of a file

    • Write("w") - Overrites the existing content in a file


Example

fileName = "demo.txt"
import os

createFile = open(fileName, "x")

try:

    readFile = open(fileName, "rt")
    print(readFile.read())
    readFile.close()

    writeFile = open(fileName, "a")
    writeFile.write("\n Something new")
    writeFile.close()

    readFile = open(fileName, "rt")
    print(readFile.read())
    readFile.close()

    # Delete file
    # os.remove(fileName)
except:
    print("something went wrong")
finally:
    print("The try except is finished")

Directory navigation

Example

import  os

#returns the current working directory in the form of a string
os.getcwd()
print(os.getcwd())

#Gets Current Directory
os.listdir()
print(os.listdir())

#List Directories and Files
os.mkdir('test')
os.listdir()
print(os.listdir())

#Renaming a Directory or a File
os.rename('test','new_one')
os.listdir()
print(os.listdir())

#Removing Directory or File
os.rmdir('new_one')
os.listdir()
print(os.listdir())

Process creation

The fork() function creates a separate address space for a child process. The child has an exact copy of all the memory of the parent process. The execution of the parent and child process is independent of each other.

With the return value of fork() we can decide in which process we are; 0 means that we are in the child process while greater than 0 means that we are in the parent process. A negative return value means that an error occurred while trying to fork.


Example

import os


def child():
    print("Running in child process".format(os.getpid()))
    print("\tpid: {}".format(os.getpid()))
    os._exit(os.EX_OK)


def main():
    newpid = os.fork()
    if newpid == 0:
        child()
    else:
        print("Running in parent process... {}".format(os.getpid()))
        print("\tParent pid: {}".format(os.getpid()))
        print("\tChild pid: {}".format(newpid))


if __name__ == "__main__":
    main()

Threads

A thread is an entity in a process. Threads allow for multiple tasks to run in parallel.


Example

import threading
import time


def cube(num):
    print("Starting cube in thread {}".format(threading.current_thread().name))
    time.sleep(1)  # Simulate slow execution by sleeping
    print("Cube: {}".format(num * num * num))

def square(num):
    print("Starting square in thread {}".format(
        threading.current_thread().name))
    time.sleep(1)  # Simulate slow execution by sleeping
    print("Square: {}".format(num * num))

def main():
    print("Active threads: {}".format(threading.active_count()))
    t1 = threading.Thread(target=square, args=(100, ))
    t2 = threading.Thread(target=cube, args=(100, ))

    t1.start()
    t2.start()
    print("Active threads: {}".format(threading.active_count()))

    # join() stops the execution of the current program until a thread completes
    t1.join()
    t2.join()

    print("Active threads: {}".format(threading.active_count()))

    print("Done!")

if __name__ == "__main__":
    main()

Inter-process communication & Client-server programming basics

Definitions

Server: A computer or computer program which manages access to a centralized resource or service in a network.

Client: A computer or a computer program that accesses and utilizes resources from a server.


Approaches to client-server implementation in Python

1. Sockets

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket (node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server. They are the real backbones behind web browsing. In simpler terms there is a server and a client.


Example

Server
import socket
import sys

#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind the socket to the port
server_address = ('localhost', 10000)
print ('starting up on %s port %s' % server_address)
sock.bind(server_address)

#Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print ( 'waiting for a connection')
    connection, client_address = sock.accept()

    try:
        print ('connection from', client_address)

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(100)
            print('received "%s"' % data)
            if data:
                print ( 'Replying..')
                connection.sendall(b'Message was received, Thank you')
                print ( 'Response was sent.')
            else:
                print ('no more data from', client_address)
                break

    finally:
        # Clean up the connection
        connection.close()

Client
import socket

#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print ('connecting to %s port %s' % server_address)
sock.connect(server_address)

try:

    # Send data
    message = 'This is the message sent to server'
    print('sending "%s"' % message)
    sock.sendall(b'This is the message.  It will be repeated.')

    # Look for the response
    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = sock.recv(100)
        amount_received += len(data)
        print ('received "%s"' % data)

finally:
    print ('closing socket')
    sock.close()

2. Http

This approach uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, which are forwarded by their computers' HTTP clients.

An HTTP web server is nothing but a process that is running on your machine and does exactly two things:

  1. Listens for incoming http requests on a specific TCP socket address (IP address and a port number which I will talk about later)

  2. Handles this request and sends a response back to the user.


Example

Server
import http.server
import socketserver

PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

Client
import requests as req

resp = req.get("http://localhost:8080")
print(resp.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment