Python Script Basics

Python program executing ways

2 type of methods are available: - If we write #!/bin/python3
  1. run like : - python3 first.py : - it means it will take "  #!/bin/python3  " # as a comment
  2. run like: - ./first.py : - it means it will take "   #!/bin/python3 " as a path and will load pytho3 from /bin/python3 ( where python is stored)
-----------------------------------------------------------

Stirngs

just like sentences.
    print("hello world!")
    print('hello world!')
    print("hello 'world'!")

concatenation:-
    print("this string is "+"awesome")

------------------------------------------------------------

Math
  1. Built in math interpreter in python.
  2. print(50+50)
  3. print(15-3)
  4. print(50*50)
  5. print(4/2)
  6. print(5-3/4*2) ( resolves according to BODMAS maths rule)
  7. print( 50 ** 50) exponents
  8. print(5%2)
  9. print(50//6) no fraction point
-------------------------------------------------------------

Variables and Methods

  1. variables are placeholders.
    1. a = 1
      1. print(a)
        1. it will print 1
    2. a = "hello"
      1. print(a)
        1. it will print hello
  2. methods are functions available.
    1. a = "hello"
    2. print(a.upper())
      1. it will make hello in uppercase. HELLO
    3. print(a.lower())
      1. it will make hello in lowercase. hello
    4. print(a.title())
      1. it will make hello in title case. Hello
    5. print(len(a))
      1. length of the a variable's data. 5.
  3. a program
                 name = heath # string
                 age = 30 # integer
                 gpa = 6.4 # float

      #type casting
                print(int(gpa))
                this will print 6 only

------------------------------------------------------------

Functions

  1.  A mini program - which we can use multiple times.
  2. syntax: -

            def function_name():     # function definition and body
                name = "nep"
                age = 30
                print(name)
                print(age)
   
            function_name()     # function call

  •  add function : -
                def add_one(num):     # function definition and body
                print(num+100)
                
                
                add_num(100)   # function call ( entering input in comment , which will make the output = 200 ( num = 100 ( num+100)))


  • add function with multiple parameter.
            
            def add_function(x,y):     # function definition and call
                print(x+y)


            add(9,4)           #function call with input as 9 and 4 which will make output 13.
            

---------------------------------------------------------------

Boolean Expressions

  • Boolean expressions
                bool1 = True
                bool2 = 3*3 == 9
                bool3 = False
                bool4 = 3*3 != 9
            
                print(bool1,bool2,bool3,bool4)
                print(type(bool1))

--------------------------------------------------------------

Conditional Statements

  • In conditional statements, there will be a condition on that basis we need to take discussions 
    • if else
    • if elif else

        Below mentioned program has a situation which shows that if you have greater than 2 dollars then you can buy the drink else no drink:-
  • if else condition: -

                def drink(money):
                    if(money >=2):
                        return("you have got the drink")
                    else:
                        return("No drink for you")
                print(drink(3))
                print(drink(1))

  • if elif else : - below mentioned script is for alcohol buying with two decisions (1. age and 2. money)

            def alcohol(age,money)
                if(age >= 21) and (money >= 5):
                    return("enjoy your drink")
                elif (age >= 21) and (money < 5):
                    return("NO drink for you")
                elif(age < 21) and (money >= 5):
                    return("nice try kid, but you are under age")
                else:
                    return("Sorry NO drink for you")


            print(alcohol(21,5))
            print(alcohol(21,4))
            print(alcohol(16,3))

-----------------------------------------------------------------

Relational and Boolean Operators

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

            test_and = (7 > 5) and (5 < 7)         #true
            test_and2 = ( 7 > 9) and ( 5 < 7)     #false
            test_or = ( 7 > 9) or ( 5 < 7)             #true
            test_and2 = ( 7 > 5) and ( 5 > 7)     #true
            
            test_not = not True     #False
            test_not = not False     #True

-----------------------------------------------------------------

Looping

  • For loop  - start to finish of an iterate. 
    • For loop is used to print all elements of the list 

            #list is: -
                    fruits = ["apples", "kiwi", "oranges", "pears", "lemon", "banana"]

                    for x in fruits:
                        print(x)


  • While loop  - Executes as long as true
                i =1
                
                while i < 10:
                    print(i)
                    i+=1

            above while loop executes till i < 10, once i = 10 loop will finish.

-----------------------------------------------------------------

Importing Modules

Importing : - modules are existing in python. these modules are not builtin but available to use.
    example: - sys.
            print(sys.version)
            
  • in the pythonfile.py file
    • import sys       # sys is a system function which we are importing.


  • importing ways.
    • from datetime  - whole datetime module
    • from datetime import datetime - specific
    • from datetime import datetime as dt          # import as an aliases. we can use dt for using datetime now.
      • print(dt.now())
-----------------------------------------------------------------

Advance String

names = "neptune"
print(names[0])
print(names[-1])


line123 = "I am drinking coffee"
print(line123[:4])     # means it will print only I am

print(line123.split( ))      # it will split on the basis of space and save into a list. like: -  ["I" , "am", "drinking", "coffee"]


line123_split = line123.split()
line123_join = " ". join (line123)         # on the with above aplit now everything got split, this statement shows how to join that splitted sentense into one string on the basis of space.
print(line123_join)



quote_ex = "he said, "we are going for a swim""
print(quote_ex)
    above quote_ex will give the errors

quote_ex = "he said, 'we are going for a swim'"
print(quote_ex)
    above quote_ex will print it nicely.

quote_ex = "he said, \"we are going for a swim\""
print(quote_ex) 
   above quote_ex will print it with double quotes where ever these are used. because \ (backslash) will give an idea to interpreter that from first \ (bakslash) till next, treat as a string.



another_space = "                               home"   # unnecessary spaces in the string
print(another_space.strip())   


print( "A"   in "Apple")      # this will return True , because it is trying to find A in the Apple string.
print("a" in "Apple")         # this will because False, because a ( lowercase a) is not in string Apple.

letter = "A"
word = "Apple"
print(letter.lower() in word.lower())           # this will first convert the letter A to lower case the word "Apple" to lowercase and provide result as True.



movie = "The Hulk"
print("My favorite movie is {}.".format(movie))    # {} is a placeholder, where we are going to enter the movie name with format function.


-----------------------------------------------------------------

Data Structures ( Lists, Tuples, Dictionaries )



S.NoData TypesSyntaxExampleDescriptionNature
1List
have brackets []
list_name = [element1, element2, element3, element4, and so on]
movies = [Inception, Avengers, Intersteller, Dun Kirk, 1920, Pikachu, The Joker]
print(movies[1] (this will print Avengers movie, because the index starts from 0 , 1, 2, 3 and so on. SO for the Joker movie the index will be 6. 
this will be printed as =  print(movies[6])

Also : -
print(movies[1:3] = Avengers, Intesteller ( never going to print 3 index, it will stop before three if you have mentioned 1:3)
print(movies[1:] = all elements
print(movies[:1] =  Only element which is present on index 0.
print(movies[-1]) = grab the last element of the list
print(len(movies)) - how many number of elements available.
movies.append = "Home Alone"  = appended in the list
movies.pop() = automatically deletes last element of the list
movies.pop(0) = delete elements with the help of index.
Mutable (can be appended, can insert other element, can iterate.)
2Tuples
have brackets ()
tuple_name = ("element1", "element2", "element3", "element4", "element5", "and so on..")
grade = ("a", "b", "c", "d", "e")
print(grades[1])
same as list but tuples are non mutable/fixed
Non-Mutable (cannot be appended, can not insert other element, can not iterate.)
3Dictionaries
Key:value pairs
dictionary_name={"key:value", "key:value", "key:value", "key:value, and so on..."}

Phone_quatity = {"iPhone: 9", "Andoird:10", "Blacberry: 3", "Windows: 7"}
employees = {"Finance":["bob", "tom", "joe", "teedy", "john", "rock"],  "IT" : ["matt", "harry", "tim", "tintin", "happy", "nick"], "HR": ["mark", "saw", "mick", "peter", "dom", "ethan","ricky"]}

A dictionary can easly hold multiple lists in it. In above example too we have mentioned lists in the place of value filed in each element of the dictionary.

To append the dictionary with other key:value pair = employees['legal'] = ["Mr. X"].

To append the dictionary with other key:value pair = employees.update({sales:["Andy", "Oliver"]})

To update the dictionary with other key:value pair, suppose you had a dictionary phone with element iphone:9 ( iphone is a key and 9 is a value) = phone['iPhone'] = 4 (this will update the value (quantity), from 9 to 4 )

Also if we want to check the value in particular key then = print(phone.get("iPhone"))  (it will show the value of iPhone key, which is 4 as per above scenario.)






Mutable (can be appended, can insert other element, can iterate.)


----------------------------------------------------------------------

Socket

127.0.0.1:7777   =  is a socket. 

Script is: -
    bin/python3     #shebang for python

    import socket      # importing socket module

    HOST = '127.0.0.1' # IP address where we want to have a connection
    PORT = 7777   # port number

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)       # s is a variable, creating a socket with IPv4 = socket.Af_INET, SOCK_STREAM is a Port
    s.connect((HOST,PORT))                                                           # to connect with mentioned host and port
 

---------------------------------------------------------------------
Port Scanner with Python

Script: - portscanner.py

import sys
import socket                                                        
from datetime import datetime

#Define our target
if len(sys.argv) == 2:
        target = socket.gethostbyname(sys.argv[1])    #sys.argv[1] is going to be the <ip address which we will enter. sys.argv[0] wil>
else:
        print("Invalid arguments")
        print("python port_scanner.py <ip>")

# Add a Banner
print("-" * 50)
print("Scanning target " + target)
print("Time started: " + str(datetime.now()))
print("-" * 50)

try:
        for port in range(20,1000):    # it will start scanninf from port 20 to 1000
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   # syntax to define socket with ipv4 with port
                socket.setdefaulttimeout(1)  # i will just wait for 1 second it port will not connect then it will move on.
                result = s.connect_ex((target,port)) #s.connect also can connect to ip:port but s.connect_ex provide error indicatior >
                if result == 0:   #above error or output indicatiors will be used here.
                        print("Port {} is Open".format(port))
                s.close()

except KeyboardIntrrupt:
        print("\nExiting program")
        sys.exit()

except socket.gaieror:
        print("Hostname could not be resolved")
        sys.exit()

except socket.error:
        print("Couldnot connect to server")
        sys.exit()




---------------------------------------------------------------------------------------------------------------------------------------------------

Comments