Python

Strings, Math and Variables & Methods

#print strings
print("Hello, World!") #double quotes
print("\n") # new line
print('Hello, World!') #single quotes

print(""" This string runs 
multiple lines """) # triple quote for multi line 

print("This is "+"a string") # we can also concatenate, this is combining variables in a string

#Maths
print(50+50) # add
print(50-50) # subtract
print(50*50) # multiply
print( 50/50) #divide
print(50+50-50*50/50) # PEMDAS
print(50**2) #raising to power. exponents
print(50%6) #modulo, get remainder
print( 50//6) # divides w/ no remainder

# Variables and modules
quote="All is fair in love and war"
print(quote.upper()) # uppercase
print(quote.lower()) # lowercase
print(quote.title()) # title

print(len(quote)) # gets length of quote

name="Heath"# string
age=30# int
gpa=3.7# float

print(int(age)) # casting int as int
print(int(30.9)) # casting float as int

print("Hello, my name is "+name+" and I am "+str(age) +" years old!")

age+=1
print(age)

birthday=1
age+=birthday
print(age)

print('\n')

Functions

# Functions
print("This is an example of a function")

defwho_am_i():
  name="Heath"
  age=30
  print("My name is "+name+" and I am "+str(age) +" years old!")
  
who_am_i()

# adding params
defadd_one_hundred(num):
  print(num+100)

add_one_hundred(100)

# multiple params
defadd(x,y):
  print(x+y)
  
add(7,7)

defmultiply(x,y):
  print(x*y)
  
multiply(7,7)

defsquare_root(x):
  print(x**0.5)
  
square_root(25)

defnl():
  print('\n')
  
nl()

Relational & Boolean Expressions

# boolean expressions (true/false)
print("Boolean Expressions:")
bool1=True
bool2=3*3==9
bool3=False
bool4=3*3!=9

print(bool1,bool2,bool3,bool4)
print(type(bool1))

nl()

# Relational and boolean expressions

greater_than=7>5
less_than=5<7
greater_than_equal_to=7>=7
less_than_equal_to=7<=7

test_and1=(7>5) and(5<7)  # True
test_and2=(7<5) and(7>5)  # False
test_or=(7>5) or(5<7)  # True
test_or2=(7<5) or(5>7)  # False

test_not=notTrue# False

nl()

Conditional statements

defdrink(money):
  ifmoney>=2:
    return"You've got yourself a drink"
  else:
    return"yeah, NO. get outta here"

print(drink(2))
print(drink(1))

defalcohol(age,money):
  if(age>=21) and(money>=5):
    return"Lucky you, it's happy hour!"
  elif(age>=21) and(money<5):
    return"not enought bud"
  elif(age<21) and(money>=5):
    return"Nice try kid"
  else:
    return"You're broke and too young"
  
print(alcohol(21,5))
print(alcohol(21,4))
print(alcohol(20,4))
  
nl()

Lists and Tuples

# lists []
movies=["Hangover", "The Perkins", "Spiderman 3"]
  
print(movies[1]) # returns the second item
print(movies[0]) # returns the first item
print(movies[1:4])
print(movies[1:])
print(movies[:2])
print(movies[-1]) 

print(len(movies))
movies.append("JAWS")
print(movies)

movies.pop()
print(movies)

movies.pop(0)
print(movies)

nl()

# Tuples - static, ()
grades=("a", "b", "c", "d", "f")
print(grades[1])

Looping

# Loops
vegetables=["cucumber", "spinach", "cabbage"]
forxinvegetables:
    print(x)
    
# While loops - execute so long as true
i=1
whilei<100:
  print(i)
  i+=1

Importing Modules

#!/bin/python3

import sys #system funtions and parameters

print (sys.version)
#this works because sys isn't imported by default

argv #argument, in bash we used $ symbol, here we use argv

#to import specific things from a module for ex we use:
from datetime import datetime
print (datetime.now())

#to import with an alias we use:
from datetime import datetime as dt
print (dt.now())

#we use this commands to import prexisting modules from python, other times we would have to improve the script by downloading other modules

Advanced Strings

#!/bin/python3

my_name = "Sergio"
print (my_name[0]) #print first letter from my_name
print (my_name[-1]) #print last letter from my_name

sentence = "This is a sentece."
print(sentence[:4]) #this will print the first word, we need to know #the amounth of letters

print(sentence.split()) #every space split the sentence

sentence_split = sentence.split()
sentence_join = ' '.join(sentence_split) #join a space
print(sentence_join)

quote= "He said, 'give me all your money'" #way to have quotes inside #of the string
quote= "He said, \"give me all your money\" #way to have double quotes #inside a string , from the first \ to the last \ ignore the double "
print(quote)

too_much_space = "    hello"
print(too_much_space.strip()) #this will print just hello

print("A" in "Apple") #this will print True
print("a" in "Apple") #this will print False, cause is capes sensitive

letter = "A"
word = "Apple"
print(letter.lower() in word.lower()) #improved, we put all in lower #case to find out what we want

movie = "The Hangover"
print("My favorite movie is {}.".format(movie))
#output is going to be My favourite movie is The Hangover

Dictionaries {}

#!/bin/python3

drinks = {"White russian": 7, "Old Fashion": 10, "Lemon Drop": 8}
#here drink is key, price is value
print(drinks)

employees = {"Finance": ["Bob, "Lina", "Tinda"], "IT": ["Gene", "Louise", "Teddy"], "HR": ["Jimmy Jr", "Mort"]}
print(employees)

employees = ['Legal'] = ["Mr Frond"] #add new key:value pair
print(employees)

employees.update({"Sales": ["Andy", "Ollie"]}) #add new key:value pair
print(employees)

drinks = ['White Russian'] = 8 #update this key:value pair
print(drinks)

print(drinks.get("White Russian")) #gets the value of that key

Sockets

#!/bin/python3

import socket

HOST = '127.0.0.1'
PORT = 7777

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#very common syntax to define s
#.AF_INET is IP before .SOCK_STREAM i a Port

s.connect((HOST,PORT))

Basic Port Scanner

#!/bin/python3

#This is not the best way to build a Port Scanner, there are better ways and better tools
#This help us to understand and think logicly

import sys
import socket
from datetime import datetime

#Define our target
if len(sys.argv) == 2:
	target = socket.gethostbyname(sys.argv[1])
	#Translate hostname to IPv4
	#argv[1] is same thing as $1 in bash
else:
	print("Invalid amount of arguments.")
	print("Synthax: python3 scanner.py <ip>")
	
#Add a pretty banner
print("-" * 50)
print("Scaning target" +target)
print ("Time started: " +str(datetime.now()))
print("-" * 50)

try:
	for port in range(50,85):
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		socket.setdefaulttimeout(1) #one second timeout
		result = s.connect_ex((target,port)) #returns an error indicator
		if result == 0:
			print("Port {} is open".format(port))
			s.close()
except KeyboardInterrupt: #Clean exit, in linux ctrl + c means stopping
	print("\nExiting program.")
	sys.exit()

except socket.gaierror:
	print("Hostname could not be resolved")
	sys.exit()
	
except socket.error:
	print("Couldn't connect to server.")
sys.exit()

argparse library

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--one', '-o', help='Prints Hello name')
parser.add_argument('--two', '-t', help='Prints Bye name')
parser.add_argument('--three', '-r', help='Prints Good Afternoon name')

args = parser.parse_args()

if args.one:
    print(f'Hello {args.one}')
elif args.two:
    print(f'Bye {args.two}')
elif args.three:
    print(f'Good Afternoon {args.three}')
else:
    parser.print_help()




parser = argparse.ArgumentParser(add_help=True, description="Description")
parser.add_argument('--one', '-o', action='store', help='Prints Hello name')
parser.add_argument('--two', '-t', action='store', help='Prints Bye name')
parser.add_argument('--three', '-r', action='store', help='Prints Good Afternoon name')

args = parser.parse_args()





import argparse
import sys

usage = '''script.py [-h] [--one "NAME" | --two "NAME" | --three "NAME"]

Prints a greeting message followed by the provided name.'''

parser = argparse.ArgumentParser(add_help=True, description="Description", usage=usage)
parser.add_argument('--one', '-o', action='store', help='Prints Hello name')
parser.add_argument('--two', '-t', action='store', help='Prints Bye name')
parser.add_argument('--three', '-r', action='store', help='Prints Good Afternoon name')

if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

options = parser.parse_args()



parser.add_argument('--one', '-o', action='store', help='Prints Hello name', required=True)
parser.add_argument('--two', '-t', action='store', help='Prints Bye name', required=True)
parser.add_argument('--three', '-r', action='store', help='Prints Good Afternoon name', required=True)


import argparse
import sys

parser = argparse.ArgumentParser(add_help=True, description="Description")
parser.add_argument('--one', '-o', action='store', help='Prints Hello NAME')
parser.add_argument('--two', '-t', action='store', help='Prints Bye NAME')
parser.add_argument('--three', '-r', action='store', help='Prints Good Afternoon NAME')

if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

options = parser.parse_args()

Last updated