0% found this document useful (0 votes)
13 views

CS1.1.1

Uploaded by

Vivek Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CS1.1.1

Uploaded by

Vivek Singh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

• Database connectivity: - Database connectivity refers to connection and communication between an application and a database system.

• Mysql.connector:- Library or package to connect from python to MySQL.


• Command to install connectivity package: - pip install mysql-connector-python
• Command to import connector: - import mysql.connector
• Steps for python MySQL connectivity:-1. Install Python, 2. Install MySQL, 3. Open Command prompt, 4. Switch on internet
connection, 5. Type pip install mysql-connector-python and execute, 6. Open python IDLE, 7. import mysql.connector
• Steps for Creating Database Connectivity Applications :-There are mainly seven steps that must be followed in order to create a database
connectivity application. Step 1 :- Start Python., Step 2 :- Import the packages required for database programming., Step 3 :- Open a
connection to database.,Step 4 :- Create a cursor instance.,Step 5 :- Execute a query.,Step 6 :- Extract data from result set.,Step
7 :- Clean up the environment.
•Import mysql.connector Package :-import mysql.connector, import mysql.connector as sqlcon
•Open a Connection to MySQL Database :-The connect() function of mysql.connector establishes connection to a MySQL database and
requires four parameters, which are ;, <Connection-Object>= mysql.connector.connect (host = <host-name>, user = <username>,
passwd = <password> [, database = <database>]), user is the username on MySQL, password is the password of the user, host-
name the database server hostname or IP address, database is optional which provides the database name of a MySQL database.
•Create a Cursor Instance :-A Database Cursor is a special control structure that facilitates the row by row processing of records in the
resultset, i.e., the set of records retrieved as per query., <cursorobject>=, <connectionobject>.cursor(), cursor = mycon.cursor()
•Execute SQL Query :<cursorobject>.execute(<sql query string>),The above code will execute the given SQL query and store the
retrieved records (i.e., the resultset) in the cursor object (namely cursor) which you can then use in your programs/scripts as required.
•RESULT SETThe result set refers to a logical set of records that are fetched from the database by executing an SQL query and made
available to the application program.
(i) <data> = <cursor>.fetchall(). It will return all the records retrieved as per query in a tuple form (i.e., now <data> will be a tuple.)
(ii) <data> = <cursor>.fetchone(). It will return one record from the resultset as a tuple or a list. First time it will return the first record, next
time it will fetch the next record and so on.
(iii) <data> = <cursor>.fetchmany(<n>). This method accepts number of records to fetch and returns a tuple where each record itself is a
tuple. If there are not more records then it returns an empty tuple.
(iv) <variable> = <coursor.rowcount. The rowcount is a property of cursor object that returns the number of rows retrieved from the cursor
so far. Following examples will make it more clear.
•Clean Up the Environment :After you are through all the processing, in this final step, you need to close the connection established.
<connectionobject>.close(), mycon.close()
•Connecting with MySQL Database using pymysql :<connection> = pymysql.connect("localhost", <username>,
<password>, <databasename>), commit – MySQLConnection.commit() method sends a COMMIT statement to the MySQL server,
committing the current transaction.
•CREATE DATABASEimport mysql.connector as my, mydb = my.connect(host = "localhost", user = "root", password = "123456"),
mycon = mydb.cursor(), mycon.execute("CREATE DATABSE Pathwalla")
•SHOW DATABASEimport mysql.connector as my, mydb = my.connect(host = "localhost", user = "root", password = "123456"),
mycon = mydb.cursor(), mycon.execute("SHOW DATABSES"), for i in mycon:,  print (i)
•CREATE TABLEimport mysql.connector as my, mydb = my.connect(host = "localhost", user = "root", password = "123456", database =
"Pathwalla"), mycon = mydb.cursor(), mycon.execute("CREATE TABLE student (Name char (25), roll int(10), class int(10))"),
mydb.commit(), mydb.close()
•SHOW TABLEimport mysql.connector as my, mydb = my.connect(host = "localhost", user = "root", password = "123456", database =
"Pathwalla"), mycon = mydb.cursor(), mycon.execute("SHOW TABLES"), for i in mycon:, print (i)
•DESCRIBE TABLEimport mysql.connector as my, mydb = my.connect(host = "localhost", user = "root", password = "123456", database
= "Pathwalla"),mycon = mydb.cursor(),mycon.execute("DESC student"),data = mycon.fetchall(),for i in data:,print (i)
•SELECT QUERYimport mysql.connector as my, mydb = my.connect(host = "localhost", user = "root", password = "123456", database =
"Pathwalla"), mycon = mydb.cursor(), mycon.execute("SELECT * FROM student"),data = mycon.fetchall(),for i in data:, print (i)
•WHERE CLAUSEimport mysql.connector as my,mydb = my.connect(host = "localhost", user = "root", password = "123456", database =
"Pathwalla"),mycon = mydb.cursor(),mycon.execute("SELECT * FROM student where Class = 12"),data = mycon.fetchall(),for i in
data:,print (i)
•UPDATE COMMANDimport mysql.connector as my,mydb = my.connect(host = "localhost", user = "root", password = "123456",
database = "Pathwalla"),mycon = mydb.cursor(),mycon.execute("UPDATE student SET roll = 5 WHERE Name =
'Ram'"),mydb.commit(),mydb.close()
•DELETE COMMANDimport mysql.connector as my,mydb = my.connect(host = "localhost", user = "root", password = "123456",
database = "Pathwalla"),mycon = mydb.cursor(),mycon.execute("DELET FROM student WHERE roll =
26"),mydb.commit(),mydb.close()
•DROP COMMANDimport mysql.connector as my,mydb = my.connect(host = "localhost", user = "root", password = "123456",
database = "Pathwalla"),mycon = mydb.cursor(),mycon.execute("DROP TABLE student"),mydb.commit(),mydb.close()
•ALTER COMMANDimport mysql.connector as my,mydb = my.connect(host = "localhost", user = "root", password = "123456",
database = "Pathwalla"),mycon = mydb.cursor(),mycon.execute("ALTER TABLE student ADD Marks int
(10)"),mydb.commit(),mydb.close()

Text Files A file whose contents can be viewed using a text editor is called a text file. A text file is simply a sequence of ASCII or Unicode
characters. Python programs, contents written in text editors are some of the example of text files.
Binary FilesA binary file stores the data in the same way as as stored in the memory. The .exe files, mp3 file, image files, word documents
are some of the examples of binary files. We can’t read a binary file using a text editor.
Opening and Closing Files : To perform file operation, it must be opened first then after reading, writing, editing operation can be
performed. To create any new file then too it must be opened. On opening of any file, a file relevant structure is created in memory as well
as memory space is created to store contents. Once we are done working with the file, we should close the file. Closing a file releases
valuable system resource. In case we forgot to close the file, Python automatically close the file when program ends or file object is no
longer referenced in the program. However, if our program is large and we are reading or writing multiple files that can take significant
amount of resource on the system. If we keep opening new files carelessly, we could run out of resources. So be a good programmer, close
the file as soon as all task are done with it.
Mode & Description 1. r - reading only. Sets file pointer at beginning of the file. This is the default mode. 2 rb – same as r mode but
with binary file., 3. r+ - both reading and writing. The file pointer placed at the beginning of the file., 4. rb+ - same as r+ mode but with
binary file., 5. w - writing only. Overwrites the file if the file exists. If not, creates a new file for writing., 6. wb – same as w mode but
with binary file., 7. w+ - both writing and reading. Overwrites. If no file exists, creates a new file for R & W., 8. wb+ - same as w+ mode
but with binary file., 9. a -for appending. Move file pointer at end of the file.Creates new file for writing,if not exist., 10. ab – same as a
but with binary file
open() Function: The key function for working with files in Python is the open() function. The open() function takes two parameters;
filename, and mode.
Python Delete File Delete a File To delete a file, you must import the OS module, and run its os.remove() function
CSV FILE (Comma separated value)is a file format for data storage which looks like a text file. The information is organized with one
record on each line and each field is separated by comma.
CSV File Characteristics : • One line for each record • Comma separated fields • Space-characters adjacent to commas are ignored •
Fields with in-built commas are separated by double quote characters.
When Use CSV? • When data has a strict tabular structure • To transfer large database between programs • To import and export data
to office applications, Qedoc modules • To store, manage and modify shopping cart catalogue
CSV Advantages • CSV is faster to handle • CSV is smaller in size • CSV is easy to generate • CSV is human readable and easy to edit
manually • CSV is simple to implement and parse • CSV is processed by almost all existing applications
CSV Disadvantages • No standard way to represent binary data • There is no distinction between text and numeric values • Poor support
of special characters and control characters • CSV allows to move most basic data only. Complex configurations cannot be imported and
exported this way • Problems with importing CSV into SQL (no distinction between NULL and quotes)
Write / Read CSV FILE Writing and reading operation from text file is very easy. First of all, we have to import csv module for file
operation/method call. For writing, we open file in ‘w’ writing mode using open () method which create newFile like object. Through
csv.writer() method ,we create writer object to call writerow() method to write objects. Similarly for reading, we open the file in ‘r’ mode
and create newFile like object,further we create newfilereader object using csv.reader() method to read each row of the file. Three file
opening modes are there ‘w’,’r’,’a’. ‘a’ for append After file operation close, opened file using close () method
Aggregate Functions and GroupingMAX, MIN, AVG, SUM, COUNT: Perform calculations on data….., GROUP BY: Groups data by one or
more columns….., HAVING: Filters grouped data.
Joins Cartesian Product: Combines every row from one table with every row from another….,Equi-Join: Combines rows based on a
specified equality condition…., Natural Join: Joins tables using columns with the same name.

Function Description
list.append() Add an Item at end of a list…….., list.extend() Add multiple Items at end of a list………, list.insert() insert an Item at a
defined index………….., list.remove() remove an Item from a list del…….., list[index] Delete an Item from a list………., list.clear()
empty all the list………, list.pop() Remove an Item at a defined index…………….., list.index() Return index of first matched item………..,
list.sort() Sort the items of a list in ascending or descending order………, list.reverse() Reverse the items of a list……….,len(list) Return
total length of the list…………,max(list) Return item with maximum value in the list………, min(list) Return item with min value in the
list……….., list(seq) Converts a tuple, string, set, dictionary into list.
Stack: A stack is a linear data structure in which all the insertion and deletion of data / values are done at one end only. It is type of
linear data structure. It follows LIFO(Last In First Out) property. Insertion / Deletion in stack can only be done from top. Insertion in
stack is also known as a PUSH operation. Deletion from stack is also known as POP operation in stack.
Applications of Stack: • Expression Evaluation:- It is used to evaluate prefix, postfix and infix expressions. • Expression Conversion:- It can
be used to convert one form of expression(prefix,postfix or infix) to one another. • Syntax Parsing:- Many compilers use a stack for parsing
the syntax of expressions. • Backtracking:- It can be used for back traversal of steps in a problem solution. • Parenthesis Checking:- Stack is
used to check the proper opening and closing of parenthesis. • String Reversal:- It can be used to reverse a string. • Function Call:- Stack is
used to keep information about the active functions or subroutines.
Using List as Stack in Python: The concept of Stack implementation is easy in Python , because it support inbuilt functions (append() and
pop()) for stack implementation.By Using these functions make the code short and simple forstack implementation. To add an item to the
top of the list, i.e., to push an item, we use append() function and to pop out an element we use pop() function. These functions work quiet
efficiently and fast in end operations.
Queue: Queue is a data structures that is based on First In First Out (FIFO) stretagy ,i.e. the first element that is added to the queue is the
first one to be removed. • Queue followsthe FIFO (First - In - First Out) structure. • According to its FIFO structure, element inserted first will
also be removed first. • In a queue, one end is always used to insert data (enqueue) and the other is used to delete data (dequeue),
because queue is open at both its ends.
Applications of Queue: Synchronization :- When data are transferred to asynch devices then it is used to synchronized. Scheduling :-
When a resource is shared among multiple consumers. Searching :- Like breadth first search in graph theory. Interrupt handling :- Handling
of multiple interrupt as the order they arrive.
Using List as Queue in Python: The concept of Queue implementation is easy in Python , because it support inbuilt functions (insert() and
pop()) for queue implementation.By Using these functions make the code short and simple for queue implementation. To add an item at
front of the queue, i.e., to enqueue an item, we use insert() function and to dequeue an element we use pop() function. These functions
work quiet efficiently and fast in end operations.
Using Module It is a file which contains python functions/global variables/clases etc. It is just .py file which has python executable code /
statement.
Using Package  It is namespace that contains multiple package or modules. It is a directory which contains a special file_init_.py
Using Library It is a collection of various packages. Conceptually,There is no difference between package and python library.In Python, a
library is used loosely to describe a collection of the core modules. ‘standard library‘ of Python language comes bundled with the core
Python distribution are collection of exact syntax, token and semantics of the Python language . The python standard library lists down
approx more than 200 such core modules that form the core of Python. “Additional libraries” refer to those optional componentsthat are
commonly included in Python distributions. The Python installers automatically adds the standard library and some additional libraries.
The additional library is generally provided as a collection of packages. To use such additional library we have to use packaging tools like
easyinstall or pip to install such additional libraries

Using Framework Framework is like a collection of various libraries which architects some more component.
A database is a structured collection of data that is organized and stored in a way that allows for efficient retrieval, management, and
manipulation of information. It serves as a central repository for storing and managing data, making it a fundamental component of
modern information systems. Here, we will delve into the basics of database concepts and understand why they are essential.
Data Organization: Databases provide a structured way to organize data. Instead of storing information in isolated files or spreadsheets,
databases allow for the systematic arrangement of data into tables, rows, and columns. This organization simplifies data management and
retrieval.
Data Integrity: Maintaining data accuracy and consistency is crucial for any organization. Databases employ mechanisms such as
constraints, validation rules, and data relationships to ensure data integrity. This reduces the risk of errors and data inconsistencies.
Data Security:Databases offer security features to control access to data. User authentication, authorization, and encryption help protect
sensitive information from unauthorized access or tampering.
Efficient Data Retrieval: With databases, you can quickly retrieve specific pieces of information using structured query languages (SQL).
This efficient data retrieval is vital for applications like customer relationship management (CRM), e-commerce, and more.
Concurrency Control: In multi-user environments, where multiple users access and modify data simultaneously, databases employ
concurrency control mechanisms to prevent data conflicts and ensure data consistency.
Scalability: As an organization grows, so does its data. Databases provide scalability options, allowing organizations to handle increasing
amounts of data efficiently by adding more hardware resources or optimizing database design.
Data Analysis: Databases are crucial for data analysis and business intelligence. They enable the storage of historical data, which can be
analyzed to make informed decisions, track trends, and forecast future performance.
Data Backup and Recovery: Databases offer backup and recovery features to safeguard against data loss due to hardware failures,
accidents, or disasters. Regular backups ensure that data can be restored in case of emergencies.
Data Redundancy Reduction: Databases minimize data redundancy by storing data in normalized tables. This reduces storage
requirements and ensures consistency by updating data in one place.
Support for Complex Data Types: Modern databases can handle complex data types such as images, videos, and JSON documents,
making them versatile for various applications.
Components of the Relational Data Model
Relation:A relation is a table in the relational data model.It consists of rows and columns.Each row represents a record or tuple of an
individual, and each column represents an attribute or field holding the same property.
Attribute:An attribute is a characteristic or property of an entity represented as a column in a relation.For example, in a “Customers”
relation, attributes might include “CustomerID,” “Name,” “Email,” and “Phone.”
Tuple:A tuple is a row in a relation.It represents a single instance or record of data.Each tuple contains values for each attribute defined
in the relation.
Domain:A domain specifies the set of allowable values for a particular attribute.For instance, the domain of the “Age” attribute might be
defined as integers between 0 and 100.It can be termed as range.
Degree:The degree of a relation is the number of attributes it contains.It indicates the complexity and structure of the relation.
Cardinality:Cardinality refers to the number of tuples in a relation.It signifies the size of the data set represented by the relation.
Keys in the Relational Data Model
Candidate Key:A candidate key is a minimal set of attributes that can uniquely identify each record / tuple in a relation / table.There can
be multiple candidate keys in a relation.One of them will be chosen as the primary key.
.
Primary Key:The primary key is a specific candidate key chosen to uniquely identify each record / tuple.It must be unique and cannot
contain NULL values.It is used for data retrieval and integrity enforcement.
Alternate Key:Alternate keys are candidate keys that are not selected as the primary key.They can still be used for uniqueness constraints
or as reference keys in other relations.
Foreign Key:A foreign key is an attribute or set of attributes in one relation that refers to the primary key of another relation.It
establishes relationships between tables and enforces referential integrity.Foreign keys ensure that values in the referencing table exist in
the referenced table.
SQL (Structured Query Language) is a powerful and standardized language used for managing and manipulating relational databases. It
provides a structured and efficient way to interact with databases, enabling tasks such as data retrieval, insertion, deletion, and schema
definition. In this set of notes, we will explore various aspects of SQL.
Data Definition Language (DDL) and Data Manipulation Language (DML)
DDL deals with defining the database structure, including creating, altering, and deleting tables and databases.
DML focuses on manipulating data within the database, such as inserting, updating, and deleting records.
Data TypesSQL supports various data types to specify the kind of data that can be stored in each column of a table:CHAR(n): Fixed-
length character strings with a specified maximum length ‘n’.,., VARCHAR(n): Variable-length character strings with a maximum length of
‘n’. INT: Integer data type for whole numbers.,, FLOAT: Floating-point number data type for decimals.,,, DATE: Date data type for
storing dates.
ConstraintsSQL allows you to apply constraints to columns for data integrity:NOT NULL: Ensures that a column cannot contain NULL
values…, UNIQUE: Enforces unique values within a column
Database OperationsCREATE DATABASE: Creates a new database…, USE DATABASE: Specifies the database to be used….., SHOW
DATABASES: Lists all available databases….., DROP DATABASE: Deletes a database….., SHOW TABLES: Displays a list of tables in the
current database……, CREATE TABLE: Creates a new table with specified columns and data types……, DESCRIBE TABLE: Provides
information about the structure of a table….., ALTER TABLE: Modifies the structure of an existing table, including adding or removing
columns and altering primary keys………, DROP TABLE: Deletes a table and its data.
Data ManipulationINSERT: Adds new records into a table…, DELETE: Removes records from a table….., SELECT: Retrieves data from
one or more tables……,Operators: Mathematical (+, -, *, /), relational (=, <>, >, <, >=, <=), and logical (AND, OR, NOT)
operators……..,Aliasing: Renaming columns or tables for readability……,DISTINCT: Retrieves unique values from a
column……..,WHERE: Filters rows based on a specified condition……, IN: Checks for a value within a list….,BETWEEN: Filters rows
within a specified range……ORDER BY: Sorts query results……NULL: Represents missing or unknown data…….IS NULL: Tests for NULL
values……..,IS NOT NULL: Tests for non-NULL values…….,LIKE: Searches for a specified pattern…..,UPDATE: Modifies existing
data……,DELETE: Removes data from a table
Local Environment  First check-in the local namespace or local function or local environment, found then use it, otherwise move to
Enclosing environment.
Enclosing Evironment If not found in Local, then it checks inside the enclosing namespace, if found then ok, otherwise moves to the
global namespace.
Global Environment If not found in Enclosing, it checks inside the global namespace, if found then ok, otherwise move to the Built-in
namespace.
Built-in Environment If not found in Global, it checks inside the Built-in namespace, if found then ok, otherwise raises an Error message –
NameError: name ‘varName’ is not defined.
Local ScopeA variable that is defined in the function called Local Variable and it has local scope.
LifetimeThe time for which a variable remains in memory is called Lifetime of Variable. It depends on the scope of the variable.

TOKENS IN PYTHONThe smallest individual unit in a program is called a token.


TYPES OF TOKEN (i) Keyword (ii) Identifiers (iii) Literals (iv) Operators & (v) Punctuators
Keyword The word has a special meaning in a programming language. If, else, while, for, or etc
Identifiers Names that are given to different parts of programs. Variable, Function, Class, etc.
Literals Data items that have a fixed value. Several types of literal in Python. (a) String (b) Numeric (c) Boolean (d) None
Operators Triggers some computation or action when applied to the variables. +, -, / .
Punctuators Symbols that are used to organize sentence, structures and expressions. ‘ “ # \ ( ) { } @ , : ; ` =, etc
VARIABLES AND ASSIGNMENTS A Variable is a named memory location, used for storing and manipulating values.
DYNAMIC TYPING A variable pointing to a value of a certain type can be made to point to a value/object of a different type. This is called
Dynamic Typing.
Integers Two types of integers in Python a) Integer (signed) – number having only integer, either positive or negative b)
Booleans – represent truth values False and True. Boolean values False and True behave like values 0 and 1, respectively.
Floating Point Numbers Is used to store numbers with a fraction part. They can be represented in scientific notation. Also called real
numbers.
Complex NumbersPython allows to store the complex number. Complex numbers are pairs of real and imaginary numbers. They can
store in the form of ‘a+bj . Both real and imag are internally represented as float value.
Sequence Data Types Sequence Data Types is an ordered collection of items, indexed by integers (both +ve or –ve). Three types of
sequence are –
StringsThe string is a combination of letters, numbers, and special symbols. In Python 3.x string is a sequence of Pure Unicode
characters. Unicode is a system, designed to represent every character from every language. A string is a sequence of characters and each
character can be individually accessed using its index position i.e. forward (0,1, 2, …) and backward (-1, -2, -3, .. …)
Lists The list is a set of comma-separated values of any datatype inside the square brackets. [ ]
Tuples A Tuple is a set of comma-separated values of any data type inside the parentheses ( )
Dictionary A dictionary is a comma-separated key-value pairs within { } and accessed using keys.No two keys can be the same .
Mutable and Immutable Data Types
Immutable Types Immutable types are those that can never change their value in place.The following are immutable: integers, floating
point numbers, Boolean, strings, tuples. In immutable types, the variable names are stored as a reference to a value object, each time
when we change the value, the variable’s reference memory address changes.
Mutable Types The Mutable types are those whose values can be changed in place. The following are mutable : lists, dictionaries, and
sets
ExpressionIn Python, An expression is a valid combination of operators, literals, and variables.There are three types of Expression in
Python, These are-
•Arithmetic Expressions:- combination of integers, floating-point numbers, complex numbers, and arithmetic operators. Example; 2+9,
9.2/3
•Relational Expression :- combination of literals and/or variables of any valid type and relational operators . Example; x > y, 5 < 8, z == y
•Logical Expression:- combination of literals, variables and logical operators. Example; t and q, p or g
•String Expression :- combination of string literals and string operators ( + -> concatenate, and * -> replicate).
Global Statement In Python, global statement allows us to use the same global variable inside the function. It does not allow functions to
create another variable of the same name. It means, listed identifiers are part of global namespace or global environment. Python uses
LEGB namespace rule to search the identifier variable. global <variable name>
A file is a sequence of bytes on the disk/permanent storage where a group of related data is stored. File is created for permanent storage
of data. In programming, Sometimes, it is not enough to only display the data on the console. Those data are to be retrieved later on, then
the concept of file handling comes. It is impossible to recover the programmatically generated data again and again. However, if we need to
do so, we may store it onto the file system which is not volatile and can be accessed every time. Here, comes the need of file handling in
Python. File handling in Python enables us to create, update, read, and delete the files stored on the file system through our python
program. The following operations can be performed on a file.

FunctionsPython provides the features to divide a large program into different smaller modules, called Functions. A Function is a group of
statements i.e. subprogram, that exists within a program for the purpose of performing specific tasks, and returns values/results whenever
it is required.Functions can take some data as input, process upon according to the instructions, and give some output at the end. Example
– max( ), min( ), sum( ), type(), etc.
Types of FunctionsIn Python, Functions can be categorized into three categoriesBuilt-in functions Functions defined in
Modules User-defined Functions
(a) Built-in FunctionsBuilt-in Functions are the predefined functions that are already available in Python. These functions are always
available in the standard library, no need to import any module for them.
Most frequently used Built-in Functions 1.int( ) – to convert into an integer. 2.float ( ) – to convert into float. 3.bool ( ) – to
convert into Boolean. 4.str ( ) – to convert into a string. 5.list ( ) – to convert a sequence into a list. 6.tuple( ) – to convert
a sequence into a tuple. 7.dict( ) – to convert sequences into the dictionary. 8.input( ) – to input value as a string. 9.eval(
) – to evaluate strings in the form of expression. 10.print( ) – to print/show output. 11.range( ) – to define a series of
numbers, useful for a loop. 12.max( ) – to find the maximum numbers. 13.min ( ) – to find the minimum numbers.
14.sum( ) – to sum two numbers or a list or tuple. 15.abs( ) – to find the absolute value (i.e. positive number) of numbers.
16.round (n, p ) – rounds a given floating point number to the specified number of digits and returns the result. 17.len( ) –
returns the length of the sequence. 18.chr( ) – returns the equivalent ASCII character of the given number. 19.ord( ) – returns
the ordinal value (ASCII number) of the given character. 20.type ( ) – returns the data type of data or variable. 20.id( ) – returns
the memory reference of value or variable.
(b) Functions defined in ModuleThese functions are pre-defined in particular modules and can only be used when the corresponding
module is imported.For example, 1.randint() function of the random module. 2.pow() function of the math module,
3.mean() module of the statistics module, 4.dump() function of the pickle module, 5.reader() function of csv module,
6.connect() function of mysql.connector module.
Calling / Invoking a FunctionA function definition defines user-defined functions. The function definition does not execute the function
body; this gets executed only when the function is called or invoked.Calling of function means, invoking or accessing or using the function.
To execute a function, invoke a function by its name and parameters inside the parenthesis (), if required. Syntax:
1.Function_Name( ) 2.Function_Name (arguments or parameters) 3.Res = Function_Name( ) 4.Res =
Function_Name( arguments / parameters)
Arguments: Values being passed by function call statement, are called arguments. Also called actual parameter or actual argument
Parameters: Values being received by function definition statement, are called parameters. Also called formal parameter and formal
argument.
Positional Arguments When the function call statement must match the number and order of arguments defined in the function
definition, such types of arguments are called Positional Arguments / Required Arguments / Mandatory Arguments.The process of
matching arguments is called Positional Argument Matching.
Default ArgumentsPython allows us to assign default values(s) to a function’s parameter(s) which becomes useful when matching
arguments is not passed in the function call statement.
Keyword (Named) ArgumentThe default arguments allow to specify the default value for the parameters, but it does not allow to pass
the value by changing order i.e. arguments always passed in the same order. Keyword arguments are the named arguments with assigned
values being passed in the function call statement. Keyword argument allows us to write any argument in any order with the help of an
argument name. Using keyword arguments, we can pass argument values by keyword i.e. by parameter name.
Variable length argumentsPython allows us to pass variable number of arguments to a function, this is called Variable length
argument.Variable length arguments are declared with * (asterisk) symbol.
Non – Void FunctionsThe Functions that return some value / values as a result, is called as Non-void Functions. Functions can return
value with the help of return statement. return is a Python keyword. Functions returning a value are also known as Fruitful Functions.
Void FunctionsThe Functions that does not return any value, as a result, is called as Void Functions. In this case no need to write return
statement or you many write return statement without value.
Function Returning Multiple ValuesThe Functions that return multiple values i.e. more than one value are called Multi–Value returning
Functions. These are some examples of functions returning a single value.
Scope of a Variable Scope means the accessibility of variables in other parts of the program. The scope rules of Python, decide in which
parts of the program a particular variable can be accessed or not.
Global Scope:A variable that is defined in the ‘main’ program, is called Global Variable and it has global scope.
Local ScopeA variable that is defined in the function called Local Variable and it has local scope.
LifetimeThe time for which a variable remains in memory is called Lifetime of Variable. It depends on the scope of the variable.

QPython program that reverses a string. QWrite recursive code to compute the greatest common divisor
def reverse_string(s): of two number.
return s[::-1] def gcd(a, b):
s = "Hello, World!" if b == 0:
print(reverse_string(s)) return a
else:
QWrite a Python function that accepts a string and return gcd(b, a % b)
calculates the number of uppercase and lowercase print(gcd(60, 48))
letters.
def count_upper_lower(s): QWrite a user-defined function to generate odd numbers
upper = 0 between a and b.
lower = 0 def odd_numbers(a, b):
for i in s: for i in range(a, b+1):
if i.isupper(): if i % 2 != 0:
upper += 1 print(i)
elif i.islower(): odd_numbers(1, 10)
lower += 1
return upper, lower QA user-defined function findname(name) where name is an
s = "Hello, World!" argument in python to delete phone no. from a dictionary
print(count_upper_lower(s)) phonebook on the basis of the name, where name is the key.
phonebook = {
QWrite a Python program to print the even numbers "John": "1234567890",
from a given list. "Jane": "0987654321",
def even_numbers(lst): "Bob": "9876543210"
for i in lst: }
if i % 2 == 0: def findname(name):
print(i) if name in phonebook:
lst = [1, 2, 3, 4, 5, 6] del phonebook[name]
even_numbers(lst) print(f"{name}'s phone number has been deleted from the
phonebook.")
QPython function to check whether a number is else:
perfect or not. print(f"{name} is not in the phonebook.")
def is_perfect(n): findname("John")
sum = 0 print(phonebook)
for i in range(1, n):
if n % i == 0: QWrite a method in Python to find and display the prime
sum += i numbers from 2 to N.
if sum == n: def is_prime(n):
return True if n <= 1:
else: return False
return False for i in range(2, n):
print(is_perfect(6)) if n % i == 0:
return False
QRecursive code to compute and print sum of return True
squares of n numbers. Value of n is passed as def prime_numbers(n):
parameter. for i in range(2, n+1):
def sum_squares(n): if is_prime(i):
sum = 0 print(i)
for i in range(1, n+1): prime_numbers(20)
sum += i**2
return sum
print(sum_squares(5))

You might also like