Introduction to Python

Some useful things regarding the python coding language!

Introduction to Python

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its notable use of significant whitespace. Since I am taking a course on introduction to python at the time of writing, what better way to document it than to write about it!? Btw, I’m gonna be trying to build a port scanner in python at the end of the course! (That will be a separate writeup hehe) So…lets get started!


Strings

  • To print basic text
#!/bin/python3  
#Print string print("Hello, world!") 
print('Hello, world!')
  • To print multiline text
print("""This string runs 
multiple lines dood!""")
  • To print 2 string concatenated together
print("This string is "+"awesome!")
  • To add an empty line spacing in-between outputs
#!/bin/python3  
#Print string print("Hello, world!") 
print('\n') #adds new line 
print('Hello, World!')

Math

  • Basic operations
#!/bin/python3  
#Math 
print(50 + 50) #addition 
print(50 - 50) #subtraction 
print(50 * 50) #multiplication 
print(50 / 50) #division
  • Advanced operations
print(50 + 50 - 50 * 50 / 50) #pemdas 
print(50 ** 2) #exponents 
print(50 % 6) #modulo 
print(50 // 6) #returns whole number

Variables & Methods

  • Declaring a variable and using it later in the program
#!/bin/python3  
#Variables & Methods 
quote = "Control is an illusion" 
print(quote)
  • Using methods to modify the output
print(quote.upper()) #uppercase 
print(quote.lower()) #lowercase 
print(quote.title()) #title 
print(len(quote)) #length of variable
  • Using methods to get properties/values of a certain type
print(len(quote)) #length of variable  
name = "Neeranjan" #String 
age = 19 #int int(19) 
height = 1.8 #float float(1.8)  
print (int(age)) 
print (int(height))
  • Using methods to manipulate the output of text
print("My name is " + name + "and I am " + str(age) + "years old. I am also " + str(height) + "m tall")
  • Increment variable by a certain amount
age += 1 #increase age variable by 1
print(age)
birthday = 1 #increase age variable by birthday variable
age += birthday
print(age)

Functions

  • Defining a function
#Functions
print("\nFunctions--")
def whoAmI(): #This is a function
 name = "Neeranjan" #String
 age = 19 #int int(19)
 height = 1.8 #float float(1.8)
 print("My name is " + name + "and I am " + str(age) + "years old. I am also " + str(height) + "m tall")
  • Running a function
whoami()
  • Adding parameters to a function
#adding parameters
def addOneHundred(num):
 print(num+100)
 
addOneHundred(50)

#adding multiple parameters
def addition(x,y):
 print(x + y)
 
addition(50,55)

def multiply(x,y):
 return x * y #returning value to method != printing
 
print(multiply(5,5))

def squareRoot(x):
 print(int(x ** 0.5))
 
squareRoot(64)
  • Creating functions to speed up simple yet time-consuming tasks
def nl():
 print('\n')


nl()

Boolean Expressions (T/F)

  • Creating basic Boolean expressions that will either return true or false
#Boolean Expressions
print("\nBoolean Expressions--")
bool1 = True
bool2 = 3*3 == 9
bool3 = False
bool4 = 3*3 != 9
print(bool1, bool2, bool3, bool4)
print(type(bool1))
  • Differentiating between STRING True and BOOLEAN
#Boolean Expressions
print("\nBoolean Expressions--")
bool1 = True
bool5 = "True"
print(type(bool1))
print(type(bool5))

Relational and Boolean operators

  • Creating Boolean statements / Variables
nl()
#Relational and Boolean operators
print("\nRelational and Boolean operators--")
greaterThan = 7 > 5
lessThan = 5 < 7
greaterThanEqualTo = 7 >= 7
lessThanEqualto = 7 <=7
#All of the above statements will return True (boolean)
  • Creating statements with AND, OR & NOT
testAnd = (7 > 5) and (5 < 7)  #AND = true statement + true statement will make the whole thing return True
testAnd2 = (7 > 5) and (5 > 7) #AND = true statement + false statement will make the whole thing return False

testOr = (7 > 5) and (5 < 7)  #OR = true statement + true statement will make the whole thing return True
testOr2 = (7 > 5) and (5 > 7) #OR = true statement + false statement will make the whole thing return True

testNot = not True #Returns False
testNot2 = not False #Returns True
  • Refer to Truth table

Conditional Statements

  • Building a simple IF statement
nl()
#Conditional statements
print("\nConditional statements--")

def buyDrink(money):
 if money >= 2:
  return "You've got yourself a drink"
 else:
  return "No drink for you!"
  
print(buyDrink(10))
print(buyDrink(1.5))
  • Building an advance IF statement with multiple conditions
def buyBeer(age,money):
 if (age >= 21) and (money >= 5):
  return "Here is your cold beer!"
 elif (age >= 21) and (money < 5):
  return "Sorry you do not have enough money"
 elif (age < 21) and (money >= 5):
  return "Nice try, kid!"
 else:
  return "You're young, dumb and broke!"
 
print(buyBeer(21,5))
print(buyBeer(20,4))
print(buyBeer(20,5))

Lists

  • Declaring a simple list and then printing it
nl()

#Lists - Have brackets []
print("\nLists--")

shows = ["Mr. Robot", "Money Heist", "Locke and key", "Orange is the new Black"]

print(shows[0]) #Item one in a list is always 0
print(shows[1])
print(shows[0:3]) #Pulls out all values just b4 the last index
print(shows[0:4]) #Pulls out all the values in the list
print(shows[2:])  #Pulls out all the values after the index specified
print(shows[:1])  #Pulls out all the values before the index specified / grabbing 1 item from the list
print(shows[-1])  #Pulls out the last value in the list
#print(len(shows)) #prints the number of items in the list
  • Adding to and removing from the list
shows.append("Sex education")
print(shows)

shows.pop() #removes the last item in the list
print(shows)

shows.pop(0)#removed the first item in the list
print(shows)

Tuples

  • Declaring a tuple and printing it
nl()

#Tuples - Does not change, ()
print("\nTuples--")

grades = ("A", "B", "C", "D", "F")
print(grades[1])

Looping

  • For loop
nl()

#Looping
print("\nLooping--")

#For loops - start to finish of an iterate
vegetables = ["cucumber", "spinach", "cabbage"]

for x in vegetables:
 print(x)
  • While loop
nl()

#While loops - Executes as long as true
i = 1

while i < 10:
 print(i)
 i += 1

Importing modules

  • Importing modules and using them in programs
import sys #system function & parameters
import os
import datetime
from datetime import datetime
from datetime import datetime as dt #import with alias



print(sys.version)

print(datetime.now())

print(dt.now())

#argv == $1 in bash. 
#sys.exit() #exits python cleanly

Advance strings

  • Retrieve certain letters/words from certain word/sentence
#Advance Strings
print("\Advance Strings--")
myName = "Neeranjan"

print(myName[4]) #Retrieve a certain letter from the word
print(myName[-1])

sentence = "This is a sentence."
print(sentence[:4]) #Retrieve a certain word from the sentence
  • Using the SPLIT and JOIN functions
print(sentence.split()) #splits the sentence based on a delimiter

splitSentence = sentence.split()
joinSentence = ' '.join(splitSentence) #Joins the sentence back together using the provided delimiter. (space in this case)
print(joinSentence)
  • Using quotes inside of a string variable
quote = "He said, 'give me all your money'" 
quote1 = "He said, \"give me all your money\""
#both of these methods will work the same
print(quote, quote1)
  • Stripping the extra space in a string
tooMuchSpace = "           hello               "
print(tooMuchSpace.strip())
  • Check for letter in word (case sensitive/non case sensitive)
#case sensitive
print("A" in "Apple") #True
print("a" in "Apple") #False

#non case sensitive
letter = "A"
word = "Apple"

print(letter.lower() in word.lower())
`
  • A better way to print text with variables in it
show = "Mr. Robot"
show2 = "Orange is the new black"
print("My favourite shows are {} and {}.".format(show, show2))

Dictionary

  • Declaring dictionary: assigning one value to a key (Key/Value Pairs)
#Dictionaries - key/value pairs
print("\Dictionary--")

drinks = {"Orange Juice": 7, "Apple Juice": 10, "Lemon Juice": 8} #Drink = key; Price = value

print(drinks)
  • Declaring dictionary: assigning multiple values to a key
employees = {"Finance": ["Krista", "Susan", "Joanna"], "IT": ["Elliot", "Tyrell", "Darlene"], "HR": ["Leon", "Mr. Robot", "Phillip"]}

print(employees)
  • Adding new key : value pair to an existing dictionary
employees["Legal"] = ["Trenton"] #Add new key:value pair
print(employees)

employees.update({"Sales": ["Anddy", "Ollie"]}) #Add new key:value pair
print(employees)
  • Updating an existing value in a dictionary
drinks["Orange Juice"] = 8
print(drinks)
  • Getting values from a dictionary
print(employees.get("IT"))