Working with functions
Working with functions
Q.1 Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns the
amount converted to rupees. Create the function in both void and non-void forms.
Solution
return amount_in_rupees
Output
Q.2 Write a function to calculate volume of a box with appropriate default values for its
parameters. Your function should have the following input parameters :
Solution
Output
(i) a function that takes a number as argument and calculates cube for it. The function does not return a
value. If there is no value passed to the function in function call, the function should calculate cube of 2.
(ii) a function that takes two char arguments and returns True if both the arguments are equal otherwise
False.
Solution
cube = number ** 3
calculate_cube(3)calculate_cube()
char1 = 'a'char2 = 'b'print("Characters are equal:", check_equal_chars(char1,
char1))print("Characters are equal:", check_equal_chars(char1, char2))
Output
Cube of 3 is 27
Cube of 2 is 8
Q.4 Write a function that receives two numbers and generates a random number from that range.
Using this function, the main program should be able to print three numbers randomly.
Solution
import random
for i in range(3):
Output
Q.5 Write a function that receives two string arguments and checks whether they are same-length
strings (returns True in this case otherwise False).
Solution
Output
True
False
Q.6 Write a function namely nthRoot( ) that receives two parameters x and n and returns nth root
of x i.e., x^(1/n).
The default value of n is 2.
Solution
return x ** (1/n)
Output
Solution
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
Output
Random number: 10
Random number: 50
Q.8 Write a function that takes two numbers and returns the number that has minimum one's digit.
[For example, if numbers passed are 491 and 278, then the function will return 491 because it has got
minimum one's digit out of two given numbers (491's 1 is < 278's 8)].
Solution
ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
else:
return num2
Output
Q.9 Write a program that generates a series using a function which takes first and last values of
the series and then generates four terms that are equidistant e.g., if two numbers passed are 1
and 7 then function returns 1 3 5 7.
Solution
return series
Output
Solution
words = sentence.split()
new_sentence = []
new_word = ''
if char.lower() != letter.lower():
new_word += char
new_sentence.append(new_word)
def capwords_custom(sentence):
words = sentence.split()
capitalized_words = []
capitalized_word = word.capitalize()
capitalized_words.append(capitalized_word)
sentence = sentence.strip()
Output
Enter a letter: e
Q.2 Create a module lengthconversion.py that stores functions for various lengths conversion
e.g.,
It should also store constant values such as value of (mile in kilometers and vice versa).
Solution
#Functionsdef miletokm(miles):
def kmtomile(kilometers):
def inchestofeet(inches):
Output
Q.3 Create a module MassConversion.py that stores function for mass conversion e.g.,
1.kgtotonne() — to convert kg to tonnes
2. tonnetokg() — to convert tonne to kg 3. kgtopound() — to convert kg to pound
4. poundtokg() — to convert pound to kg
Solution
#Functionsdef kgtotonne(kg):
return kg * KG_TO_TONNE
def tonnetokg(tonne):
def kgtopound(kg):
return kg * KG_TO_POUND
def poundtokg(pound):
Output
Question 4
Conversion
├──Length
│ └──Lengthconversion.py
└──Mass
└──Massconversion. py
Make sure that above package meets the requirements of being a Python package. Also, you
should be able to import above package and/or its modules using import command.
Answer
1. The basic structure of above package includes packages's name i.e., Conversion and all modules
and subfolders.
2. Create the directory structure having folders with names of package and subpackages. In the
above package, we created two folders by names Length and Mass. Inside these folders, we
created Lengthconversion.py and MassConversion.py modules respectively.
3. Create __init__.py files in package and subpackage folders. We created an empty file and saved
it as "__init__.py" and then copy this empty __init__.py file to the package and subpackage
folders.
4. Associate it with python installation. Once we have our package directory ready, we can associate
it with Python by attaching it to Python's site-packages folder of current Python distribution in our
computer.
5. After copying our package folder in site-packages folder of our current Python installation, now it
has become a Python library so that now we can import its modules and use its functions.
Conversion/
├── __init__.py
├── Length/
│ ├── __init__.py
│ └── Lengthconversion.py
└── Mass/
├── __init__.py
└── MassConversion.py
RELATIONAL DATABASES
Assignments
Q.1 Summarize the major differences between a relation and a traditional file.
Answer
Allows for defining relationships between tables. No inherent support for relationships.
Offers flexibility in data storage and retrieval. Limited flexibility in data organisation.
Examples : MySQL, PostgreSQL Examples : Text files, CSV files, Excel spreadsheets
Q.2
(i)Define database.
Answer
(ii)Define SQL.
Answer
The Structured Query Language (SQL) is a language that enables us to create and operate on
relational databases (RDBMS), which are sets of related information stored in tables.
(iii)Define view.
Answer
A view is a (virtual) table that does not really exist in its own right but is instead derived from one
or more underlying base tables.
Answer
Duplication of data is known as data redundancy. Data redundancy in a database leads to
wasted storage and multiple copies of the same data. When these copies do not match with one
another, it leads to data inconsistency. Additionally, data redundancy can result in performance
degradation, security risks, and increased complexity.
Answer
Mismatched multiple copies of same data is known as data inconsistency. Data inconsistency
undermines database reliability, hindering decision-making, causing operational errors, and
increasing complexity.
Q.5
(i)Define tuple.
Answer
(ii)Define attribute.
Answer
(iii)Define domain.
Answer
A domain is a pool of values from which the actual values appearing in a given column are
drawn.
(iv)Define degree.
Answer
(v)Define cardinality.
Answer
Answer
A primary key is a set of one or more attributes that can uniquely identify tuples within the
relation.
(ii)Define foreign key.
Answer
A non-key attribute, whose values are derived from the primary key of some other table, is
known as foreign key in its current table.
Answer
MySQL is a freely available open source Relational Database Management System (RDBMS)
that uses Structured Query Language (SQL). MySQL provides us with a rich set of features that
support a secure environment for storing, maintaining and accessing data.
1. Speed — If the server hardware is optimal, MySQL runs very fast. It supports clustered
servers for demanding applications.
2. Ease of use — MySQL is a high performance, relatively simple database system. From
the beginning, MySQL has typically been configured, monitored and managed from the
command line. However, several MySQL graphical interfaces are also available.
3. Query Language Support — MySQL understands standards based SQL.
4. Portability — MySQL provides portability as it has been tested with a broad range of
different compilers and can work on many different platforms. It is fully multi-threaded
using kernel threads. It can easily use multiple CPUs if they are available.
5. Cost — MySQL is available free of cost. MySQL is a open source database.
6. Data Types — MySQL provides many data types to support different types of data. It also
supports fixed-length and variable-length records.
7. Security — MySQL offers a privilege and password system that is very flexible and
secure, and that allows host-based verification. Passwords are secure because all
password traffic is encrypted when we connect to a server.
8. Scalability and Limits — MySQL can handle large databases. Some real life MySQL
databases contain 50 million records, some have up to 60,000 tables and about
5,000,000,000 rows.
9. Connectivity — Clients can connect to MySQL Server using several protocols.
10. Localization — The server can provide error messages to clients in many languages.
11. Clients and Tools — MySQL provides several client and utility programs. These include
both command-line programs such as mysqldump and mysqladmin, and graphical
programs such as MySQL Administrator and MySQL Query Browser. MySQL Server has
built-in support for SQL statements to check, optimize and repair tables.
Q.8 What is the role of database server in database management system ? Give the key
features of MySQL.
Answer
A database server is the key to solving the problems of database management system
(information system). In general, a server must reliably manage a large amount of data in a
multi-user environment so that many users can concurrently access the same data. A database
server must also prevent unauthorized access and provide efficient solutions for failure recovery.
Answer
All programs and users accessing data within the MySQL database must utilize Structured
Query Language (SQL). MySQL is compatible with standard-based SQL, enabling it to
understand and process SQL commands efficiently. Additionally, the MySQL server incorporates
built-in support for executing SQL statements, allowing users to perform tasks such as checking,
optimizing, and repairing tables.
Answer
Answer
Answer
Examples of DDL commands are CREATE, ALTER, Examples of DML commands are INSERT,
DROP, GRANT, ANALYZE etc. UPDATE, DELETE, SELECT etc.
Q.13 Name some commands used to assign/revoke privileges from database users.
Answer
Commands used to assign/revoke privileges from database users are GRANT, REVOKE.
Answer
Table maintenance commands are ANALYZE TABLE, CHECK TABLE, REPAIR TABLE,
RESTORE TABLE.
Answer
TCL part of SQL includes commands for specifying the beginning and ending of transactions
along with commands to have control over transaction processing. Some examples of TCL
commands are COMMIT, ROLLBACK, SET TRANSACTION and SAVEPOINT. These
commands manage changes made by DML commands.
Q.1 What are different divisions of SQL and commands ? Give examples of commands in each division.
Answer
1. Data Definition Language (DDL) commands — CREATE, ALTER, DROP, TRUNCATE etc.
2. Data Manipulation Language (DML) commands — INSERT, UPDATE, DELETE etc.
3. Transaction Control Language (TCL) commands — COMMIT, ROLLBACK, SAVEPOINT etc.
4. Session Control Commands
5. System Control Commands
Q.2 What is foreign key ? How do you define a foreign key in your table ?
Answer
A non-key attribute, whose values are derived from the primary key of some other table, is known as
foreign key in its current table. Defining a foreign key in a table involves specifying the relationship
between the tables and setting up rules for data integrity. When two tables are related by a common
column or set of columns, the related column(s) in the parent table (or primary table) should be either
declared as a primary key or unique key. Meanwhile, the related column(s) in the child table (or related
table) should have a foreign key constraint referencing the primary or unique key in the parent table.
Q.3 How is FOREIGN KEY commands different from PRIMARY KEY command ?
Answer
The PRIMARY KEY is a set of one or more attributes that can uniquely identify tuples within the relation.
A primary key column cannot contain NULL values, and it must have unique values for each row. Only
one primary key constraint can exist per table. Conversely, the FOREIGN KEY command establishes a
relationship between two tables by linking a column or set of columns in one table to the primary key or a
unique key in another table. It enforces referential integrity, ensuring that values in the foreign key
column(s) of the referencing table match values in the referenced table's primary key or unique key
column(s). A foreign key can allow NULL values, indicating that the relationship is optional. Multiple
foreign key constraints can exist in a table, each referencing a different parent table.
Answer
FOREIGN KEY commands establish relationships between tables by linking columns in one table to the
PRIMARY KEY or a unique key in another table. This linkage ensures referential integrity, meaning that
values in the FOREIGN KEY column(s) of the referencing table must match values in the PRIMARY KEY
or unique key column(s) of the referenced table. Therefore, FOREIGN KEY commands are directly
related to PRIMARY KEY commands as they rely on the unique identification provided by PRIMARY KEY
constraints in other tables.
Q.5 How do you enforce business rules on a database ?
Answer
Database constraints enforce business rules on a database. These include PRIMARY KEY for unique
identifiers, FOREIGN KEY for maintaining relationships between tables, UNIQUE for ensuring
uniqueness, CHECK constraint limit values that can be inserted into a column of a table, and defau lt
constraints are utilized to specify a default value for a column when no value is explicitly provided during
an insert operation.
Q.6 What are table constraints ? What are column constraints ? How are these two different ?
Answer
Table constraints are rules or conditions applied to an entire table in a database. They are defined when
creating or altering a table's schema.
Column constraints are rules or conditions applied to individual columns within a database table. They
are specified at the column level when creating or altering a table's schema.
The difference between the two is that column constraints apply only to individual columns, whereas
table constraints apply to groups of one or more columns.
Q.7 What is default value ? How do you define it ? What is the default value of column for which
no default value is define ?
Answer
A default value is a predefined value assigned to a column in a database table. It can be specified using
the DEFAULT clause when defining the table's schema. If no default value is defined for a column, and a
new row is inserted into the table without providing a value for that column, the column's default value will
be NULL, unless the column is defined with a NOT NULL constraint. In such cases, an error will occur if a
value is not provided.
Answer
The syntax is : DROP TABLE table_name;. The syntax is : DROP DATABASE database_name;.
Answer
Answer
INSERT INTO PendingSELECT * FROM AccountsWHERE amt_outstanding > 10000;
Answer
Table employee
Output
To view all the details (all columns and rows) of the "employee" table the below query is executed :
+----+------------+-----------+----------+--------+
+----+------------+-----------+----------+--------+
+----+------------+-----------+----------+--------+
Q.3 Give commission of Rs.500 to all employees who joined in year 1982 (table Empl).
Answer
Table: Empl
MAHADE
8566 MANAGER 8839 1991-04-02 2985 NULL 20
VAN
KULDEE
8844 SALESMAN 8698 1991-09-08 1500 0 30
P
SHIAVN
8882 MANAGER 8839 1991-06-09 2450 NULL 10
SH
Explanation
Since there are no employees who joined in the year 1982 according to the data provided in the "Empl"
table, executing the given SQL query will result in no changes to the "COMM" column.
Q.4 Allocate the department situated in BOSTON to employee with employee number 7500
(tables EMPL, Dept)
Answer
UPDATE EMPLSET DEPTNO = (
SELECT DEPTNO
FROM Dept
Write a query to delete all those records from table Orders whose complete payment has been
made.
Answer
DELETE FROM Orders WHERE OrdNo IN (
SELECT Payment.OrdNo
FROM Payment
SHOW TABLES ;
Q.7 Write Query statements for following transaction : (Consider tables of question 12)
Answer
SELECT ProdNo#
FROM Orders
Q.8 Modify table Empl, add another column called Grade of VARCHAR type, size 1 into it.
Answer
Answer
UPDATE EmplSET Grade = '1'WHERE Sal >= 700 AND Sal <= 1500;
UPDATE EmplSET Grade = '2'WHERE Sal > 1500 AND Sal <= 2200;
UPDATE EmplSET Grade = '3'WHERE Sal > 2200 AND Sal <= 3000;
UPDATE EmplSET Grade = '4'WHERE Sal > 3000;
Q.10 Add a constraint (NN-Grade) in table Empl that declares column Grade not null.
Answer
Q.11 Insert a record of your choice in table Empl. Make sure not to enter Grade.
Answer
INSERT INTO Empl (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)VALUES (12345,
'DEEPAK', 'CLERK', 8902, '1990-12-18', 8000, 200, 10);
Answer
Answer
Q.14 Create the table Department table based on the following table instance chart.
ID NUMBER(8),
Name VARCHAR(25));
Q.15 Populate the table Department with data from table dept. Including only required columns.
Answer
Q.16 Create the table Employee based on the following table instance chart.
Column Name Data Type Length
ID NUMBER 8
First_Name VARCHAR 25
Last_Name VARCHAR 25
Dept_ID NUMBER 8
Answer
ID NUMBER(8),
First_Name VARCHAR(25),
Last_Name VARCHAR(25),
Dept_ID NUMBER(8)
);
Answer
Cust_ID NUMBER 7
Cust_Name VARCHAR 30
Cust_Address1 VARCHAR 20
Cust_Address2 VARCHAR 30
Pincode NUMBER 6
Cust_Phone VARCHAR 10
Answer
Cust_ID NUMBER(7),
Cust_Name VARCHAR(30),
Cust_Address1 VARCHAR(20),
Cust_Address2 VARCHAR(30),
Pincode NUMBER(6),
Cust_Phone VARCHAR(10)
);
Q.19 Add one column Email of data type VARCHAR and size 30 to the table Customer.
Answer
Answer
Answer
Answer
Length 2 20
Answer
Fk Table Department
Fk Column Dept_ID
Length 6 20 30 10 9, 2 2
Answer
EmpAddress VARCHAR(30),
EmpPhone VARCHAR(10),
DeptID VARCHAR(2),
Answer
DESCRIBE <TABLENAME> ;