Sunday, 28 July 2019

Python Basics and Fundamentals


Basics and Fundamentals of Python


Python is more powerful language in modern days. Python is widely used in AI and machine learning.

Let’s download the python library https://www.python.org/downloads/  and IDE for python -https://www.jetbrains.com/pycharm/ download community edition of pycharm.


Now open pycharm and create a app.py file start with first code-
print("MK Study Journal")  # will print MK Study Journal in console


Beauty of python is we need no to create any explicit data variable, it automatically create the variable as assigned value. Refer below
print("MK Study Journal")  # will print MK Study Journal in console

variable1 = "MK Study Journal"
print(variable1) # will print 'MK Study Journal' in console

variable2 = True
print(variable2) # will print 'True' in console

variable3 = 123
print(variable3) # will print '123' in console


Take user input-
variable = input("Please enter True\False: ")
print(variable) # will print user input True\False


Conditional statement-
variable = input("Please enter number between 1 to 10: ")
if variable < 5:
   
print("Won")
elif variable < 10:
   
print("loss")
else:
   
print("Invalid input")


Multiple assignment-
a = b = c = 1
a,b,c = 1,2,"MK Study Journal"
print(a) # will print 1
print(b) # will print 2
print(c) # will print MK Study Journal


Python String:-
variable = "MK Study Journal"
print(variable[0]) # will print character at index 0 = M
print(variable[0:5]) # will print character form index 0 to 5 = MK St
print(variable[-1]) # will print last character = l
print(variable[:]) # will print compete string = MK Study Journal


Data Type conversion:-
variable = input("Please enter you birth year ") #variable is treated as String
age = 2019 - int(variable) # string to int conversion
print(age) # will print age if user input 1988 the age will be 31


Types of operator-
var1 = 10
var2 = 2
print(var1+var2) # addition 12
print(var1-var2) # substraction 8
print(var1*var2) # * Multiplication 20
print(var1/var2) # / Division 50
print(var1%var2) # % Modulus 0
print(var1**var2) # ** Exponent 100
print(var1//var2) # // floor division 5


Loop Control:-
# while loop
count = 0
while (count < 10):
  
print('The count is:', count)
   count = count +
1
  
# for loop
for char in 'MKStudyJournal':
  
print('Current Letter :', char)

# nested loop
var1 = 2
while(var1 < 100):
   var2 =
2
  
while(var2 <= (var1 / var2)):
      
if not(var1 % var2): break
     
var2 = var2 + 1
  
if (var2 > var1/var2) : print (var1, " is prime number")
   var1 = var1 +
1


Triple quotes-print multiline string-
# triple quote to print multi line string
variable = """ Hello Friends
Welcome in MK Study Journal"""
print(variable)


List operations-
list1 = ['M','T', 'W','T', 'F','S','S']
list2 = [
1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])      # list1[0]:  M
print ("list2[1:5]: ", list2[1:5])  # list2[1:5]:  [2, 3, 4, 5]

# updating value in list
list1[0] = 'Mon'
list2[1] = 'two'
print ("list1[0]: ", list1[0])      # list1[0]:  Mon
print ("list2[1]: ", list2[1])      # list2[1]:  two

print (len(list1[1]))  # length of list1 is 7
print (len(list2[1]))  # length of list2 is 7

# deleting value in list
del list1[0]
del list2[1]
print ("list1[0]: ", list1[0])      # list1[0]:  T
print ("list2[1]: ", list2[1])      # list2[1]:  3

# length of list after one element deletion
print (len(list1[1]))  # length of list1 is 6
print (len(list2[1]))  # length of list2 is 6

print (max(list1[1]))  # max element in list1 is T
print (min(list2[1]))  # min element in list1 is 1


Tuples – tuples is a sequence of immutable python objects.
tuple1 = (1, 2, 3, 4, 5 );
tuple2 =
"a", "b", "c", "d";
emptyTuple = ()
singleValueTuple = (
1,)
print(tuple1)           # print (1, 2, 3, 4, 5)
print(tuple2)           # print ('a', 'b', 'c', 'd')
print(emptyTuple)       # print ()
print(singleValueTuple) # print (1,)
print(tuple1[0])        # print 1
print(tuple1[-1])       # print 5
print(tuple1[1:4])      # print (2, 3, 4)
tuple3 = tuple1+tuple2  # updating tuple
print(tuple3)           # print (1, 2, 3, 4, 5, 'a', 'b', 'c', 'd')
del tuple3              # delete entire tuple
print(tuple3)           # NameError: name 'tuple3' is not defined
tuple3 = ('Hi!',) * 4
print(tuple3)           # print ('Hi!', 'Hi!', 'Hi!', 'Hi!')
print('Hi!' in tuple3)  # print true


Dictionary: - Dictionary is a key value pair separated by: and represent in curly braces.
Like –{key1:value1, key2:value2}
dictionary1 = {}    # empty dictionary
dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print ("dict['key1'] value: ", dict['key1'])    # dict['key1'] value:  value1
print ("dict['key2'] value: ", dict['key2'])    # dict['key2'] value:  value2

dict['key1'] = 1;                                # update existing entry
print ("dict['key1'] value: ", dict['key1'])     # dict['key1'] value:  1

del dict['key1'];                                # remove entry with key 'key1'
print ("dict['key1'] value: ", dict['key1'])    # KeyError: 'key1'
dict.clear();                                    # remove all entries in dict
print (dict)                                     # {}
del dict ;                                       # delete entire dictionary


Function block:-
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
A return statement with no arguments is the same as return None.
def checkPrime( num):
  
if num%2 != 0:
      
print("Prime number")
  
else:
      
print("Not a Prime number")

def factorial(num):
    fatorial =
1;
   
while num >= 1:
        fatorial = fatorial*num
        num = num-
1
   
print("factorial value is ",fatorial)

number =
int(input("Enter number : "))  # user input number

factorial(number)
checkPrime(number)


Handling with files
import os

fileObject =
open("mkstudyjournal.txt", "w+")   # open file in wb-Opens a file in writing and reading
print("Name of the file: ", fileObject.name)    # Name of the file:  mkstudyjournal.txt
fileObject.write( "second-MK Study Journal")    # write into file
fileObject.write( "third-MK Study Journal")     # write into file
print(fileObject.seek(0,0))                     # reset reader pointer position 0
print("", fileObject.read(45))                  # read file
print(fileObject.tell())                        # Current file position 45
fileObject.close()

os.rename(
"mkstudyjournal.txt", "ren-mkstudyjournal.txt")
os.makedirs(
"/temp/text")                        # make directory
os.removedirs("/temp/text")                      # remove directory


Exception Handling-
try:
    fileObject =
open("test1", "w")
    fileObject.write(
"Exception handling!!")
except IOError:
   
print("Error: can\'t find file or read data")
else:
   
print("success")
    fileObject.close()

try:
    var1 =
int(input("Enter number: "))
    var =
10/var1
except ValueError:          # if input value is not numeric
   
print("Error: can not convert to int, Invalid number")
except ZeroDivisionError:   # if input value is 0
   
print("Error: can\'t divide by zero")
else:
   
print("success")

User defined error-
class CustomkError(RuntimeError):
   def __init__(self, arg):
      self.args = arg

try:
   raise CustomkError("user defined error")
except CustomkError:
    print("Error: custom error")


Object oriented
class Student:

    fullName = "test"

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        Student.fullName = firstName+" "+lastName

    def fullName(self):
        print("Student name: ", Student.fullName)

    def displayStudent(self):
        print("FirstName : ", self.firstName, ", LastName: ", self.lastName)

student = Student("Manoj", "Kumar")
student.displayStudent()
 
# inheritance property implementation
class Person:

    fullName = "test"

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        Student.fullName = firstName + " " + lastName

    def displayPerson(self):
        print("Hello parent", Student.fullName)

    def displayWelcome(self):
        print("Welcome")

class Student(Person):

    def __init__(self, firstName, lastName):
        self.firstName = firstName
        self.lastName = lastName
        Student.fullName = firstName+" "+lastName

    def displayPerson(self):
        print("Hello child", Student.fullName)


student = Student("ChildFN", "ChildLN")
student.displayWelcome()    # call parent method print Welcome

# method overriding
student.displayPerson()     # call child method print Hello child ChildFN ChildLN

person = Person("ParentFN", "ParentLN")
person.displayPerson()      # parent method print -Hello parent ParentFN ParentLN


CGI Programming in Python-
Create httpd.cfg with below content –
<Directory "/cgi-bin">  
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>

<Directory "/cgi-bin">
Options All
</Directory>
Create python file in directory /cgi-bin CGI.py
import cgitb

cgitb.enable()

print("Content-Type: text/html\n")
print("<!doctype html>")
print("<h2>Welcome in MK Study Journal</h2>")
print("<h2>Thank you !!</h2>")
Run below command in terminal-
python -m http.server --bind localhost --cgi 8080
Open browser-
terminal command will be as follows-


Navigation between CGI-
Create below textareasubmit.py file-
import cgitb

cgitb.enable()

print("Content-Type: text/html\n")
print("<!doctype html>")
print("<body>")
print('<form action = "/cgi-bin/textarea.py" method = "post"')
print('<textarea name = "textArea" cols = "40" rows = "4">')
print("</textarea>")
print('<input type = "submit" value = "Submit" />')
print("</form>")
print("</body>")
Create below textareareader.py file
import cgi, cgitb

form = cgi.FieldStorage()

if form.getvalue('textArea'):
   text_area = form.getvalue('textArea')

else:
   text_area = "Not entered"

print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<body>")
print("<h2> Entered Text is %s</h2>" % text_area)
print("</body>")
Now open below url –
http://localhost:8080/cgi-bin/textareareader.py and enter the text in text area and submit, this will navigate to http://localhost:8080/cgi-bin/textarea.py


Multithreading in Python-
import threading
import time

class PrintNumbers(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):

        for i in range(10):
            time.sleep(1)       #sleep for 1 seconds
            print(i)            # will print 0 to 9
            print(threading.current_thread()) # threadName <PrintNumbers(Thread-1, started 19464)>

thread1 = threading.Event()

t1 = PrintNumbers()
t1.start()

import threading

class PrintNumbers(threading.Thread):

    def __init__(self, startIndex, lastIndex, step, set_event, clear_event):
        threading.Thread.__init__(self)
        self.startIndex = startIndex
        self.lastIndex = lastIndex
        self.step = step
        self.set_event = set_event
        self.clear_event = clear_event


    def run(self):
        for i in range(self.startIndex, self.lastIndex, self.step):
            print(i)
            self.set_event.set()
            self.clear_event.clear()
            self.clear_event.wait()
        self.set_event.set()


thread1 = threading.Event()
thread2 = threading.Event()

t1 = PrintNumbers(0, 10, 2, thread1, thread2)
t2 = PrintNumbers(1, 10, 2, thread2, thread1)

t1.start()
t2.start()

t1.join()
t2.join()

 


1 comment: