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

Python#03

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

Python Lists

    • Used to store collection of values in a single variable. 
    • Created using []
    • Items are ordered, changeable, and allow duplicate values.
    • Items are indexed, the first item has index [0], the second item has index [1] etc.
    • Has defined order, order can't be changed. 
    • New items will be appended to the list.
    • list is mutable, meaning that we can change, add, and remove items in a list after it has been created
    • lists are indexed, lists can have items with the same value: can be duplicated

EX7. List Operations [Creation]

# List operation

#creating a list

ilist = [1,2,3,4,5]

flist = [1.0,2.0,3.0,4.0,5.0]

slist = ['Tom', 'Jerry', 'Mickey']

#Finding length of lists
print('Length of lists created : ',len(ilist),len(flist),len(slist))

#print data types of list items
print('Data Types of lists created : ',type(ilist),type(flist),type(slist))


Result: Integer, float and string lists are created.

Length of lists created :  5 5 3
Data Types of lists created :  <class 'list'> <class 'list'> <class 'list'>

In the following example explains the important list operations are discussed with code and output. This example is self explanatory list functions, usage and output result are given below. These code you can practice and play with index numbers in this list.
# List operation

# Appending List
print('Before Appending ..........')
slist = ['Tom', 'Jerry', 'Mickey']
print(slist)
slist.append('Dick')
slist.append('Harry')
print('After Appending ..........')
print(slist)
#Print ['Tom', 'Jerry', 'Mickey', 'Dick', 'Harry']


print('Before Inserting ...the index.......')
slist = ['Tom', 'Jerry', 'Mickey']
print(slist)
slist.insert(0,'Dick')
print(slist)
slist.insert(2,'Harry')
print('After Inserting ..........')
print(slist)
#Prints ['Dick', 'Tom', 'Harry', 'Jerry', 'Mickey']


print('Before Popping ..........')
slist = ['Tom', 'Jerry', 'Mickey']
print(slist)
slist.pop()
print('After Popping . removing one element at the end.....')
print(slist)
#Prints ['Tom', 'Jerry']


print('Before Slicing ....slice(start:end:increment)......')
slist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(slist[2:7])
# Prints ['c', 'd', 'e', 'f', 'g']


print("With Negative indexing")
slist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(slist[:-2])
#print ['a', 'b', 'c', 'd', 'e', 'f', 'g']

print("With Negative indexing")
slist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
print(slist[::-1])
#print ['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] .. Reverse the list

print("With Specifying step")
slist = [0,1,2,3,4,5,6,7,8,9,10]
print(slist[2:8:2])
#print [2, 4, 6]


print("before ...modifying List Values")
alist = [0,1,2,3,4,5,6,7,8,9,10]
print(alist)
slist[2:4] = ['a','b', 'c']
print("After ..modifying List Values list[start:end] = [values]")
print(alist)
#print [0, 1, 'a', 'b', 'c', 4, 5, 6, 7, 8, 9, 10]

print("Before ...Deleting List Values")
alist = [0,1,2,3,4,5,6,7,8,9,10]
print(alist)
alist[2:4] = []
print("After ..Deleting index 2,3,4 values]")
print(alist)
#print [0, 1, 4, 5, 6, 7, 8, 9, 10]

# Copying lists
print('Copying Lists')
alist = ['a', 'b', 'c', 'd', 'e']
blist = alist[:]
print(alist, blist)
# Prints ['a', 'b', 'c', 'd', 'e'] ['a', 'b', 'c', 'd', 'e']
print(blist is alist)
# Prints False

print('Before sorting .......')
slist = ['Tom', 'Jerry', 'Mickey']
print(slist)
#prints ['Tom', 'Jerry', 'Mickey']
slist.sort()
print('After Sorting........')
print(slist)
#prints ['Jerry', 'Mickey', 'Tom']

Result:

Before Appending ..........
['Tom', 'Jerry', 'Mickey']
After Appending ..........
['Tom', 'Jerry', 'Mickey', 'Dick', 'Harry']
Before Inserting ...the index.......
['Tom', 'Jerry', 'Mickey']
['Dick', 'Tom', 'Jerry', 'Mickey']
After Inserting ..........
['Dick', 'Tom', 'Harry', 'Jerry', 'Mickey']
Before Popping ..........
['Tom', 'Jerry', 'Mickey']
After Popping . removing one element at the end.....
['Tom', 'Jerry']
Before Slicing ....slice(start:end:increment)......
['c', 'd', 'e', 'f', 'g']
With Negative indexing
['a', 'b', 'c', 'd', 'e', 'f', 'g']
With Negative indexing
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
With Specifying step
[2, 4, 6]
before ...modifying List Values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After ..modifying List Values list[start:end] = [values]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Before ...Deleting List Values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After ..Deleting index 2,3,4 values]
[0, 1, 4, 5, 6, 7, 8, 9, 10]
Copying Lists
['a', 'b', 'c', 'd', 'e'] ['a', 'b', 'c', 'd', 'e']
False
Before sorting .......
['Tom', 'Jerry', 'Mickey']
After Sorting........

['Tom', 'Jerry', 'Mickey']
After Appending ..........
['Tom', 'Jerry', 'Mickey', 'Dick', 'Harry']
Before Inserting ...the index.......
['Tom', 'Jerry', 'Mickey']
['Dick', 'Tom', 'Jerry', 'Mickey']
After Inserting ..........
['Dick', 'Tom', 'Harry', 'Jerry', 'Mickey']
Before Popping ..........
['Tom', 'Jerry', 'Mickey']
After Popping . removing one element at the end.....
['Tom', 'Jerry']
Before Slicing ....slice(start:end:increment)......
['c', 'd', 'e', 'f', 'g']
With Negative indexing
['a', 'b', 'c', 'd', 'e', 'f', 'g']
With Negative indexing
['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
With Specifying step
[2, 4, 6]
before ...modifying List Values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After ..modifying List Values list[start:end] = [values]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Before ...Deleting List Values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After ..Deleting index 2,3,4 values]
[0, 1, 4, 5, 6, 7, 8, 9, 10]
Copying Lists
['a', 'b', 'c', 'd', 'e'] ['a', 'b', 'c', 'd', 'e']
False
Before sorting .......
['Tom', 'Jerry', 'Mickey']
After Sorting........
["Jerry;, 'MIckey','Tom']

Results are given and self explanatory with comments

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...