Swapnil Saurav

Data Analytics – November 2022

DAY 1,2, 3: Click here to Download the class excel file

Click here to watch the Day 1 video

Assignment

Develop

1. Library Management System – think of different tables it can have and also add columns to those tables

2. Add constraints to columns as applicable

3. Add data types to each column

4. Add atleast 5 sample data to each table

 

SQL Server 

 

DATATYPES:

.Approximate numeric data types (Float)

This data type is used to store floating-point and real values. It is mainly used in scientific calculations.

Date and Time data types

We use these data types to hold the temporal values such as date and time, including time offset in a column.

Character string data type

This data type allows us to define the character data type only, which can be fixed or variable in length.

Unicode character string data types

This data type allows us to define the full range of Unicode character sets encoded in the UTF-16 character set.

Binary data types

This data type allows storing image, audio, and video files of fixed and variable length into a database location. It stores information in 0 and 1 format.

 

Creating a table

— Creating a table

Create Table Library.dbo.Members(

MemberID INT IDENTITY PRIMARY KEY,

Full_name Varchar(40) NOT NULL,

Phone char(10),

emailid Varchar(20)

)

 

— Create table databasename.schemaname.tablename()

— Within the bracket we need to give the column names and the data types

— Add constraints if any: Primary Key

— We can use Identity to generate unique integer values: SQL SERVER

 
Deleting a table and creating it again

USE [Library]

GO

 

/****** Object:  Table [dbo].[BOOKS]    Script Date: 24-11-2022 07:04:04 ******/

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[BOOKS]’) AND type in (N’U’))

DROP TABLE [dbo].[BOOKS]

GO

/****** Object:  Table [dbo].[BOOKS]    Script Date: 24-11-2022 07:03:22 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[BOOKS](

[BOOKID] [int] IDENTITY PRIMARY KEY,

[BTITLE] [nchar](10) NULL,

[AUTHOR] [nchar](10) NULL,

[COST] [real] NULL

GO

Codd’s Rules (defines RDBMS systems)

  • Rule 1 Information rule: information needs to be stored in a table format and each cell has to have one unique data => Table format
  • Rule 2 Guaranteed access: Each single data has to be accessible => each table has a primary key
  • Rule 3 Handling NULL values uniformly for all tables: data missing/not known/not applicable
  • Rule 4 Active online catalog: Data Dictionary (managed by system) should have all the information about metadata. => sys.objects in MSSS
  • Rule 5 comprehensive sub-language rule: database language to access data in a linear syntax format => SQL
  • Rule 6 Updating Rule (about Table): data needs to be updatable  => Update/Delete/Alter
  • Rule 7 Insert, Update, Delete available (Database)  => UNION,INTERSECTION etc
  • Rule 8 Physical data independence: can only be changed from within the database. No external factor can change the stored data. 
  • Rule 9 Logical data independence: Application should not be impacted by any change in the database
  • Rule 10 Integrity independence: database design can not be influenced by anyother team
  • Rule 11 Distribution independence: User need/should not know where the data is stored.
  • Rule 12 Non subversion: access to the lowest level => if you have access to a table, you should be able to access all the records/tuples in that table

Design

  • Table
  • Tuple
  • Record
  • Relation instance: group of columns that gives the relationship
  • Employee table: EMP_NAME & EMP_PHONE
  • Schema: Group of tables and other database objects
  • Relation key (KEY): set of columns that will uniquely identify each row
  • EMP_ID, NAME & DOB, Phonenumber & NAME
  • Referential Integrity constraint (FOREIGN KEY): link 2 tables, in current table its called FOREIGN KEY and in Other table, it has to be a Primary Key
 

E R Diagram

Example: (Member entity)

 

Handling Many to Many relationship:

 

Click here to Watch the Video

Home, Assignments and Projects

Homework 1:

Image Search for 3 ER diagrams from internet (preferably related to your domain of interest)

 

Re-draw it and just add 3-4 lines about that ER

 

Assignment 1:

E R diagram: Library Management System and We will later convert these into database

 

Project 1: Develop the conceptual model with an EntityRelationship Diagram (ERD)

1. What are the entities in our database (nouns – these will be the tables) – Draw these as rectangles

2. What are their attributes? (properties/characteristics of an entity that we want to collect and store in the DB) – think about what would uniquely identify a particular instance of the entity)

– Draw these as bubbles off the square

– Underline the attribute(s) that uniquely identifies instance

 

3. What are the relationships between entities? (what is the cardinality of that relationship? (1-1? 1-many? Etc.)

– Draw lines between entities – put a label on the line in a diamond

– Indicate by crow’s feet (or #’s) the cardinality at each end of the relationship

 

E R Diagram Refresher :

Rectangle — Entity

Ellipses — Attribute (underlined attributes are [part of] the primary key)

Double ellipses — multi-valued attribute

Dashed ellipses– derived attribute, e.g. age is derivable from birthdate and current date

Keys:

– Superkey:  an  attribute  or  set  of  attributes  that  uniquely  identifies  an entity–there  can  be  many  of  these

– Composite  key:  a  key  requiring  more  than  one  attribute

– Candidate  key:  a  superkey  such  that  no  proper  subset  of  its  attributes is  also  a  superkey  (minimal  superkey  – has  no  unnecessary attributes)

– Primary  key:  the  candidate  key  chosen  to  be  used  for  identifying entities  and  accessing  records.    Unless  otherwise  noted  “key”  means “primary  key”

– Alternate  key:  a  candidate  key  not  used  for  primary  key

– Secondary  key:  attribute  or  set  of  attributes  commonly  used  for accessing  records,  but  not  necessarily  unique

– Foreign  key:  term  used  in  relational  databases  (but  not  in  the  E-R model)  for  an  attribute  that  is  the  primary  key  of  another  table  and  is used  to  establish  a  relationship  with  that  table  where  it  appears  as  an attribute  also. So  a  foreign  key  value  occurs  in  the  table  and  again  in the  other  table.  This  conflicts  with  the  idea  that  a  value  is stored  only once;  the  idea  that  a  fact  is  stored  once  is  not  undermined.

Using Management Studio:

USE [Library]

GO

 

/****** Object:  Table [dbo].[Transactions]    Script Date: 29-11-2022 06:36:52 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[Transactions](

[TID] [smallint] IDENTITY(1,1) NOT NULL,

[MemberID] [int] NOT NULL,

[BookID] [int] NOT NULL,

[IssueDate] [date] NULL,

[ReturnDate] [date] NULL,

 CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED 

(

[TID] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

GO

 

ALTER TABLE [dbo].[Transactions]  WITH CHECK ADD  CONSTRAINT [FK_Transactions_Transactions] FOREIGN KEY([MemberID])

REFERENCES [dbo].[Members] ([MemberID])

GO

 

ALTER TABLE [dbo].[Transactions] CHECK CONSTRAINT [FK_Transactions_Transactions]

GO

 

ALTER TABLE [dbo].[Transactions]  WITH CHECK ADD  CONSTRAINT [FK_Transactions_Transactions1] FOREIGN KEY([BookID])

REFERENCES [dbo].[BOOKS] ([BOOKID])

GO

 

ALTER TABLE [dbo].[Transactions] CHECK CONSTRAINT [FK_Transactions_Transactions1]

GO

 

USING QUERY EDITOR:

 

Create Table BOOKDETAILS (

BDID SMALLINT PRIMARY KEY,

BOOKID INT FOREIGN KEY REFERENCES BOOKS(BOOKID),

CITY varchar(15),

Publisher varchar(15) 

)

Go

— Insert data into the tables

Insert into dbo.Members(Full_name,Phone,emailid) values(‘Sachin’,’23456′,’sachin@sachin.com’)

GO

Insert into dbo.Members(Full_name,Phone,emailid) values(‘Kapil’,’45456′,’kapil@sachin.com’)

GO

 

— Reading is done by Select query

Select MemberID, Full_name from dbo.Members

 

— Practice https://livesql.oracle.com/

 


 

— ALTER is used to change the structure of your table – add, drop, Alter (modify in some versions) table members

 

ALTER TABLE dbo.BOOKS

ADD ISBN char(13)

GO

ALTER TABLE dbo.BOOKS

ADD ISBN_10 char(10)

Go

 

— Drop column ISBN_10

ALTER TABLE dbo.BOOKS

DROP COLUMN ISBN_10

Go

 

— Change the datatype of a column

ALTER TABLE dbo.BOOKS ALTER COLUMN ISBN int

 

— ####################################

— Properties of a Foreign Key

— On DELETE OR UPDATE:

— 1. NO ACTION

— 2. CASCADE

— 3. SET TO NULL

— 4. DEFAULT

 

— DELETE – when value in main table is deleted, it performs above selected option in the secondary table

— UPDATE – when value in main table is updated, it performs above selected option in the secondary table

 

— BOOKS : 1 , 2, 3

 

— Delete : SET TO NULL

— UPDATE : CASCADE

 

ALTER TABLE dbo.BOOKS ALTER COLUMN BTITLE nchar(30)

GO

ALTER TABLE dbo.BOOKS ALTER COLUMN AUTHOR nchar(30)

GO

 

Insert into dbo.Books(BTITLE,AUTHOR) values (‘SQL Programming’,’Sachin’)

 

select * from dbo.BOOKS

go

select * from dbo.members

go

 

select * from dbo.Transactions

go

 

Insert into dbo.Transactions (MemberID,BookID,IssueDate) Values (1,2,GETDATE())

 

Insert into dbo.Transactions (MemberID,BookID,IssueDate) Values (2,2,GETDATE())

 

–Update the existing value in table

Update dbo.Transactions Set BookID = 3 where TID=2

 

 

Update dbo.Members Set MemberID = 100 where MemberID=1

 

Delete from dbo.Members where MemberID=1

DAY 16: using SELECT in SQL  (livesql.oracle.com)

 

select * from hr.employees;

 

Select EMPLOYEE_ID, LAST_NAME, FIRST_NAME, EMAIL, HIRE_DATE from hr.Employees;

 

 

Select EMPLOYEE_ID, LAST_NAME “LASTNAME”, FIRST_NAME, EMAIL, SALARY, HIRE_DATE from hr.Employees;

 

Select EMPLOYEE_ID, LAST_NAME AS LASTNAME, FIRST_NAME, EMAIL, SALARY, HIRE_DATE from hr.Employees;

 

 

Select EMPLOYEE_ID, LAST_NAME “LASTNAME”, FIRST_NAME, EMAIL, SALARY, SALARY*12 “ANNUAL SALARY”, HIRE_DATE from hr.Employees;

 

Select Distinct last_name , first_name from hr.Employees

 

Select Distinct last_name , first_name, COMMISSION_PCT from hr.Employees ORDER BY COMMISSION_PCT

 

Select Distinct last_name , first_name, COMMISSION_PCT from hr.Employees ORDER BY COMMISSION_PCT NULLS FIRST

 

Select first_name || ‘ ‘ || last_name “Employee_Name” from hr.Employees

 

Select first_name || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” from hr.Employees

 

Select FIRST_NAME || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” from hr.Employees Where Department_ID = 60 AND first_name = ‘Alexander’

 

Select first_name || ‘ ‘ || last_name || ‘ Earns $’ || Salary*12 || ‘ Annually’ “Message” , Department_ID from hr.Employees Where Department_ID = 60 OR Department_ID = 90

 

select * from hr.employees;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT >= .2;

 

— order by to sort

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT >= .2 order by COMMISSION_PCT  desc;

 

select first_name, last_name, salary, COMMISSION_PCT, HIRE_DATE from hr.employees where COMMISSION_PCT >= .2 order by HIRE_DATE 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null and rownum <=5;

 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null and rownum <=5 order by COMMISSION_PCT ;

 

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null order by COMMISSION_PCT ASC , FIRST_NAME ASC

 

— You can also refer column using a number – 1 indicate first column which is first_name

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where COMMISSION_PCT is not null order by COMMISSION_PCT ASC, 1;

 

select first_name, last_name, salary, COMMISSION_PCT from hr.employees where first_name like ‘%d%’ order by COMMISSION_PCT NULLS FIRST

 

— AND : first_name like ‘D%’ and salary > 5000   – MIN RECORD 0  MAX RECORD  10  – COUNT = 5  –  INTERSECTION

— OR  : first_name like ‘D%’ or salary > 5000  – MIN RECORD 20  MAX RECORD  30  – COUNT = 25 – UNION

 

— 10 records where names which starts with D , 20 records which has salary greater than 5000  / 5 rows which are common

 

select count(*) from hr.employees where first_name like ‘D%’ ;  –9

select count(*) from hr.employees where salary >=5000;  –58

select count(*) from hr.employees where salary >=5000 and first_name like ‘D%’  ; — 5

 

select first_name, last_name from hr.employees where salary >=5000

INTERSECT

select first_name, last_name from hr.employees where first_name like ‘D%’;

 

select count(*) from hr.employees where salary >=5000 or first_name like ‘D%’;

select first_name from hr.employees where salary >=5000

UNION

select first_name from hr.employees where first_name like ‘D%’;

 

— OPERATORS in SQL

—  Identity / negation   + –

— Multiplication Division    * /

— Addition, Subtraction, Concatenation    + –  ||

— Comparison operators:     =   !=   <   >   <=    >=  IS NULL   LIKE   BETWEEN   IN

— Logical Operators:   NOT   AND    OR

— Set operators:   UNION   INTERSECT  MINUS

 

select * from hr.employees where salary <0

 

select * from hr.employees  where -salary < 0   — negation

 

select FIRST_NAME, LAST_NAME, Salary*12 Annual_Salary from hr.employees   — Multiplication

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* COMMISSION_PCT Total_Salary , COMMISSION_PCT, Salary  from hr.employees

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where salary between 5000 and 10000 

 

— IT_PROG   AD_VP  (60,90)

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where DEPARTMENT_ID IN (90,60)

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name, Salary+ Salary* coalesce(COMMISSION_PCT,0) Total_Salary , COMMISSION_PCT, Salary  from hr.employees where JOB_ID IN (‘IT_PROG’,’AD_VP’)

 

select * from hr.departments

 

select DEPARTMENT_ID from  hr.departments  where LOCATION_ID in (1700, 1800, 1500)

 

select FIRST_NAME ||’ ‘|| LAST_NAME Full_Name  from hr.employees where DEPARTMENT_ID IN (select DEPARTMENT_ID from  hr.departments  where LOCATION_ID in (1700, 1800, 1500))

 

 

select FIRST_NAME, LAST_NAME, LOCATION_ID , emp.DEPARTMENT_ID from hr.employees emp, hr.departments dept where COMMISSION_PCT is not null and emp.DEPARTMENT_ID = dept.DEPARTMENT_ID

 

— OPERATORS in SQL

 

—  Identity / negation   + –

 

— Multiplication Division    * /

 

— Addition, Subtraction, Concatenation    + –  ||

 

— Comparison operators:     =   !=   <   >   <=    >=  IS NULL   LIKE   BETWEEN   IN  ANY SOME ALL

 

— Logical Operators:   NOT   AND    OR

 

— Set operators:   UNION   INTERSECT  MINUS

 

Select * from hr.employees

 

Select * from hr.employees where salary = ANY (3000,6000)

 

Select * from hr.employees where salary = 3000 or salary =6000

 

Select * from hr.employees where salary = SOME (3000,6000)

 

Select * from hr.employees where salary >= ALL (3000,6000)

 

Select * from hr.employees where salary = 3000 and salary =6000

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

UNION

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

UNION ALL

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

INTERSECT

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

 

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

INTERSECT

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

 

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

MINUS

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

 

— (1,3,5,6) – (2,4,6,7)  =  (1,3,5)

 

Select First_name, last_name from hr.employees where salary = 3000 or salary =6000

MINUS

Select First_name, last_name from hr.employees where DEPARTMENT_ID = 30 or DEPARTMENT_ID =60

 

 

DEFINE salary_val = 3000

Select First_name, last_name from hr.employees where salary = &salary_val

UNDEFINE salary_val

 

— FUNCTIONS – String/text

Select lower(first_name), upper(last_name), initcap(email) from hr.employees

 

select concat(concat(first_name,’ ‘), last_name) from hr.employees — 2 strings

 

— Substring : SUBSTR    returns the position of a char:  INSTR

select first_name, substr(first_name,1,5), instr(upper(first_name),’A’) from hr.employees

 

— RPAD LPAD

 

select RPAD(first_name,12,’.’) || ‘ ‘ || LPAD(last_name,10,’x’)  from hr.employees

 

select RPAD(first_name,9,’ ‘) || ‘ ‘ || LPAD(last_name,9,’ ‘) || ‘ works as ‘ || LPAD(JOB_ID,8,’ ‘) MESSAGE from hr.employees

 

 

— — Number Functions

select * from dual


select sqrt(36) from dual


select distinct sqrt(salary) from hr.employees


select salary + COMMISSION_PCT TOTAL_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, round(salary + COMMISSION_PCT) ROUND_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, trunc(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, ceil(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary + COMMISSION_PCT TOTAL_SALARY, floor(salary + COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


select salary * -COMMISSION_PCT TOTAL_SALARY, ABS(salary * -COMMISSION_PCT) TRUNC_SALARY from hr.employees where COMMISSION_PCT is not null


Select MOD(19,5) from dual


— — DATE FUNCTIONS

select * from hr.employees


select sysdate from dual


select FIRST_NAME, LAST_NAME, HIRE_DATE, floor(sysdate-hire_date)  from hr.employees


select FIRST_NAME, LAST_NAME, HIRE_DATE,  floor(sysdate-hire_date)  DAYS_SERIVICE, MONTHS_BETWEEN(sysdate,hire_date) MONTHS_SERVICE  from hr.employees


select ADD_MONTHS(sysdate,5) from dual


select NEXT_DAY(sysdate,1)  from dual — date of the first weekday 1 for Sunday, 2 for Monday ….


select NEXT_DAY(sysdate,’FRIDAY’)  from dual — date of the first weekday


select last_day(sysdate)   from dual


select last_day(‘1-Feb-2023’)   from dual


select next_day(‘1-Feb-2023’,2)   from dual


select ADDDATE(day,1,sysdate)   from dual


— year, quarter, month, day


select sysdate + 1 from dual


select DateAdd(sysdate, “1”, 10) from dual



select to_char(sysdate+100, ‘Dy DD-Month-YYYY HH24:MI:SS’) as “Current Time” from dual;


select dayofweek(sysdate) from dual


select now() from dual


Digitalfirm Nov 2022

Day 1:

Installation:

Python:  https://learn.swapnil.pw/python/pythoninstallation

 Pycharm:  https://learn.swapnil.pw/python/pythonides

 R & RStudio:   https://swapnil.pw/uncategorized/installating-r-studio

https://www.mckinsey.com/featured-insights

 

print("terterterg feererg eryey erytey eytytyt",end='\n')
print(10+5);print("10+5+3+1");print(10+5+3+1)
print("10+5+3+1 =",10+5+3+1, "and 5 + 4 + 95 =", 5+4+95);

# \n is used to move the content to new line
print('Hello',end='. ')
print("How are you",end='. ')
print("Thank you",end='\n') #I am printing thank you here
'this is a sample content print("Thank you")'
'''
multiline
text

'''
print(''' this is a sample text''')
print("\n is use for newline") #printing text is 2 different lines
print("\\n is use for newline") # \\ will be read as \

########################################
num1 = 18+4+2+10
print(num1)
print(num1)

print(num1)
print(num1)

quantity = 13
cost = 19
total = quantity * cost
print(total)
#output: The cost of each pen $19 so the total cost of 17 pens will be $323
print("The cost of each pen $",cost,"so the total cost of",quantity,"pens will be $",total)
#using f string - use variables within strings - variable should be in {}
print(f"The cost of each pen ${cost} so the total cost of {quantity} pens will be ${total}")

# basic variables
#integer
#float
#string
#bool
#complex
#data types
a = 50 #int - numbers without decimal
print("a = 50 => ", type(a))
a = 50.0 #float - numbers decimal
print("a = 50.0 => ", type(a))
a = "50" #str - text
print("a = '50' => ", type(a))
a = True # or False - 2 values , bool
print("a = True => ", type(a))
a = 5j #j is square root of -1
print("a = 5j => ", type(a))
print(a*a)

#Operators
print("Arithematic operations")
a=5
b=8
print(a+b)
print(a-b)
print(a*b)
print(b/a) #float as output
print(a**b) #** power/exponential
print(a//b) #integer division
print(b//a) #integer division
print(a%b) # 5
print(b%a)

print("Conditional Operators")
#input as integer/float - output will be bool
a=8 #assignment, assigning the value 5 to a
b=8
print(a>b) #is a greater than b
print(a<b)
print(a>=b)
print(a<=b)
print(a==b) # == asking a question
print(a!=b) #is a not equal to b
#Logical operators: I/P: Bool and O/P: Bool
# P1: Sachin and Dravid will open the batting
# P2: Sachin or Dravid will open the batting
# A: Sachin and Sehwag opened the batting -
#AND - even one condition is FALSE - entire thing would be False
#OR - even one condition is TRUE - entire thing would be TRUE
a = 10
b = 20
print("a>b or b>a and b!=a: ",not(a>b or b>a and b!=a))
print("not b==a: ",not b==a)
# TRUE

#membership: in
l1 = [3,4,5,6,7]
print(l1)
print(type(l1))
print(5 not in l1)

#convert into different number systems
a= 10 #integer - decimal number system
print(bin(a))
b=0b10
print("b = ",int(b))
#hex for hexadecimal (0x5050) and oct for octal (0o) - number systems
print(oct(b))
print(hex(b))
###### example 1
marks1 = 89
marks2 = 90
marks3 = 56
marks4 = 67
marks5 = 78
sum = marks1 + marks2+marks3 + marks4 + marks5
avg = sum/5
print(f"Total marks obtained in 5 subjects is {sum} and average is {avg} %")

###### example 2
marks1 = input("Enter marks in Subject 1: ")
marks1 = int(marks1)
marks2 = int(input("Enter marks in Subject 2: "))
marks3 = 56
marks4 = 67
marks5 = 78
sum = marks1 + marks2+marks3 + marks4 + marks5
avg = sum/5
print(f"Total marks obtained in 5 subjects is {sum} and average is {avg} %")

# Conditional statements
if avg>=50:
print("You have passed")
print("In IF")
print("Hello")
print("hi")
else:
print("You have failed")

print("Thank you")
#
##Assignment 1: Input a number from the user and Check if the number is positive or not
##Assignment 2: Input number of sides from the user and check if its triangle or not
n=4  #s2 = 0 s1 =5
if n<3:
print("Invalid Shape")
elif n==3:
print("Its a triangle")
elif n==4:
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1==s2:
print("Its a square")
if s1==0:
print("Area is not possible")
else:
print("Area is: ",s1*s2)
else:
print("Its a rectangle")
if s1==0:
print("Area is not possible")
else:
if s2==0:
print("Area is not possible")
else:
print("Area is: ",s1*s2)

elif n==5:
print("Its a pentagon")
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1 == s2:
print("Its a square")
if s1 == 0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
else:
print("Its a rectangle")
if s1 == 0 or s2==0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
elif n==6:
print("Its a hexagon")
s1 = int(input("Enter length: "))
s2 = int(input("Enter breadth: "))
if s1 == s2:
print("Its a square")
if s1 == 0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
else:
print("Its a rectangle")
if s1 == 0:
print("Area is not possible")
elif s2==0:
print("Area is not possible")
else:
print("Area is: ", s1 * s2)
elif n==7:
print("Its a heptagon")
elif n==8:
print("Its an octagon")
else:
print("Its a complex shape")


#Assignment: Program to find sum and avg of 5 marks
# and assign grade on the basis on:
# avg > 90: A
#avg >75: B
#avg >60: C
#avg >50: D
#avg >40: E
#avg<40: F
#Loops- repeat given block of code

#For loop - exactly how many times to repeat
for i in range(1,10,2): #range(start - included,end-excluded,increment): 1,3,5,7,9
print(i,":Hello")

for i in range(3, 6): # range(start - included,end-excluded,increment=1): 3,4,5
print(i, ":Hello")

for i in range(3): # range(start=0,end-excluded,increment=1): 0,1,2
print(i, ":Hello")
sum=0
for i in range(5):
marks = int(input("Enter marks: "))
sum+=marks
avg = sum/5

for i in range(5):
print("*",end=" ")
print()
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()
print("------------------\n")
'''
* * * * *
* * * *
* * *
* *
*
'''
for j in range(5):
for i in range(5-j):
print("*",end=" ")
print()
print("------------------\n")

'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(1+j):
print("*",end=" ")
print()
print("------------------\n")

'''
*
* *
* * *
* * * *
* * * * *
'''
#While
i=0
while i<5:
print("Hello")
i+=1

#adding 2 numbers till user says yes
ch='y'
while ch=='y':
a=30
b=50
print("Sum is 80")
ch=input("type y to continue, anyother key to stop: ")



#rewriting same program using While True
while True:
a = 30
b = 50
print("Sum is 80")
ch = input("type y to continue, anyother key to stop: ")
if ch!='y':
break

#lets write a program to print addition of 2 numbers only when they are even
#otherwise ignore, continue till user wants

while True:
n1 = int(input("Enter first number: "))
if n1%2==1:
continue #continue will take you the beginning of the loop
n2 = int(input("Enter second number: "))
if n2 % 2 == 1:
continue
sum = n1 + n2
print("Sum is ",sum)
ch=input("Hit enter to continue, anyother key to stop: ")
if len(ch)!=0:
break #break will throw you out of the loop

Assignments

1.     # Assignment 1: Modify the Total Avg marks calculation program to do it for 5 students
# Assignment 2: Modify your Voting program (eligible to vote or not) to a repeat it for multiple input until
# user wants to continue

  1. Write a Python program that computes the factorial of an integer.
  2. Program to find sum N natural numbers
  3. Write code to display and count the factors of a number
  4. Program to check if eligible to vote in India
  5. Enter marks of 3 subjects for 5 students and grade them. Check for data validity and use BREAK and CONTINUE where necessary
  6. Check the type of a Triangle: Isosceles, Equilateral, Scalene, Right Angle
  7. Input 3 numbers and re-arrange them in ascending order. Use BOOLEAN
#STRINGS
name1 = "Sachin"
#first character
print(name1[0]) #0 is for first character
print(name1[2]) #3rd character
size = len(name1)
print(name1[size-1]) #last character
print(name1[-1]) #last character
print(name1[1:4]) #2,3,4 th characters
print(name1[:3]) #no val on left of : means its zero
print(name1[3:6]) #last 3 characters
print(name1[size-3:size]) #last 3 characters
print(name1[-6:-3]) #first 3 characters
print(name1[-size:3-size]) #first 3 characters
print(name1[-3:]) #last 3 char - no val on right of :mean go till last

print("For loop")
for i in name1:
print(i)

for i in range(len(name1)):
print(f"the chracter at the index {i} is {name1[i]}")

for i in enumerate(name1):
print(i)

for i,j in enumerate(name1):
print(f"the chracter at the index {i} is {j}")

print("S" in name1)
name2 = "Tendulkar"
print(name1 + " " + name2)

print((name1 +" ")* 4)
#STRINGS
name1 = "Sachin"
#first character
print(name1[0]) #0 is for first character
print(name1[2]) #3rd character
size = len(name1)
print(name1[size-1]) #last character
print(name1[-1]) #last character
print(name1[1:4]) #2,3,4 th characters
print(name1[:3]) #no val on left of : means its zero
print(name1[3:6]) #last 3 characters
print(name1[size-3:size]) #last 3 characters
print(name1[-6:-3]) #first 3 characters
print(name1[-size:3-size]) #first 3 characters
print(name1[-3:]) #last 3 char - no val on right of :mean go till last

print("For loop")
for i in name1:
print(i)

for i in range(len(name1)):
print(f"the chracter at the index {i} is {name1[i]}")

for i in enumerate(name1):
print(i)

for i,j in enumerate(name1):
print(f"the chracter at the index {i} is {j}")

print("S" in name1)
name2 = "Tendulkar"
print(name1 + " " + name2)

print((name1 +" ")* 4)
# String methods
val1 = "Sachin 10Dulkar"
print(val1.isalnum())
print(val1.islower())
print(val1.istitle())
val2 = "12345"
print(val2.isdigit())
#lower upper title
print("Second set of functions")
val3 = "how ARE you doiNG todaY?"
print(val3.upper())
print(val3.lower())
print(val3.title())
#find
txt_to_search = "Are"
val4 = val3.lower()
print(val4.find(txt_to_search.lower()))
print(val3.replace("ARE","is"))
val3 = val3.lower().replace("are","is")
print(val3)

#split and join
val3 = "how ARE you are doiNG todaY?"
print(val3.split())
val4 = "HOW|ARE|YOU|DOING|TODAY"
print(val4.replace("|"," "))
val4_list = val4.split("|")
val6_str = " ".join(val4_list)
print(val6_str)
val7 = " how ARE you doiNG todaY? "
val7_strip = val7.strip()
print(val7_strip)
val_cnt = val3.lower().count("area")
print(val_cnt)
# LIST
str1 = "Hello"
print(str1[1])
# str1[1] = "Y" #this is not possible
# strings are called as immutable data types
list1 = [50, 4, 5.5, "Hello", True]
print(type(list1))
print(len(list1))
print(list1[3][2])
print(type(list1[3]))

for i in list1:
print(i)
for i in range(len(list1)):
print(list1[i])

l1 = [1, 2, 3, 4]
l2 = [10, 20, 30]
l3 = l1 + l2
print("Adding two list: ", l3)
print("Multiply: ", l2 * 3)
print(30 not in l2)

print(l2[2])
l2[2] = "Thank You" # lists are mutable
print(l2[2])

sum = 0
marks = []
for i in range(0):
m1 = int(input("Enter marks: "))
sum += m1
marks.append(m1)

print("Total marks", sum)

# append will add at the end
# insert - pos and value: value is added at the given pos
marks.insert(2, 11) # [11
marks.insert(2, 22) # [11,22]
marks.insert(2, 33) # [11,22,33]
marks.insert(2, 44) # [11,22,44,33]
marks.insert(2, 55) # [11,22,55,44,33]
marks.insert(2, 66) # [11,22,66,55,44,33]
marks.insert(2, 77) # [11,22,77,66,55,44,33]
# marks[7] = 100 - error since index 7 isnt there
print("Marks obtained are: ", marks)
# pop - removes from the given position
# remove - removes given value
val_remove = 77
if val_remove in marks:
marks.remove(val_remove)
else:
print("Value is not present in the list")
print("Marks obtained are: ", marks)
pos_remove = 2
if pos_remove < len(marks):
marks.pop(pos_remove)
else:
print("List doesnt have that index")

print("Marks obtained are: ", marks)
marks.clear()
print("Marks obtained are: ", marks)

Assignment


 

Assignments

1. Write a Python program to sum all the items in a list.

2. Write a Python program to multiplies all the items in a list.

3. Write a Python program to get the largest number from a list.

4. Write a Python program to get the smallest number from a list.

5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. 

Sample List : [‘abc’, ‘xyz’, ‘aba’, ‘1221’]

Expected Result : 2

6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. 

Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

7. Write a Python program to remove duplicates from a list.

8. Write a Python program to check a list is empty or not.

9. Write a Python program to clone or copy a list.

10. Write a Python program to find the list of words that are longer than n from a given list of words.

11. Write a Python function that takes two lists and returns True if they have at least one common member.

12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.

Sample List : [‘Red’, ‘Green’, ‘White’, ‘Black’, ‘Pink’, ‘Yellow’]

Expected Output : [‘Green’, ‘White’, ‘Black’]

13. Write a Python program to generate a 3*4*6 3D array whose each element is *.

14. Write a Python program to print the numbers of a specified list after removing even numbers from it.

15. Write a Python program to shuffle and print a specified list.

16. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).

17. Write a Python program to generate and print a list except for the first 5 elements, where the values are square of numbers between 1 and 30 (both included).

18. Write a Python program to generate all permutations of a list in Python.

19. Write a Python program to get the difference between the two lists.

20. Write a Python program access the index of a list. 

DAY 8

 

def myreverse(a):
print("A = ", a)
a.reverse()
return a[0]


list1 = [50, 4, 5.5, "Hello", True]
list2 = [90, 20, 50, 40, 30, 70]
list2.reverse()
# print(list2)
print("Myreverse: ", myreverse(list2))
print(list2.reverse())
list2.sort()
# print(list2)
list1.extend(list2)
print("New set: ", list1)
a = "5"
# print(int(a))
print("Learning COPY")
list2 = [90, 20, 50, 40, 30, 70]
list3 = list2 # shallow copy
list4 = list2.copy() # deep copy
print("list2: ", list2)
print("list3: ", list3)
print("list4: ", list4)
list2.append(10)
print("list2: ", list2)
print("list3: ", list3)
print("list4: ", list4)

print("Stack Implementation")
list_master = []
while True:
print("1. Add to the stack")
print("2. Remove from the stack")
print("3. Clear the stack")
print("4. Quit")
op = int(input("Enter your option"))
if op == 1:
val = int(input("Enter the element to add: "))
list_master.append(val)
print("After adding list: ", list_master)
elif op == 2:
if len(list_master) > 0:
list_master.pop(-1)
print("After adding list: ", list_master)
else:
print("List is empty!")
elif op == 3:
list_master.clear()
print("After adding list: ", list_master)
elif op == 4:
print("Thank you for using the program.")
break
else:
print("Invalid option, Try again!")

############### LIST #######################

# TUPLE
t2 = ()
t3=(55,)
t1 = (5, 4, 6, 8, 4)
print(type(t1))
t1 = list(t1)
print(t1.count(8))
# Dictionary
# list: linear ordered mutable collection
# tuple: linear ordered immutable collection
# dictionary: non-linear ordered mutable collection (unordered untill 3.7)
# dictionary is made up of key & value
dict1 = {} # empty dictionary
print(type(dict1))
dict1 = {"Name": "Sachin", "City": "Mumbai", "Runs": 12900, "IsPlaying": False}
print(dict1)
print(dict1["City"])
print(dict1.get("City"))
val = "India"
key = "Country"
t_dict = {key: val}
dict1.update(t_dict)
print("Dictionary after Update: \n", dict1)
print("Size of dictionary: ", len(dict1))

print("keys:", dict1.keys())
for i in dict1.keys():
print(i)
for i in dict1.values():
print(i)
for i in dict1.keys():
print(dict1[i])

for i, j in dict1.items():
print(i)

if "City" in dict1: # default it checks in keys
print("We have City")
if "Mumbai" in dict1.values():
print("We have City Mumbai")
else:
print("Mumbai is not there")

print("Dict1: ", dict1)
dict1.pop("City") # key as input
print("Dict1: ", dict1)
dict1.popitem() # key as input
print("Dict1: ", dict1)
print(type(dict1.values()))
dict1.pop(list(dict1.keys())[list(dict1.values()).index("Sachin")])
# print()
print("Dict1: ", dict1)
#Set - also mutable
set1 = {"New York"}
print(type(set1))
set1.add("Chicago")

#update
#union
s1 = {1,3,5,7,2,4}
s2 = {2,4,6,8}
print("Union: ",s1.union(s2))
print("Union: ",s1 | s2)
#s1.update(s2)
#print("Union Update: ",s1)

#difference
print("difference :",s1-s2)
print("difference :",s2-s1)
print("Difference: ",s1.difference(s2))
#s1.difference_update(s2)
#print("Difference update: ",s1)
print("Symmetric Difference: ", s1 ^ s2)


#intersection
print("intersection :",s1.intersection(s2))
print("intersection: ",s1 & s2)
print("intersection update: ",s1.intersection_update(s2))
print(s1)
s1.intersection_update(s2)
print("intersection update: ",s1)

print(set1)
l1 = [5,10,10,15,15,15,20,20,25]
l1 = list(set(l1))
print(l1)

### Functions



def myfunc1(name): #which takes ONE input argument and doesnt return anything
print("Hello ",name)
print("How are you?")
print("Where are you going?")

def myfunc2(name): #which takes ONE input argument and doesnt return anything
print("Hello ",name)
print("How are you?")
print("Where are you going?")
return "Thank You", "Bye"

def myfunc(): #this is an example which doesnt take any input argument and doesnt return
print("Hello")
print("How are you?")
print("Where are you going?")

myfunc()
print("second time: ")
myfunc1("Kapil") #1 required positional argument: 'name'
print(myfunc2("Sachin"))


#functions

#required positional arguments
## Function definition
def calculate(a,b):
print("Value of a is ",a)
print("Value of b is ",b)
sum = a+b
diff = a-b
mul = a*b
div = a/b
return sum,diff,mul,div

## Function definition - Default argument
def calculate1(a,b=50):
print("Value of a is ",a)
print("Value of b is ",b)
sum = a+b
diff = a-b
mul = a*b
div = a/b
return sum,diff,mul,div

result = calculate(30,20)
print("Addition of given 2 values is ", result[0])
result = calculate1(30,5)
print("Addition of given 2 values is ", result[0])
result = calculate1(30)
print("Addition of given 2 values is ", result[0])
#non positional
result = calculate1(b=30,a=5) #nonpositional => Keyword arguments
print("Addition of given 2 values is ", result[0])

#variable name arguments
def mycalculation(a,c,*b,**d): # * takes multiple values
print("A = ",a)
print("B = ", b)
print("C = ", c)
print("D = ", d)

mycalculation(5,6,7,8,9,10,11,name="Sachin", runs=5000)

def check_prime(a):
result1 = True
for i in range(2,a//2):
if a%i == 0:
result1 = False
break
return result1

result = check_prime(1100)
if result:
print("Its a prime number")
else:
print("Its not a prime number")

#generate prime numbers between 500 and 1000
prime_num = []
for i in range(500,1001):
if check_prime(i):
prime_num.append(i)
print("Prime numbers are: ",prime_num)
#Recursive function
def myfunc(number):
if number <1:
return 0
print(number)
myfunc(number-1)

def factorial(n):
if n<1:
return 1
return n * factorial(n-1)


if __name__ =="__main__":
myfunc(100)
# 5! = 5 * 4 * 3 * 2 * 1!
fact = factorial(5)
print("Factorial is ",fact)
class Person:
population = 0
def welcome(self,name):
self.name = name
print("Welcome to the world")
Person.population+=1

def display(self):
print("Welcome to ",self.name)
print("Total Population: ",Person.population)

p1 = Person()
p1.welcome("Sachin")
p3 = Person()
p3.welcome("Laxman")

p2 = Person()
p4 = Person()
p5 = Person()
p2.welcome("Rekha")
p4.welcome("Geeta")
p5.welcome("Rohit")
p3.display()
p4.display()
class Person():
def __method1(self):
print("Method 1")
def _method2(self):
print("Method 2")
def method3(self):
print("Method 3")
self.__method1()
class Student(Person):
def read(self):
print("I am studying")

p1 = Person()
#p1.__method1() - private members cant be called
p1.method3()
p1._method2()

s1 = Student()
s1.read()
s1.method3()

# public
#protected _ :practically its like public, but theoritically it cant be accessed outside the class
#private __ : members can not be used outside the class

19 DEC 2022

#Class
str1="555"
print(type(str1))
str2 = "Good day"
print(str1.upper())

class Apple:
loc = "World"
def getvalue(self,name):
self.name = name
def display(self):
print(f"I am {self.name}")
@classmethod
def setaddress(cls):
cls.loc = "Universe"
@classmethod
def address(cls):
print(f"Location: {cls.loc}")

a1=Apple()
a1.getvalue("Sachin")
a2=Apple()
a2.getvalue("Kapil")
a3=Apple()
a3.getvalue("Laxman")
a4=Apple()
print(type(a1))
a1.display()
a1.setaddress()
a2.address()

class MySum:
def getval(self):
self.num1 = int(input("Enter value 1: "))
self.num2 = int(input("Enter value 2: "))
def printsum(self):
self.sum = self.num1 + self.num2
print("Sum of the values: ",self.sum)

m1 = MySum()
m1.getval()
m1.printsum()
class Employee:
population = 0

def __init__(self,name,age, salary):
self.name = name
self.age = age
self.__salary = salary
Employee.population +=1

def edit_details(self,name,age,salary):
self.name = name
self.age = age
self.__salary = salary
def _getsalary(self):
return self.__salary

@classmethod
def display_pop(cls):
print("Total Count of Objects = ",cls.population)

p1 = Employee("Sachin",48,1500) # this is calling __init__()
p2 = Employee("Virat", 29,1400)
p3 = Employee("Rohit", 29,1300)
#print(p1.__salary)
p1.display_pop()
print(p1._getsalary())
#print(p2.getsalary())
#print(p3.getsalary())

'''
Encapsulation:
access modifiers:
3 types: Public (variablename), Private (__variablename) -only to class, Protected (_variablename)
'''
word = "hello"
guess = "ll"
ind = 0
word1 = word.replace("l","L",1)
print(word1)
for i in range(word.count(guess)):
ind = word.find(guess,ind)
print(ind)
ind=ind+1

word3 = "How are you doing"
l1 = word3.split("o")
print(l1)
word4 = "o".join(l1)
print(word4)

#Strings
word = "hEllo".lower()
print(word)
display_text = "* "*len(word)
print(display_text)
while True:
guess = input("Guess the character: ")
guess = guess[0].lower()

if guess.isalpha():
if guess in word:
ind = 0
for i in range(word.count(guess)):
ind = word.find(guess, ind)
#now time to reveal
#0 - 0, 1-2, 2-4
display_text = display_text[:ind*2] + guess+display_text[ind*2+1:]
ind = ind + 1
print(display_text)

if "*" not in display_text:
print("Congratulations!")
break
else:
print("Given character is not in the original word")
else:
print("Invalid character")

class Book:
book_count = 0
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
Book.book_count+=1

def getbook(self):
print(f"{self.title} is written by {self.author}")

@classmethod
def getBookCount(cls):
print("Total books available: ",cls.book_count)

book1 = Book('Swapnil Saurav','Learn and Practice Python', 9012)
book1.getbook()
book1.getBookCount()
#Inheritance
class School:
def __init__(self,schoolname):
self.schoolname = schoolname

def _displaydetails(self):
print("School name is ",self.schoolname)

class Student (School):
def __init__(self,stname, schoolname):
School.__init__(self,schoolname)
self.stname = stname

def displaydetails1(self):
print("Student name is ",self.stname)
def displaydetails1(self,name):
print("Student name is ",self.stname)

def displaydetails1(self,name,age):
print("Student name is ", self.stname)

class Teacher (School):
def __init__(self,tname):
self.tname = tname

def displaydetails(self):
print("Teacher name is ",self.tname)

sc1 =School("ABC International School")
st1 = Student("Sachin Tendulkar","XYZ International School")
t1 = Teacher("Kapil Dev")
sc1._displaydetails()
st1.displaydetails1()
t1.displaydetails()

'''
Public
Protected _var (single underscore)
Private __var (double underscore)
'''
#1. declare a class calc
#2. initialize functon to read 3 variables
#3. create another method to calculate: sum. multiply minus
#4. Display the result using another method
#5. Create another class to perform arithematic operators
## that you have learnt in Python: + - * / % ** //

class Calc:
def __init__(self,a,b,c):
self.n1 = a
self.n2 = b
self.n3 = c
self.add = "Addition not yet done"
self.mul = "Multiplication not yet done"
self.min = "Difference not yet done"

def calc(self):
self.add = self.n1 + self.n2
self.mul = self.n1 * self.n2
self.min = self.n1 - self.n2

def display(self):
print("Sum = ",self.add)
print("Multiplication = ",self.mul)
print("Difference = ",self.min)

class Arithmatic(Calc):
def __init__(self,a,b,c):
Calc.__init__(self,a,b,c)
self.n1 = a
self.n2 = b
self.n3 = c
self.div = "Division not yet done"
self.mod = "Modulus not yet done"
self.pow = "Power not yet done"
self.intdiv = "Integer Division not yet done"

def calc(self):
Calc.calc(self)
self.div = self.n1 / self.n2
self.mod = self.n1 % self.n2
self.pow = self.n1**self.n2
self.intdiv = self.n1 // self.n2

def display(self):
Calc.display(self)
print("Division = ",self.div)
print("Modulus = ",self.mod)
print("Power = ",self.pow)
print("Integer Division = ", self.intdiv)

c1 = Arithmatic(10,5,12)
c1.calc()
c1.display()

c2 = Calc(3,4,6)
c2.calc()
c2.display()

TYPES OF FUNCTION

 

def myfun1(a,b):
'''Example of Required Positional Argument'''
print(f"a is {a} and b is {b}")
sum = a + b
print("Sum: ",sum)
#return sum

def myfun2(a=16,b=6):
'''Example of Default Positional Argument'''
print(f"a is {a} and b is {b}")
sum = a + b
print("Sum: ",sum)
#return sum

def myfun3(a,*b,**c): #variable length arguments
print("a = ",a)
print("b = ", b) # * means tuple
print("c = ", c) # **- dictionary


myfun3(50,5,6,7,8,9,9,11,14,name="sachin",game ="Cricket")


#Keyword argument
n1,n2=14,26
print(myfun2(a=n2,b=n1))
result = myfun2(b=34)


n1,n2=14,26
print(myfun2(n1,n2))
result = myfun2(34)
#result*=2
print(result)

n1,n2=54,66
print(myfun1(n1,n2))
result = myfun1(34,76)
#result*=2
print(result)

#Types of functions based on input parameter:
## 1. Required positional arguments: YOu have to provide value and in same order (left to right)
## Default (positional) arguments
import os
print(os.name)
if os.name=="nt":
print("Its a Windows machine")
elif os.name=="posix":
print("its a Linux/Mac")
else:
print("Other OS")

print(os.getcwd())
#os.rmdir("Nov_2")
#os.rename("file1.txt", "file1dec.txt")
print("iterate in folder:")
from pathlib import Path
path_list = Path("C:\\Users\\Hp\\Poems\\")
for i in path_list.iterdir():
print(i)
os.mkdir("Test2")

fp= open(r"C:\Users\Hp\Poems\Poem1.txt","r") #r for read w for write a append
content = fp.read(200)
print(type(content))
print(content)
fp.seek(0)
content = fp.readline(500)
print(type(content))
print(content)

content = fp.readlines()
print(type(content))
print(content[4])
fp.close()
fp1 = open(r"C:\Users\Hp\Poems\testCopy\sample.txt","a")
if fp1.writable():
fp1.writelines(content)

fp1.close()
#Numpy
import numpy as np
x = range(16)
# range: 0 to upto 16 - 0...15
x = np.reshape(x,(4,4))
print(type(x))
print(x)
size = x.shape
print("Total rows = ",size[0])
print("Total columns = ",size[1])

#indexing
print(x[1,2])
print(x[3,1])
print(x[0,:])
print(x[:,0])
print(x[1:3,1:3])

#
x = np.zeros((3,3))
print(x)
x = np.ones((3,3))
print(x)
x = np.full((3,3),99)
print(x)

x = np.random.random((3,3))
print(x)

l1 = [[5,10,15],[9,10,11],[2,3,1]]
print(type(l1))
l1 = np.array(l1, dtype=np.int8)
print(l1)
print(type(l1))
l2 = np.array([[3,6,9],[7,14,21],[2,4,6]])
print(l2)

#addition
print(l1 + l2)
print(np.add(l2,l1))

print(l1 - l2)
print(np.subtract(l2,l1))

print(l1 / l2)
print(np.divide(l2,l1))

print("==========================")
print(l1,"\n",l2)
print(l1 @ l2)
print(np.matmul(l2,l1))

for i in l1.flat:
print(i)

x = np.identity(6)
print(x)
print("Printing l1:\n",l1)
print("Printing Transpose of l1:")
l1_t = np.transpose(l1)
print(l1_t)

l1_det = np.linalg.det(l1)
print("Determinant of L1 is ",l1_det)
l1_inv = np.linalg.inv(l1)
print("Inverse of L1 is ",l1_inv)

#Singular matrix have determinant zero so we cant find inverse of that matrix

# 2x-3y = 8
# 3x-4y = 12
# what is x & y?
# Numpy to solve linear algebra
# 2x +5y + 2z = -38
# 3x - 2y + 4z = 17
# -6x +y -7z = -12
import numpy as np
Coeff = [[2,5,2],[3,-2,4],[-6,1,-7]]
Coeff_mat = np.array(Coeff)
Coeff_det = np.linalg.det(Coeff_mat)
if Coeff_det ==0:
print("There are no possible solution for given equations")
else:
Const = [[-38],[17],[-12]]
Coeff_inv = np.linalg.inv(Coeff_mat)
sol = np.matmul(Coeff_inv,Const)
print("Solution is: \n",sol)
print(f"x={sol[0,0]}, y={sol[1,0]}, z={sol[2,0]}")
#SETS
set1 = {1,5,9,10,20}
print(type(set1))
set1.add(22)
print(set1)

set2 = set1 #deep copy - set2 and set1 will point to same location in memory
set3 = set1.copy() #shallow copy - create a duplicate copy
print("printing 1: ")
print("Set 1: ",set1)
print("Set 2: ",set2)
print("Set 3: ",set3)
set2.add(25)
set2.add(29)

print("printing 2: ")
print("Set 1: ",set1)
print("Set 2: ",set2)
print("Set 3: ",set3)
print("Set 1: ",id(set1))
print("Set 2: ",id(set2))
print("Set 3: ",id(set3))

#union, intersection, difference, symmetric difference
Set2 = {1, 20, 5, 22, 9, 10, 29, 25}
Set3 = {1, 20, 5, 22, 9, 10,31,35}
print(Set2.union(Set3))
print(Set2 | Set3)

print(Set2.intersection(Set3))
print(Set2 & Set3)

print(Set2.difference(Set3))
print(Set3 - Set2)

print(Set2.symmetric_difference(Set3))
print(Set2 ^ Set3)
print("Set 2: ",Set2)
print("Set 3: ",Set3)
print(Set2.symmetric_difference_update(Set3))
print("Set 2: ",Set2)
print("Set 3: ",Set3)

from datetime import datetime
currenttime = datetime.now()
print("Current time: ",currenttime)

n=10000
counter = 0
for i in range(n):
for j in range(n):
counter+=1
if counter*100 % (n*n)==0:
print(f"{counter*100//(n*n)}% Task Completed")

endtime = datetime.now()
print("Total time taken by the program is ",endtime-currenttime)

from datetime import datetime, timedelta
print("Current time: ",datetime.now())
print("Current date: ",datetime.now().strftime("%Y,%m-%d"))
print("Current year: ",datetime.now().year)
print("Current month: ",datetime.now().month)
print("Current day: ",datetime.now().day)
print("Current hour: ",datetime.now().hour)
print("Current minute: ",datetime.now().minute)
print("Current second: ",datetime.now().second)

import time
print("Current time: ",time.strftime("%Y,%m-%d"))
print("Total time: ",time.time())
print("Tomorrow's time: ",datetime.now()+timedelta(days=1))
from pytz import timezone
print("Current time in US Eastern is",datetime.now(timezone("US/Eastern")).strftime("%Y-%m-%d"))

# random numbers
import random
random.seed(100)
print("Random = ",random.random()) # randon no. between 0 & 1
print("Random = ",int(random.random()*1000))
print("Random Integer values: ",random.randint(500,9000))
choices = ["ONE","TWO","THREE","FOUR","FIVE","SIX"]
print("One value from the list: ",random.choice(choices))
random.shuffle(choices)
print("random shuffle: ",choices)

#MAP - works with List where you want to apply same calculation to all the numbers
distances = [1100,1900,4500,6500,3400,2900,5400]*500
dist_ft = 0 #3.1 *
from datetime import datetime

start=datetime.now()
dist_ft = list(map(lambda x:3.1*x,distances))
end=datetime.now()
print("Total time taken by MAP = ",end-start)

start=datetime.now()
dist_ft2 = []
for i in distances:
val = i*3.1
dist_ft2.append(val)
#print("Output using Loops = ",dist_ft2)
end=datetime.now()
print("Total time taken by LOOP = ",end-start)