Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python core/DAY 2.ipynb
3074 views
Kernel: Python 3
#Program to seggreggate even and odd from a list n=int(input("Enter the no of values in the list")) i=0 li=[] while(i < n): e=int(input("Enter no on %d\n"%i)) li.insert(i,e) i=i+1 print (li) i=0 lieven=[] liodd=[] while(i < len(li)): if li[i]%2==0: inp_even=li[i] lieven.insert(i,inp_even) else: inp_odd=li[i] liodd.insert(i,inp_odd) i=i+1 print (lieven) print (liodd)

b=[[1,2,3],[2,2,3],[4,5,6]]

b[0][2]

### Multi dimensional lists a=[[1,2],[3,4]] a[0][1]
for j in b: print(j)
b+b
print(a[1][1])
n=[["abc",29],["def",28]] n
n[0] n[1][1]

Python’s Tuples (1 hr)

  • Immutable

  • Common Tuples Methods

  • Tuples Operations

  • Tuples Indexing

  • Tuples Slicing

  • Tuples Iteration

  • Multi-Dimensional Tuples (Matrices)

a=(1,2,3,-9,0) a[1:3]#it will include a[1]& a[2]
#operations b=("red","blue") a+b c=3*b
d=("c","b","d","a","A") del d
a[3]=9 # Will show error as tuple are immutable del a[3]
min(a) max(a)
len(a)
b=("a","b","c","d","e","f") #concadination c=a+b c
z=(1,2,3) x=z[0] x
x,y = (7, 10) #sequence unpacking print("Value of x is {}, the value of y is {}.".format(x, y))

Indexing & Slicing

#c[1] #c[:1] #before index position 1 #c[1:] #before index position 1(includes index 1 also) #c[2:4] c[2:9:3] #start:stop:diff

Iteration

for i in a: #iterating over tuple print(i) print(a)
## Type conversion a=[1,2,3] tuple(a)
x=["a",1,2,"E"] tuple(x)
### l=[] number = int(input("how many value you want in a list: ")) for i in range(0,number): e = int(input("enter your choice number:")) l.append(e) n=tuple(b) print(n)

Enumerate

The enumerate function returns a tuple containing a count(index) for every iteration (from start which defaults to 0) and the values obtained from iterating over a sequence.

course = ('IoT', 'Data Science', 'Data Analytics', 'Machine Learning') for index, course in enumerate(course): print(index,course)

Tuples are faster than list

import timeit print(timeit.timeit('a=(1,2,3,4,5,6,7,8,9,10,11,12)', number=2000000)) print(timeit.timeit('b=[1,2,3,4,5,6,7,8,9,10,11,12]', number=2000000))
a=((6,7,3),(8,9,0),(7,3,3)) a
a[2][1]
for i in a: print(i)

Python Dictionaries (2 hr)

  • Python Dictionaries

  • Assigning Values to Dictionaries

  • Dictionary Methods

  • Dictionaries vs Lists & Tuples

  • Dictionary Indexing

  • Dictionary Iteration

  • Stack – Pop, Push

d={} d={"a":2,"b":3,"c":3} d #d["a"] #d.keys() #d.values()
max(d.values())
d.clear() print(d)
details = { "brand": "Ford", "model": "Mustang", "year": 1964 } details.pop("model") #removes model print(details)
details.update({"color": "White"}) print(car)
for i in details: print(i)
#Code to generate & print dictonary n=int(input("Input a number ")) d = {} for x in range(1,n+1): d[x]=x*x #value is square of number print(d) print("*"*20)
#sort (ascending and descending) a dictionary by value. import operator d = {1: -2, 3: 4, 4: 3, 2: 1, 0: 0} print('Original ',d) sorted_d = sorted(d.items(), key=operator.itemgetter(0)) print('Dictionary in ascending order by value : ',sorted_d) sorted_d = sorted(d.items(), key=operator.itemgetter(0),reverse=True) print('Dictionary in descending order by value : ',sorted_d) print("*"*20)
#merge two dict d1 = {'a': 1, 'b': 2} d2 = {'a': 3, 'd': 4} #d = d1.copy() d1.update(d2) print(d1)
#Map two list into dictionaries keys = ['red', 'green', 'blue'] values = [0,1,2] d1 = dict(zip(keys, values)) print(d1) print("*"*20)
#add a key to a dictionary. d = {0:10, 1:20,3:30} print(d) d.update({2:40}) print(d) print("*"*20) #Concatenate two dictinaries dic1={'a':1, 'b':2} dic2={'c':3, 'd':4} dic3={'e':5,'f':6,'g':7} dic4 = {} for d in (dic1, dic2, dic3): dic4.update(d) print(dic4) print("*"*20) #Sum all values in a dict my_d = {'d1':100,'d2':-4,'d3':12} print( "sum=",sum(my_d.values())) print("*"*20) #Map two list into dictionaries k = ['red', 'green', 'blue'] v = [0,1,2] d1 = dict(zip(k, v)) print(d1) print("*"*20)
#iterate dictinary over loop d = {'name' : 00, 'ash': 1, 'ashi': 2, 'sid': 3} for dict_key, dict_value in d.items(): print(dict_key,':',dict_value) print("*"*20)

SETS

s1={1,1,2,3,4,5,8} s2={1,4,8,-1,0} s2^s1
s1={"ashi","ram"} s2={"ashi","ram","ravi"} type(s1)
set1={10,20,30,40} set2={11,12,30} print("union of set1 & set2") print(set1|set2) print("Intersection of set1 & set2") print(set1&set2) print("difference between set1 & 2") print(set1-set2) print("symmettric diffrernce set 1 & 2",set1^set2)
for i in s1: print(i)
#s[0]="new" len(s1)
set1.add(60) set1 c=set1.copy() c set1.discard(10)#similary set1.remove set1
x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.update(y) print(x)
fs = frozenset({1,2,3,4}) # set assignment print("set=",fs) print("Type=",type(fs))
fs.add(6)
## Remove duplicate items from a list a = [10,20,30,20,10,50,60,40,80,50,40] b=set(a) b

loops

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

Creating Python Function (2hrs)

  • Function Basics

  • Defining Functions

  • Function Polymorphism

  • Argument Defaults

  • Lambdas

  • Local Variables

  • Understanding __builtin

  • Preventing Variable Modifications

  • Argument Matching Methods

  • Keyword Argument Methods

def new(x,y): s=x+y return x+y new(3,4)
def sub(x,y): diff=x+y return diff sub(4,5.0)
def data(name="",x=0,y=0,z=0): print(" %s :: %d years old." %(name,age)) data("SID",32) data("ash",28)
## function to multiply all the numbers in a list def multiply(numbers): total = 1 for x in numbers: total *= x return total print(multiply((8, 2, 3, -1, 7)))

A lambda function can take any number of arguments, but can only have one expression.

##lambda function that adds 10 to the number passed in as an argument, and print the result: x = lambda a : a*a print(x(132))
## A lambda function that multiplies argument a with argument b and print the result: x = lambda a, b,c : a * b*c print(x(5, 6,8))

The Python interpreter has a number of functions and types built into it that are always available.

  1. abs()

The abs() is one of the most popular Python built-in functions, which returns the absolute value of a number. A negative value’s absolute is that value is positive.

abs(-89)
#bin() converts an integer to a binary string bin(5) ##bin(0.7)#not works on float
## bool() converts a value to Boolean. bool(2) #bool("a") #bool("")
## complex() function creates a complex number complex(.8)
#eval() Function takes a string as an argument, which is parsed as an expression X=9 eval("3*X/X+6+(3**8)")
## hex() Python built-in functions, converts an integer to hexadecimal hex(17)
#To get details about any module, keyword, symbol, or topic, we use the help() function. help()

Errors & Exceptions

#ZeroDivisionError #Syntax Error(EOF Error,Indentation Error) #IOError #ImportError #ValueError #NameError #wrong operation :Type ERROR

Classses & Objects

class Phone: Color=" " Price =00 Type=" " ob1=Phone()#Creation of objects and assinging it to class phone. ob2=Phone() ob1.Color="RED" ob1.Price=10000 ob1.Type="Smart" ob2.Color="Black" ob2.Price=12000 ob2.Type="Smart" print("This is a %s phone of %s color and its price is %drs"%(ob1.Type,ob1.Color,ob1.Price)) print("This is a %s phone of %s color and its price is %drs"%(ob2.Type,ob2.Color,ob2.Price)) print(80*"*")
This is a Smart phone of RED color and its price is 10000rs This is a Smart phone of Black color and its price is 12000rs ********************************************************************************
class Shop: "Things in MYshop" Quantity = 10 Type = "" price=500.00 def bill(x): t=x.price*x.Quantity #print("your bill for % s dress of %d quantity = %frs:"%(x.Type,x.Quantity,t)) return t coustmer1=Shop() coustmer1.Quantity=5 coustmer1.Type="saree" coustmer1.price=20000 coustmer1.bill()
100000
  • All classes have a function called init(), which is always executed when the class is being initiated.

  • This type of function is also called constructors

class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
John 36
  • Inheritance allows us to define a class that inherits all the methods and properties from another class.

  • Parent class is the class being inherited from, also called base class.

  • Child class is the class that inherits from another class, also called derived class.

## Inheritance class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname()
class Student(Person): pass x = Student("Mike", "Olsen") x.printname()
File "<ipython-input-11-30b865ef42a3>", line 3 x = Student("Mike", "Olsen") ^ IndentationError: expected an indented block
#ZeroDivisionError #Syntax Error(EOF Error,Indentation Error) #IOError #ImportError #ValueError #NameError #wrong operation :Type ERROR print("*****ZeroDivisionError*******") try: x=int(input("Enter First Number")) y=int(input("Enter Second Number")) print("sum is:", x+y) print("div is:",x/y) print("product is:",x*y) except (ZeroDivisionError,ValueError) as e: print("oops!!Error either wrong division or wrong data type entered") print("ReEnter:") x=int(input("Enter First Number")) y=int(input("Enter Second Number")) print("sum is:", x+y) print("answer is:",x/y) print("product is:",x*y) print("****Module Error*****") try: import time t=time.strftime("%c") print(t) except ImportError as e: print("OOps you have imported wrong module") print("****IOE Error*****") try: a=input("Enter file name you want to read") f=open(a,"r") x=f.read() print(x) except IOError as e: print("you have entered wrong file name") a=input("ReEnter file name") f=open(a,"r") x=f.read() print(x) print("Name Error") x=6 try: print("the square of x is",(k*k)) except NameError as e: print("youn have entered unknow variable")

Regular Expression in Python (1 hr)

  • Meta Characters

  • re module

  • Search

  • Match

Hands On

  1. Script merge two list to create a dictionary

  2. Script that creates a user input list & later on converts it to immortal data set.

  3. Script to make a chain of function decorators (bold, italic, underline etc.).

  4. Script to remove leading zeros from an IP address

## Script merge two list to create a dictionary keys = ['red', 'green', 'blue'] values = ['Apple','Grapes', 'Berry'] color_dictionary = dict(zip(keys, values)) print(color_dictionary)
## Script that creates a user input list & later on converts it to immortal data set. lst = [ ] n = int(input("Enter number of elements : ")) for i in range(0, n): ele = [input(), int(input())] lst.append(ele) print(lst) ## Conversion to tuple(immortal data set) imm=tuple(lst) print("The immortal dataset=",imm)
## Script to make a chain of function decorators (bold, italic, underline etc.). def make_bold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def make_italic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped def make_underline(fn): def wrapped(): return "<u>" + fn() + "</u>" return wrapped @make_bold @make_italic @make_underline def hello(): return "hello world" print(hello()) ## returns "<b><i><u>hello world</u></i></b>"
##Script to remove leading zeros from an IP address def removeZeros(ip): # splits the ip by "." # converts the words to integeres to remove leading removeZeros # convert back the integer to string and join them back to a string new_ip = ".".join([str(int(i)) for i in ip.split(".")]) return new_ip ; ##example2 ip ="100.020.003.400" print(removeZeros(ip)) #example2 ip ="001.200.001.004" print(removeZeros(ip))

Project

Developing a project to apply revision of salary to the Employees based on set of rules.

totalsalary = 0 salaryhigh = 0 salarylow = 10000000 employee = 0 p1=p2=p3=p4=0 total_emp=int(input("Enter number of employees in your company")) for employee in range(0, total_emp): for i in range(1,total_emp): print("EMP %d details= " %(i)) salary=int(input("Emp Current Salary")) years=int(input("Emp Total Years in company")) rating=input("Overall rating of emp") contri = input("Contribution rating of emp") if (years >=5 && <=10): if rating =="Excellent": if contri=="Excellent": if salary <= 200000: print("Salary Raise =",(.15*salary)) elif>200000: print("Salary Raise = ",(.10*salary)) elif contri=="Good": if salary <= 200000: print("Salary Raise =",(.10*salary)) elif>200000: print("Salary Raise = ",(.8*salary)) elif contri=="Average": if salary <= 200000: print("Salary Raise =",(.8*salary)) elif>200000: print("Salary Raise = ",(.5*salary)) elif contri=="Poor": if salary <= 200000: print("Salary Raise =",(.5*salary)) elif>200000: print("Salary Raise = ",(.2*salary)) else : pass else : pass else: pass