Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Tuesday 8 March 2022

Python#07

Class in Python

A Class in Python is a logical grouping of data and functions. It gives the freedom to create data structures that contains arbitrary content and hence easily accessible.

Class” is a logical grouping of functions and data. Python class provides all the standard features of Object Oriented Programming.

Class inheritance mechanism :  A derived class that override any method of its base class. A method can call the method of a base class with the same name. Python Classes are defined by keyword “class” itself. Inside classes, you can define functions or methods that are part of the class

Everything in a class is indented, just like the code in the function, loop, if statement, etc.

The self argument in Python refers to the object itself. Self is the name preferred by convention by Pythons to indicate the first parameter of instance methods in Python

Python runtime will pass “self” value automatically when you call an instance method on in instance, whether you provide it deliberately or not

In Python, a class can inherit attributes and behavior methods from another class called subclass

class ametClass():
def aMethod(self):
print("Men Money Machine & Matters")

def bMethod(self, param):
print("Hey I am testing class method :" + param)

def main():
c = ametClass()
c.aMethod()
c.bMethod('I am param porul')

main()

Result:

Men Money Machine & Matters

Hey I am testing class method :I am param porul

####inheritance

class aClass():

def aMethod(self):
print('A ha : Base class method 1')

def bMethod(self, str):
print('oh oh Base class method 2 '+str)

class childClass(aClass):

def cMethod(self):
aClass.aMethod(self) # Note instance of base class method
print('A ha : Child class Method1.....')

def dMethod(self, str):
print('Oh Oh Child class method 2'+str)

def main():

c1 = aClass()
c1.aMethod() # Note child inherited from aClass
c1.bMethod('Base class ..nna') # Note child inherited from aClass

c2 = childClass()
c2.aMethod()
c2.bMethod('Besh besh Child Class Method1')
c2.cMethod()
c2.dMethod('Nanna Irukku Child Class Method 2')

main()

Result

A ha : Base class method 1

oh oh Base class method 2 Base class ..nna

A ha : Base class method 1

oh oh Base class method 2 Besh besh  Child Class Method1

A ha : Base class method 1

A ha : Child class Method1.....

Oh Oh Child class method 2Nanna Irukku Child Class Method 2

Using Constructors
# Constructors : Defining and initalizing  values

class Cadet:

name = " " # Class Variables
def __init__(self, name):
self.name = name

def printWelcome(self):
print('Welcome to Kalvi Koil, AMET '+ self.name)

Cadet1 = Cadet('Anbu')

Cadet1.printWelcome()

Result :

Welcome to Kalvi Koil, AMET  Anbu

The above sample codes explain the how to define a class, define class method, inherit a class, overloading a method, initialize the class using constructor.

Happy Learning by simple super code!

Python#06

 Python Yield

yield is not like return. When return is used it is given to caller. When yield is used you can iterate, pass or suspend. Le us see with example. Ready guys! Start.. Here you go..

Here is the situation when you should use Yield instead of Return

Use yield instead of return when the data size is large

Yield is the best choice when you need your execution to be faster on large data sets.

Use yield when you want to return a big set of values to the calling function. 

Yield is an efficient way of producing data that is big or infinite.
yield wont take memory. 

Execution is faster The yield keyword in python works like a return with the only difference is that instead of returning a value, it gives back a generator function to the caller. 

A generator is a special type of iterator that, once used, will not be available again. 

The values are not stored in memory and are only available when called.

The values from the generator can be read using for-in, list() and next() method.

The main difference between yield and return is that yield returns back a generator function to the caller and return gives a single value to the caller.

Yield does not store any of the values in memory, and the advantage is that it is helpful when the data size is big, as none of the values are stored in memory.

The performance is better if the yield keyword is used in comparison to return for large data size.

# Yield is just like return but with generator(?) objects instead of values
Generators are special functions that have to be iterated to get the values
# To get the values the
# To get the values the objects has to be iterated
#Syntax yield expression
# #Sample yield function
# def demoyield():
# yield "Welcom to AMET - Pioneer in Maritime Education"
#
# out = demoyield()
# print(out)
# #<generator object demoyield at 0x000002802AC5DA50>
# # iterate to get the value in the above object
# #Generators are functions that return an iterable generator object. The values from the generator object are fetched one at a time instead of the full list together and hence to get the actual values you can use a for-loop, using next() or list() method
# for i in out:
#.      print(i)
# Example 2
# def gen():
#       yield 'G'
#.      yield 'A'
#       yield 'N'
#       yield 'D'
#       yield 'H'
#       yield 'I'
#       yield ' '
#       yield 'M'
#       yield 'A'
#       yield 'H'
#       yield 'A'
#       yield 'N'
#
# demo = gen()
#
# for i in demo:
#.      print(i)
#
#example 3 difference between normal function and generator function
#Normal
def normalfun():
     return 'Hello Zoox Robo Taxi to Universe - normal function'
def genfun():
       yield "'Hello Zoox Robo Taxi to Universe - generator function"

print(normalfun())
print(genfun())
# Hello Zoox Robo Taxi to Universe - normal function
#until it prints the whole string normalfun()wont stop
# <generator object genfun at 0x00000298E53AD900>
#but gen iterates so we can use the generator obhject to get the values and also , 'pause' and 'resume'
print(next(genfun()))
#Note next function
print(list(genfun()))

Python#05

 File Operations in Python

How to open a file, read, print, write, append the contents.?  All shown with the following example code and output

 # Simple Excel file read


import pandas as pd

csv_file = pd.read_csv('csv.csv')

print(csv_file)


# # printed the following
# h1 h2 h3 h4
# 0 1 2 3 4
# 1 5 6 7 8
# 2 9 10 11 12
# 3 13 14 15 16
# ##################
#Excel file sheet1 reading specific

excel_file = pd.read_excel('sample.xlsx', sheet_name='Sheet1')

print(excel_file)

# Print out
# Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4
# read multiple sheets

df_sheet_multi = pd.read_excel('sample.xlsx', sheet_name=['Sheet1', 'Sheet2'])

print(df_sheet_multi)

#Printout
# {'Sheet1': Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4, 'Sheet2': Unnamed: 0 slno name age sal
# 0 1 11 11 11 11
# 1 2 22 33 44 55
# 2 3 66 66 66 66
# 3 4 77 77 77 77}

print(25*'-','Sheet1')

print(df_sheet_multi['Sheet1'])


# ------------------------- Sheet1
# Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4

print(25*'-','Sheet2')

print(df_sheet_multi['Sheet2'])


# ------------------------- Sheet2
# Unnamed: 0 slno name age sal
# 0 1 11 11 11 11
# 1 2 22 33 44 55
# 2 3 66 66 66 66
# 3 4 77 77 77 77

# To Create and write contents

f = open("demo.txt", "w")

f.write("I have written the contents!")

f.close()



#open and read the file after the appending:
f = open("demo.txt", "r")

print(f.read())

#prints => I have written the contents!
f.close()


f = open("demo.txt", "a")

f.write("Now I have written the contents more again !")

f.close()

#In demo.txt => I have written the contents!Now I have written the contents more again !

import os.path

file_exists = os.path.exists('readme.txt')

print(file_exists)

#False

import os.path

file_exists = os.path.exists('demo.txt')

print(file_exists)

#True

f = open("demo1.txt", "w")

f.write("I have written the contents!")

f.close()


f = open("demo2.txt", "w")

f.write(str(list(csv_file)))


f = open("demo2.txt","r")

print(f.read())

#f.close()

print(f.read())

#Print ['h1', 'h2', 'h3', 'h4']


Hope The above simple code snippets and printouts shown as comments is clear and understandable. Happy Open and Distance Learning!

Thursday 24 February 2022

List & Lambda

Let us Review Python a bit and look at List & Lambda Function!

Python is the easiest popular programming language. Anything and everything you can do with python! Everyone knows about Google. Google uses Python extensively.

We learn some fundamentals by examples.

Ex.1 Print

Code

result

print("Hello, Friends!")

Hello, Friends!

Types and functions

Python automatically recognizes the types of data. Here are a few examples:

Number – Integer, Float, Complex: 3, 3.0, ‘3+j’
Character Strings: ‘ODL’, ‘AMET’
List of Objects: [10, 20, 30, 40], [‘Male’, ‘Female’]
In addition, Python has special datum meaning nothing: None

Python is rich in libraries, built-in-function. Now let us learn about variables

Ex.2 Add two constants

Code

Result

print(5+5)

10

Ex. 3 Add variables

Code

Result

X,Y = 5,5

 

print(X+Y)

10

X,Y = 5,’FIVE’

print(X+Y)

SyntaxError: invalid character '’' (U+2019)

 Note multiple assignments in a single statement

Ex. 4 Add string variables

Code

Result

X,Y = ‘5’,’5’

 

print(X+Y)

55

X,Y = ‘AMET’,’UNIVERSITY’

 

print(X+Y)

AMET University

Let us print some useful Multiplication Table

Ex 5. For loop with range -

Multiplication Table for 5: Here we use for loop with simple syntax as shown:

Code

Result

 

 

 

for x in range(1,11):

     print(x*5)

5
10
15
20
25
30
35
40
45
50

for x in range(1,11,2):

    print(x*5)

 

#Note range function (start,stop,step)

 

1
3
5
7
9 

for x in range(1,10):

 txt = '{} * {} = {}'    

 print(txt.format(x,5,x*5))

 

#note simple formatting

1 * 5 = 05
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45

 

 

For repetitive steps, we used for loop. See the syntax range. Note range (start, stop, step)

The start is inclusive and the stop is excluded with the increment step.

 Ex 6. For Loop iteration

code

result

 

for x in "AMET":

    

 print(x)

A
M
E
T

for x in ['marine’, ‘nautical science']:

    

 print(x)

marine
nautical science
 

Let us check how PVM (Python Virtual Machine) handles internally through some simulator

 

Click This Link Python Tutor - Visualize Python and paste the above code in the space given and see the steps forward.

 

 

 Ex 7. Introspection to Python variable types
#Ex 7 basic and collection variables
var_i = 5
var_f = 5.0
var_str = "AMET"
print(type(var_i))
print(type(var_f))
print(type(var_str))
print(25*'-','Collection Variables')



# Numeric collection variables
var_list = [1,2,3]
var_tuple = ("one", "two", "three")
var_set = {1,2,3}
var_dict = {"1":"one", "2": "Two", "3":"Three"}
print(type(var_list))
print(type(var_tuple))
print(type(var_set))
print(type(var_dict))

#
Result: 

<class 'int'>
<class 'float'>
<class 'str'>
------------------------- Collection Variables
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>

Happy Learning Lambda🎨😊





Sunday 20 February 2022

Python#02

EX 4: Using IF 

Now imagine you are asked to find right alliance 👫 by your parents just like in TV Programme KALYANAMALAI. Choose a bride/bridegroom based the traits like qualification and salary. You want to choose one who is earning around 1 lac and  better qualification. How python will simulate this situation and decide, let us code.

Now let us formulate the problem with variables qual and salary with values qual = UG, PG, Ph.D. (Rank 1,2,3 respectively), salary = 20k,40k,50k, 100k, 150k, 200k respectively
we have to pick the right bride/bridegroom.

#qual = [0,1,2] # 0 -ug, pg = 1, Ph.D = 3

#salary = (20,30,40,50,75,100,120) #

qual = input("Enter candidates qualification 0 -UG, 1- PG, 2 - Ph.D :\n ")

sal = input("Salary of the candidate :\n")

# Check select better qualified Ph.D, and salary with 100|120k

if int(qual) >= 2:
if int(sal) >= 100:
print("Candidate is chosen for marriage alliance")
else:
print("Candidate is not chosen since salary is not sufficient")
else:
print("Candidate is not chosen since Not having enough qualification")

 Run :


Enter candidates qualification 0 -UG, 1- PG, 2 - Ph.D :
1
Salary of the candidate :
120
Candidate is not chosen since Not having enough qualification

Process finished with exit code 0
In the previous scenario, if we have list  of bride/bridegrooms to be checked for alliance, how to run through the list and identify, let us deep dive in python coding.

EX 5: Using IF..Else..

qual = (0, 1, 2)  # 0 -ug, pg = 1, Ph.D = 3

salary = (20, 30, 40, 50, 75, 100, 120) # 20 - 20k

# c = qual, salary
candidates = [[2, 200], [1, 120], [2, 80], [2, 120], [1, 80]]

for r in candidates:

if r[0] >= 2:

if r[1] >= 100:

print("Candidate qual = %2d salary = %6.2f is chosen for alliance" % (r[0], r[1]))

else:
print("Candidate qual = %2d salary = %6.2f is not chosen for alliance" % (r[0], r[1]))

else:
print("Candidate qual = %2d salary = %6.2f is not chosen for alliance" % (r[0], r[1]))

Result:

Candidate qual =  2  salary = 200.00 is chosen for alliance
Candidate qual = 1 salary = 120.00 is not chosen for alliance
Candidate qual = 2 salary = 80.00 is not chosen for alliance
Candidate qual = 2 salary = 120.00 is chosen for alliance
Candidate qual = 1 salary = 80.00 is not chosen for alliance
Visualize this by   https://tinyurl.com/3kduyfsc.

Now We know how to use Python. easily Now we will see the python basics.

Python has a format. It has very important property indentation to indicate a block of code. Indentation  is blank spaces in the beginning of the code.

def functionname():
statement 1

stament N

if you make mistake in indentation, you will get IndentationError: unexpected indent

Python has also constants, variables and some data structures like list, tuple, set, dictionary and also supports comprehension with lambda function. Here are some examples:

Python constants
print(5)            #   5      : int Constant

print (5.5) # 5.5 : float constant

print ('55') # '55' : string constant

Result:


5

5.5

55

Python variables

Variables do not need to be declared with any particular type, automatically they have been assigned according to the value you typed.

You can change type after they have been set.


i = 5 # integer variable i
print(i,type(i))


f = 5.5 # float variable f
print (f,type(f))

s = 'hello' # string variable s
print (s,type(s))

print(int(f),type(int(f))) # casting float to integer

print(str(i),type(str(i))) # casting integer to string


Result:

5 <class 'int'>
5.5 <class 'float'>
hello <class 'str'>
5 <class 'int'>
5 <class 'str'>

String variable can be declared using single quote or double quotes.

Variable Names

A variable can have a short name (like i, f  and s) or a more descriptive name (age, fname, first_name, lname, last_name,  city, ). 

Rules for Python variable names:

  • must start with a letter or the underscore character
  • cannot start with a number
  • can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • case-sensitive (age, Age and AGE are three different variables)

Examples:

tom = "Mickey", t_o_m = "Mickey",  _tom = "Mickey", tOm = "Mickey",TOM = "Mickey", tom1= "Mickey"

Many variables can be assigned values  in a single statement


i, f, s = 5, 5.5, 'Hello'

print(type(i), type(f),type(s))

Result:


<class 'int'> <class 'float'> <class 'str'>

Many values take single value.


x
, y, z = 'Apple', 'Bananas', 'Orange'
print(x, y, z)
print()

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

Result:

Apple Bananas Orange

Orange
Banana
Cherry

In python, we can assign the same value to many variables like this

x =  y = z = "Tom&Jerry"
print(x)
print(y)
print(z)

Result:


Tom&Jerry
Tom&Jerry
Tom&Jerry

Python supports same variable name for collection of values like list, tuple, set,  dictionary.

 NEXT


Python#01

Let us play with Python (Beginner)

Any Language is for communication between parties. Here we will go through python abilities.

What is Python?

Python is a general-purpose computer programming language.

Python is a dynamic, interpreted and object-oriented language.

Python has a rich set of APIs and wide range of libraries

Python is easy to learn and use and most suitable for data analysis


Where is Python used?

It is used in almost every technical field. The various areas of Python use are given below.

  • Data Science and data Analysis
  • Date Mining and text mining
  • Desktop Applications
  • Mobile Applications
  • Web Applications
  • Enterprise Applications
  • Machine Learning for prediction
  • Computer Vision or Image Processing Applications.
  • Speech Recognition.

Should know how to input and output for any language (Even for Computer).

Processing can be dealt with later. we will learn by exercises.

Ex 1: User Input Strings

Imagine  the scene:
When you meet a new person, normally say hello, What is your name?
He replies with "My name is Tom, What is your name ?"
You replied with "Nice name, my name is Jerry".
We will mimic this with the python  program:
Install PyCharm IDE
Create project
Give name as PYTHON
main.py is normally created with default code.
Delete the contents in main.py
Type in the below code and run
fname = input("hello, What is your name?")
name = input(f"My name is {fname}, What is your name ?")
print(f"Nice name, My name is {lname}")
Result:
hello, What is your name?Tom
My name is Tom, What is your name? Jerry
Nice name, My name is Jerry

Process finished with exit code 0

So input is reading input values. Here values Tom & Jerry, We handled strings. Next, we will handle numbers. Suppose we wrongly entered numbers instead of strings. How to track the type of value entered.

Smart python has a function for this.

# input numbers type conversion

fname = input(" Type Any value?")

print(type(fname))

fname = int(fname)

print(type(fname))

Result:

Type Any value?5
<class 'str'>
<class 'int'>

Ex 2: Handling numbers 

Now let us imagine another scene. Your son is asking for Multiplication Table 17.

Let us assume the table has to be printed like this below

1 x 17 = 17

2 x 17 = 34.

.

9 x 17 = 153.

.10 x 17 = 170 

Here we see how python does this with numbers ie. integer values

# Multiplication table (from 1 to 10) in Python

num = input("Which table You want, my dear son?")

#convert string to int
num = int(num)

# Iterate 10 times from i = 1 to 10
for i in range(1, 11):
print(num, 'x', i, '=', num*i)

Result :

Which table You want, my dear son?17
17 x 1 = 17
17 x 2 = 34
17 x 3 = 51
17 x 4 = 68
17 x 5 = 85
17 x 6 = 102
17 x 7 = 119
17 x 8 = 136
17 x 9 = 153
17 x 10 = 170

In this example please see the for loop and arithmetic operator *

Ex 3: Print simple interest I with P, N,R given

Suppose you want to put money in the bank as FD. Want to know how much interest will come. To print simple interest (I)  for the given Principal (P), Number of years (N), and rate of interest(R), let us code simply in python.

# Finding Simple Interest

p = int(input("enter Principal amount P :"))

n = int(input("For how many years N :"))

r = int(input("enter Rate of Interest % :"))

# calculate
for i in range(1, n + 1):
interest = (p * i * r) / 100
print('Interest = {3:.2f} for Principal = {0}, for year = {1} with rate = {2}'.format(p, i, r, interest))
Result : 

Enter Principal amount P :1000000
For how many years N :12
enter Rate of Interest % :12
Interest = 120000.00 for Principal = 1000000, for year = 1 with rate = 12
Interest = 240000.00 for Principal = 1000000, for year = 2 with rate = 12
Interest = 360000.00 for Principal = 1000000, for year = 3 with rate = 12
Interest = 480000.00 for Principal = 1000000, for year = 4 with rate = 12
Interest = 600000.00 for Principal = 1000000, for year = 5 with rate = 12
Interest = 720000.00 for Principal = 1000000, for year = 6 with rate = 12
Interest = 840000.00 for Principal = 1000000, for year = 7 with rate = 12
Interest = 960000.00 for Principal = 1000000, for year = 8 with rate = 12
Interest = 1080000.00 for Principal = 1000000, for year = 9 with rate = 12
Interest = 1200000.00 for Principal = 1000000, for year = 10 with rate = 12
Interest = 1320000.00 for Principal = 1000000, for year = 11 with rate = 12
Interest = 1440000.00 for Principal = 1000000, for year = 12 with rate = 12

Making Prompts for Profile Web Site

  Prompt: Can you create prompt to craft better draft in a given topic. Response: Sure! Could you please specify the topic for which you...