Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Programming in Python- Unit1-Merged

The document provides an introduction to Python programming, covering its features, execution modes, and basic input/output functions. It explains the use of operators, literals, data types, and the structure of Python programs, including comments and identifiers. Additionally, it outlines how to work with lists, tuples, and dictionaries in Python.

Uploaded by

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

Programming in Python- Unit1-Merged

The document provides an introduction to Python programming, covering its features, execution modes, and basic input/output functions. It explains the use of operators, literals, data types, and the structure of Python programs, including comments and identifiers. Additionally, it outlines how to work with lists, tuples, and dictionaries in Python.

Uploaded by

r7596813
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

Topic/Title: INTRODUCTION TO PYTHON

Name of the Paper : Programming in python


Semester : I
Department : Computer Science
Name of the Faculty : Dr.J.Vanathi
Designation : HEAD
Unit – 1
Introduction to Python
Introduction to Python
➢ An ordered set of instructions to be executed by a computer to carry out a
specific task is called a program, and the language used to specify this set of
instructions to the computer is called a programming language.
➢ Python uses an interpreter to convert its instructions into machine language, so
that it can be understood by the computer.
➢ An interpreter processes the program statements one by one, first translating and
then executing.
➢ This process is continued until an error is encountered or the whole program is
executed successfully.
Features of Python

 Python is a high level language. It is a free and open source language.


 It is an interpreted language, as Python programs are executed by an interpreter.
 Python programs are easy to understand as they have a clearly defined syntax and
relatively simple structure.
 Python is case-sensitive. For example, NUMBER and number are not same in Python.
 Python is portable and platform independent, means it can run on various operating
systems and hardware platforms.
 Python has a rich library of predefined functions.
 Python is also helpful in web development. Many popular web services and
applications are built using Python.
 Python uses indentation for blocks and nested blocks.
Working with Python

 To write and run (execute) a Python program, we need to have a Python interpreter

installed on our computer or we can use any online Python interpreter.

 The interpreter is also called Python shell.

 The symbol >>> is the Python prompt, which indicates that the interpreter is ready

to take instructions. We can type commands or statements on this prompt to execute

them using a Python interpreter.


Execution Modes

There are two ways to use the Python interpreter:


a) Interactive mode
b) Script mode
Interactive mode allows execution of individual statement instantaneously. Whereas,
Script mode allows us to write more than one instruction in a file called Python source
code file that can be executed.

(A) Interactive Mode


 To work in the interactive mode, we can simply type a Python statement on the >>>
prompt directly. As soon as we press enter, the interpreter executes the statement and
displays the result.
 Working in the interactive mode is convenient for testing a single line code for
instant execution.
 But in the interactive mode, we cannot save the statements for future use and we
have to retype the statements to run them again.
(B) Script Mode

 In the script mode, we can write a Python program in a file, save it and then use the

interpreter to execute it.

 Python scripts are saved as files where file name has extension “.py”.

 To execute a script, We can open the program directly from IDLE

 While working in the script mode, after saving the file, click [Run]->[Run Module]

from the menu.


Input & Output Functions: input ()
function, print() function
Definition
The input() function allows user input.
Syntax
input(prompt)
Parameter Values
Parameter -prompt

Description - A String, representing a default message before the


input.
Example
print('Enter your name:')
x = input()
print('Hello, ' + x)
Output
Enter your name:
Hello, Ram
Input & Output Functions: input ()
function, print() function
In Python, we have the input() function for taking the user input.
➢ The input() function prompts the user to enter data.
➢ It accepts all user input as string.
➢ The user may enter a number or a string but the input() function treats them
as strings only.
➢ The syntax for input() is:
input ([Prompt])
➢ Prompt is the string we may like to display on the screen prior to taking the
input, and it is optional.
➢ When a prompt is specified, first it is displayed on the screen after which
the user can enter data.
➢ The input() takes exactly what is typed from the keyboard, converts it into
a string and assigns it to the variable on left-hand side of the assignment
operator (=).
➢ Entering data for the input function is terminated by pressing the enter key.
Contd..
Example for Input Statement
>>> fname = input("Enter your first name: ")
Enter your first name: Ravi
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
Explanation
➢ The variable fname will get the string ‘Ravi’, entered by the user.
➢ Similarly, the variable age will get the string ‘19’.
➢ We can typecast or change the datatype of the string data accepted from
user to an appropriate numeric value.
➢ For example, the following statement will convert the accepted string to an
integer.
➢ If the user enters any non-numeric value, an error will be generated.
print() function
With the print() function, you can display output in various formats, while the
input() function enables interaction with users by gathering input during
program execution.
Printing output in Python is straightforward, thanks to the print() function.
Contd..
This function allows us to display text, variables, and expressions on the
console.
Example
print("Hello, World!")
output
Hello, World!
Print Statement
➢ Python uses the print() function to output data to standard output device —
the screen.
➢ The function print() evaluates the expression before displaying it on the
screen.
➢ The print() outputs a complete line and then moves to the next line for
subsequent output.
➢ The syntax for print() is:
print(value [, ..., sep = ' ', end = '\n']) • sep:
➢ The optional parameter sep is a separator between the output values.
➢ We can use a character, integer or a string as a separator.
➢ The default separator is space.
Example for Print Statement
Statement Output

print("I" + "love" + "my" + "country") I love my country

print("I'm", 16, "years old") I'm 16 years old


Comments in Python-Indentation
• A Python statement is an instruction that the Python interpreter can
execute.
• There are different types of statements in Python language such as
Assignment statements, Conditional statements, Looping statements, etc.
• The token character NEWLINE is used to end a statement in Python.
• It signifies that each line of a Python script contains a statement.
• These all help the user to get the required output.
Comments
➢ Comments are used to add a remark or a note in the source code.
➢ Comments are not executed by interpreter.
➢ In Python, a comment starts with # (hash sign).
➢ Everything following the # till the end of that line is treated as a comment
and the interpreter simply ignores it while executing the statement.
Tokens: Identifiers, keywords,
Variables
Python Keywords
Keywords are reserved words.
Each keyword has a specific meaning to the Python interpreter, and we can
use a keyword in our program only for the purpose for which it has been
defined.
As Python is case sensitive, keywords must be written exactly as given in the
below.
Python keywords:
➢ False
➢ return
➢ None
➢ continue
➢ for
➢ try
➢ True
➢ def
➢ while
Variables
➢ A variable in a program is uniquely identified by a name (identifier).
➢ Variable in Python refers to an object — an item or element that is stored
in the memory.
➢ Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric
(e.g., 345) or any combination of alphanumeric characters (CD67).
➢ In Python we can use an assignment statement to create new variables and
assign specific values to them.
Example:
gender = 'M’
message = "Keep Smiling"
price = 987.9
Identifiers
Identifiers
In programming languages, identifiers are names used to identify a variable,
function, or other entities in a program.
The rules for naming an identifier in Python are as follows:
➢ The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_). This may be followed by any combination of characters
a–z, A–Z, 0–9 or underscore (_). Thus, an identifier cannot start with a digit.
➢ It can be of any length. (However, it is preferred to keep it short and
meaningful).
➢ It should not be a keyword or reserved word
➢ We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
For example, to find the average of marks obtained by a student in three
subjects, we can choose the identifiers as marks1, marks2, marks3 and avg
rather than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks 3)/3
Operators in Python (Arithmetic,
Relational, Logical, Assignment)
Operators in Python
Operators
➢ An operator is used to perform specific mathematical or logical operation
on values.
➢ The values that the operator works on are known as operands.
➢ For example, in the expression 10 + num, the value 10, and the variable
num are operands and the + (plus) sign is an operator.

Precedence of Arithmetic Operators in Python


The precedence of Arithmetic Operators in Python is as follows:
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
Arithmetic Operators

Arithmetic Operators
➢ Python supports arithmetic operators to perform the four basic arithmetic
operations as well as modular division, floor division and exponentiation.
➢ '+' operator can also be used to concatenate two strings on either side of
the operator.

>>> str1 = "Hello"


>>> str2 = "India"
>>> str1 + str2
Output:'HelloIndia'
Relational Operators

Relational Operators
➢ Relational operator compares the values of the operands on its either side
and determines the
relationship among them.
➢ Assume the Python variables num1 = 10, num2 = 0, num3 = 10, str1 =
"Good", str2 =
"Afternoon" for the following examples:
Logical Operators
Operator Description Syntax Example

and Returns True if x and y x>7 and x>10


both the operands
are true

or Returns True if x or y x<7 or x>15


either of the
operands is true

not Returns True if the not x not(x>7 and x>


operand is false 10)
Bitwise Operators
Python bitwise operators are used to perform bitwise calculations on integers.
The integers are first converted into binary and then operations are performed
on each bit or corresponding pair of bits, hence the name bitwise operators.
The result is then returned in decimal format.

Expressions
➢ An expression is defined as a combination of constants, variables, and
operators.
➢ An expression always evaluates to a value.
➢ A value or a standalone variable is also considered as an expression but a
standalone operator
is not an expression.
➢ Examples of valid expressions are given below.
(i) 100
(ii) num (iii) num – 20.4
(iv) 3.0 + 3.14
(v) 23/3 -5 * 7(14 -2)
(vi) "Global" + "Citizen"
Delimiters, Literals (Numeric, String,
Boolean, Escape)
A delimiter is a sequence of one or more characters used to specify the boundary between
separate, independent regions in plain text or other data streams.
An example of a delimiter is the comma character, which acts as a field delimiter in a
sequence of comma-separated values.

A literal in Python is a syntax that is used to completely express a fixed value of a specific
data type.
Literals are constants that are self-explanatory and don’t need to be computed or evaluated.
They are used to provide variable values or to directly utilize them in expressions.
Types of Literals in Python
Python supports various types of literals, such as numeric literals, string
literals, Boolean literals, and more.
String literals
Character literal
Numeric literals
Boolean literals
Literal Collections
Special literals

Python literal collections


Python provides four different types of literal collections:

List literals
Tuple literals
Dict literals
Set literals
Types of Literals in Python
List literal
The list contains items of different data types. The values stored in the List
are separated by a comma (,) and enclosed within square brackets([]). We can
store different types of data in a List. Lists are mutable.i.e are able to change
their values.
Example
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)

Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
Types of Literals in Python
Tuple literal
A tuple is a collection of different data-types. It is enclosed by the
parentheses ‘()‘ and each element is separated by the comma(,). It is
immutable.

Example
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)

Output
(2, 4, 6, 8)
(1, 3, 5, 7)
Types of Literals in Python

Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly
braces ‘{}‘ and each pair is separated by the commas(,). We can store
different types of data in a dictionary. Dictionaries are mutable.

Example
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}

print(alphabets)
print(information)
Python Data Types
Python Data Types
Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value.
A numeric value can be an integer, a floating number, or even a complex
number.

Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types( memoryview, bytearray, bytes).

Numeric Data Types in Python


The numeric data type in Python represents the data that has a numeric value.
A numeric value can be an integer, a floating number, or even a complex
number. These values are defined as Python int, Python float, and Python
complex classes in Python.
Python Data Types
Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or
different data types. Sequences allow storing of multiple values in an
organized and efficient fashion. There are several sequence data types of
Python:

Python String
• Python List
• Python Tuple

String Data Type


Strings in Python are arrays of bytes representing Unicode characters. A
string is a collection of one or more characters put in a single quote, double-
quote, or triple-quote. In Python, there is no character data type Python, a
character is a string of length one. It is represented by the str class.
Python Data Types
Creating String
Strings in Python can be created using single quotes, double quotes, or even
triple .
Example
String1 = 'Welcome to the cartoon World'
print("String with the use of Single Quotes: ")
print(String1)
String1 = "I'm a cartoon"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
String1 = '''I'm a cartoon and I live in a world of "cartoons"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
String1 = '''cartoon
For
Life'''
Python Data Types

print("\nCreating a multiline String: ")


print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
Python Data Types
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection
of data. It is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets[].
Example
List = []
print("Initial blank List: ")
print(List)
List = ['cartoonsForcartoon']
print("\nList with the use of String: ")
print(List)
List = ["cartoons", "For", "cartoons"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
List = [['cartoons', 'For'], ['cartoons']]
print("\nMulti-Dimensional List: ") print(List)
Python Data Types

Output:
Initial blank List:
[]
List with the use of String:
['cartoonsForcartoon']
List containing multiple values:
cartoons
cartoon
Multi-Dimensional List:
[['cartoons', 'For'], ['cartoon']]
Topic/Title: INTRODUCTION TO PYTHON

Name of the Paper : Programming in python


Semester : I
Department : Computer Science
Name of the Faculty : Dr.J.Vanathi
Designation : HEAD
Unit – II
Control Structures
In Python statements are of following types:
1. Empty Statement
2. Simple Statement
3. Compound Statement

1. Empty Statement: Empty statement is the simplest statement. This is a


statement which does nothing. In Python an empty statement is
pass statement.
Pass statement of Python is a do nothing statement i.e. empty statement or
null operation statement.

2. Simple Statement
Simple Statement: Any single executable statement is a simple statement in
Python.
Example
>>>name=input(“Enter your name please:- “)
>>>print(“My name is “,name)
Control Structures
3. Compound Statement: A compound statement in Python has a header ending
with a colon( : ) and a body containing a sequence of statements at
the same level of indentation.
<compound statement header>:
<Indented body containing multiple simple / and or compound statement>
Header Line: It begins with a keyword and ends with a colon.
Body: Consists of one or more Python statement each indented inside the header
line.
FLOW CONTROL STATEMENT:- statements may execute sequentially,
selectively or iteratively.
(A) Sequence: The sequence means statements are being executed one by one in
the order in which it appears in the source code. This is the default flow of control.

Sequential Statements
Sequential statements are a set of statements
whose execution process happens in a sequence.
The problem with sequential statements is that if the
logic has broken in any one of the lines,
then the complete source code execution will break.
Control Structures
Control Structures

STATEMENTS IN PYTHON
(B) Selection: The selection construct means the execution of statement(s)
depending upon a condition testing. If a condition evaluates to True, a
course-of-action is followed otherwise another course of action is followed.
The construct selection is also called decision construct because it helps in
making decision about which course of action to be followed.
Control Structures
Syntax of if statement is:
if condition:
statement(s)
Example
age = int(input("Enter your age "))
if age >= 18:
print("Eligible to vote")
if..else statement
➢ A variant of if statement called if..else statement allows us to write two
alternative paths
and the control condition determines which path gets executed.
➢ The syntax for if..else statement is as follows.
if condition:
statement(s)
else:
statement(s)
Control Structures
elif statement
Syntax
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Looping Constructs
Repetition
➢ Repetition of a set of statements in a program is made possible using
looping constructs.
The ‘For’ Loop
➢ The for statement is used to iterate over a range of values or a sequence.
➢ The for loop is executed for each of the items in the range.
➢ These values can be either numeric, they can be elements of a data type
like a string, list, or tuple. With every iteration of the loop, the control
variable checks whether each of the values
in the range have been traversed or not.
➢ When all the items in the range are exhausted, the statements within loop
are not executed; the control is then transferred to the statement immediately
following the for loop.
➢ While using for loop, it is known in advance the number of times the loop
will execute.
Looping Constructs

Syntax of the For Loop for in


for <control-variable> in <sequence/items in
range>:
<statements inside body of the loop>
Looping Constructs
The ‘While’ Loop
➢ The while statement executes a block of code repeatedly as long as the
control
condition of the loop is true.
➢ The control condition of the while loop is executed before any statement
inside the loop is executed.
➢ After each iteration, the control condition is tested again and the loop
continues as long as the condition remains true.
➢ When this condition becomes false, the statements in the body of loop are
not executed and the control is transferred to the statement immediately
following the body of while
loop.
➢ If the condition of the while loop is initially false, the body is not executed
even once.
The statements within the body of the while loop must ensure that the
condition eventually becomes false; otherwise the loop will become an
infinite loop, leading to a logical error in the program.
Looping Constructs

Syntax of while Loop


while test_condition:
body of while
THE if STATEMENTS

The if statements are the conditional statements in python and these


implement selection constructs (decision).
An if statements tests a particular condition. If the condition evaluates true a
course-of-action is followed otherwise another course-of-action
is performed.
If statement has various forms which is presented here

if <conditional expression>:
statement
[statement] Indentation of all statements of the true block must be same
Example
if ch==‘ ‘:
no_of_space+=1
no_of_chars+=1
THE if STATEMENTS
Another Form
if <conditional expression>:
statement
[statement] True Block
else:
statement False Block
[statement]
num=int(input(“Enter a number:- “))
if num%2==0:
print(num,” is an even number”)
else:
print(num,
“ is an odd number”)
THE if STATEMENTS
Next Form
if <conditional expression>:
if <condition expression2>: # Nested if
statement True Block of nested if
[statement]
else:
statement False Block of nested if
[statement]
else:
statement # False Block of outer if
[statement]
THE if STATEMENTS
Next Form (Nested if, else if ladder)
if <conditional expression>:
if <condition expression2>: # Nested if
statement
[statement]
else:
statement
[statement]
else:
if <condition expression3>: #else if ladder
statement
[statement]
else:
statement
[statement]
THE if STATEMENTS
Next Form (Nested if, else if ladder)
if <conditional expression>:
statement
[statement]
elif <condition expression>:
statement
[statement]
else:
statement
[statement]
Form1 of If Statement
if <conditional statement>:
if <conditional statement>:
staements(s)
else:
statement(s)
elif <conditional statement>:
statement
[statements]
else:statementa[statements]
THE if STATEMENTS
Form2 of If Statement
if <conditional statement>:
statement
[statements]
elif <conditional statement>:
if <conditional statement>:
statement
[statements]
else:
statement
[statements]
else:
statement
[statements]
THE if STATEMENTS
Form 3 of If Statement
if <condition expression>:
statement
[statements]
elif <condition expression>:
statement
[statements]
else:
if <condition expression>:
statement(s)
else:
statement(s)
THE if STATEMENTS
if <condition expression>:
if <condition expression>:
statement(S)
else:
statement(s)
statement [statements]
elif <condition expression>:
if <condition expression>:
statement(S)
else:
statement(s)
else:
if <condition expression>:
statement(s)
else:
statement(s)
ITERATIVE STATEMENTs IN
PYTHON
Some problem’s solution demands execution of one or more statements more
than once. For such problem’s solution Python provides iterative statement or
loop control statement.
Python has two kinds of loop to represent two categories of loops
1. counting loops : Loops that repeat a certain number of times.
Python for loop is a counting loop.
Conditional Loops: Loops that repeat until a certain things happens. They
keep repeating as long as some condition is true. Python while loop is
conditional loop.
Before we move the structure of loop control statement let us see the function
range.
range() function:- range() function of Python generates a list which is special
sequence type. A sequence in Python is a sequence of values bound together
by a single name. Some python sequences are string, tuples, lists etc.
This function has following form
range(lower limit, upper limit, stepvalue)
Example
range(5) will give a list[0,1,2,3,4]
range(0,5) will give a list[0,1,2,3,4]
Jump Statements
break:
This is jumping statement in Python. This statement when executed takes the
control out of current loop.
Continue:
This is also a jumping statement in python. This statement on execution
forces the interpreter for next iteration leaving statements lying below the
continue statement unexecuted.
Example to show the difference between break and continue.
print("The loop with break produces output as below")
for i in range(1,5):
if i%3==0:break;
else:
print(i)
Output
1
2
print("The loop with continue")
for i in range(1,5):
if i%3==0:
continue
else:
print(i)
Output
1
2
4
Loop else statement

loop else statement is executed only when the loop is terminated normally. It
is not executed when the control comes out of loop
due to break statement.
syntax
loop control variable initialization
while(logical expression):
body of the loop
updation of loop control variable
else:
statement(s)

for variable in <sequence>:


loop body statements
else:
statement(s)
Break and Continue Statement
Looping constructs allow programmers to repeat tasks efficiently.
➢ In certain situations, when some particular condition occurs, we may want
to exit from a loop (come out of the loop forever) or skip some statements of
the loop before continuing further
in the loop. These requirements can be achieved by using break and continue
statements, respectively.
➢ Python provides these statements as a tool to give more flexibility to the
programmer to control the flow of execution of a program.
Break Statement
➢ The break statement alters the normal flow of execution as it terminates
the current loop and resumes execution of the statement following that loop.
Pass statement
The pass statement is used as a placeholder for future code.
When the pass statement is executed, nothing happens, but you avoid getting
an error when empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or
in if statements.
def myfunction():
pass
FUNCTION

FUNCTION
Definition:
Functions are the subprograms that perform specific task. Functions are the
small modules.
Types of Functions:
There are three types of functions in python:
1. Library Functions (Built in functions)
2. Functions defined in modules
3. User Defined Functions
TYPES OF FUNCTIONS
TYPES OF FUNCTIONS
1. Library Functions: These functions are already built in the python library.
2. Functions defined in modules: These functions defined in particular
modules.
When you want to use these functions in a program, you have to import the
corresponding module of that function.
3. User Defined Functions: The functions that are defined by the user are
called user defined functions.
1. Library Functions in Python: These functions are already built in the
library of python. For example: type( ), len( ), input( ), id( ), range( ) etc.
2. Functions defined in modules:
a. Functions of math module: To work with the functions of math module, we
must import math modules in the program.
User Defined Functions
The syntax to define a function is:
Where:
➢ Keyword def marks the start of function header.
➢ A function name to uniquely identify it. Function naming follows the same
rules of writing identifiers in Python.
➢ Parameters (arguments) through which we pass values to a function. They are
optional.
➢ A colon (:) to mark the end of function header.
➢ One or more valid python statements that make up the function body.
Statements must have same indentation level.
➢ An optional return statement to return a value from the function.

Example:
def display(name):
print("Hello " + name + " How are you?")
Function Parameters
Function Parameters
A functions has two types of parameters:
1. Formal Parameter
2. Actual Parameter
1. Formal Parameter:
Formal parameters are written in the function prototype and function header
of the definition.
Formal parameters are local variables which are assigned values from the
arguments when the
function is called.
Function Parameters

Python supports two types of formal parameters:


i. Positional parameters
ii. Default parameters
i. Positional parameter:
These are mandatory arguments. Value must be provided to these parameters
and values should be matched with parameters.
Example:
Let a function defined as given below:
def Test(x,y,z):


Function Parameters
Then we can call the function using these possible function calling
statements:
p,q,r = 4,5,6
Test(p,q,r) # 3 variables which have values, are passed
. Default Parameters:
a. The parameters which are assigned with a value in function header while
defining the function, are known as default parameters. This values is
optional for the parameter.
b. If a user explicitly passes the value in function call, then the value which is
passed by the user, will be taken by the default parameter. If no value is
provided, then the default value will be taken by the parameter.
c. Default parameters will be written in the end of the function header, means
positional parameter cannot appear to the right side of default
Parameter.
Actual Parameter

When a function is called, the values that are passed in the call are called
actual parameters. At the time of the call each actual parameter is assigned to
the
corresponding formal parameter in the function definition.
Example:
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y

print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual
parameters
In the above example, x and y are formal parameters. a and b are actual
parameters.
Difference between formal
parameter and actual parameter

Formal parameter Actual parameter


Formal parameters are written in the When a function is called, the values that
function prototype and function header of are passed in the call are called actual
the definition. Formal parameters are local parameters. At the time of the call each
variables which are assigned values from actual parameter is assigned to the
the arguments when the function is called. corresponding formal parameter in the
function definition.
Built-in Functions
Name Description
abs() The abs() function is used to get the absolute (positive) value of a
given number.
all() The all() function is used to test whether all elements of an iterable are
true or not.
any() The any() function returns True if any element of the iterable is true.
The function returns False if the iterable is empty.
ascii() The ascii() function returns a string containing a printable
representation (escape the non-ASCII characters ) of an object.
bin() The bin() function is used to convert an integer number to a binary
string. The result is a valid Python expression.
bool() The bool() function is used to convert a value to a Boolean.
bytearray() The bytearray() function is used to get a bytearray object.
Types of Functions
There are two types of functions, namely
1. Value-Returning Function
2. Non-Value-Returning Function
Value- Returning Function
A statement ‘return’ is used at the end of the function execution and “returns”
the result of the function to the calling program. Please note that a ‘return’
statement cannot be used outside the function. Let’s look at a small example
of value returning function.

#Value-Return Function Example


def cube(n):
return n*n*n
s=cube(6)
print(“The Cube Value Returned from the
function is:”,s)
The Cube Value Returned from the function
is:216
Types of Functions
In the above example, ‘cube’ is the name of the function that calculates and
returns the cube of any given number N.
We are calling the function by passing an argument as 6 to cube routine. The
routine calculates 6*6*6 and returns the value back
to the calling statement. This calculated value 216 is stored in the variable ‘s’,
which is printed by using the print ( ) function.

Non-Value-Returning Function

If a function is not going to return any value, instead it’s going to do some
task like displaying some message to the user, then it’s called as a “Non-
Value-Returning Function”. It doesn’t have a ‘return statement.
Types of Functions
Example code for Non-Value-Return Function
def non value return(n):
print(“This is demo code for non-value
return function”)
print(“This doesn’t have a return
statement”)
non value return():
This is demo code for non-value return
function
This doesn’t have a return statement
In the above example, we can see that the output of the function call is
nothing but those print statements.
Every function in Python is a value returning function only. If there is no
explicit return from the function, it returns a
special value none.
Types of Functions
Calling Value-Return Functions

Let us assume we need to calculate a mathematical


expression say f(x,y) = x^2 + y^2 .A simple function returning value can be
used to solve this expression. The program code goes as follows:

Value returning function example code


def f(n): #function declaration
return n*n
x=int(input(“Enter the Value of X:”)):
y=int(input(“Enter the Value of X:”)):
print(“The value of f(x,y) is:”,f(x)+f(y))
#function calling inside the print statement
Output
Enter the Value of X:2
Enter the Value of X:3
The value of f(x,y) is: 13
Types of Functions
In the above code, we first declare the function f(n) using the keyword ‘def’.
We get input values for the variables x & y from the user. Since the input
function returns a string, we use
the ‘ínt’ keyword to convert the string value into an integer value and to
perform the mathematical operations. Then we use the
print() function to print the sum of results returned from the respective
functions f(x) and f(y).

Similarly built-in functions like functions namely, abs(), pow(), mean(),


round(), cmp() all fall in this category of value returning function
Types of Functions
Calling Non-Value Returning Function
As the name indicates, non-value-returning functions will not return any
value. The function calls are basically been seen as statements and can be
used anywhere.

Example code for Non-Value Return Function


def nonreturn(name):
print(“This is a non value return function
demo”)
print(“Hello,Welcome”+name+”!!”)
nonreturn(“Tom”)
This is a non value return function demo
Hello,WelcomeTom!!
Parameter Passing for Immutable
and Mutable Arguments
Immutable Arguments

In Python, Immutable arguments are those whose value cannot be changed


after creation or initialization. A new memory location is allocated to the
variable whenever its value changes.

Immutable objects like numbers (int and float), tuple and strings are also
passed by reference like mutable objects names list, set and dict. So, any
change that happens to the immutable argument inside the function block, a
new memory location is created to the new value and manipulated. The caller
object remains unchanged. Hence, the caller will not be aware of the changes
inside the function block to that immutable argument.
Parameter Passing for Immutable and
Mutable Arguments
Explanation:
The integer ‘x’ is an immutable (unchangeable) argument.
A local duplicate copy ‘a’ for the integer object ‘x’ is created and used inside
the function fnt() .The caller block has no effect on the value of the
variable‘x’.
The value of ‘y’ is the value of variable ‘a’ which is returned from function
fnt() after adding10.
Variables ‘x’ and ‘y’ are different and their id values are also different as
shown below.
Variable ‘y’ and ‘a’ are the same as you can see their id values are the same.
Both point to same integer object(20)
Parameter Passing for Immutable and
Mutable Arguments
def fnt(new): # function declaration
new =new +10
print(‘id of new:’, id(new)) # id of y and a
are same
return new #function call
x=10
y= fnt(x) #function called by passing
parameter x
#the value of y will be 20
print(‘x:’,x)# value of x is unchanged
# value of y is the return value of the
function fnt
print(‘y:’, y) #y is now incremented by 10
print(‘id of x:’, id(x)) # id of x
print(‘id of y:’,id(y)) # id of y, different
from x·
Mutable arguments in Python
Examples of mutable arguments in Python are set, list and dict. Their values
can be changed in place after the assignment or creation. When the value of
the mutable argument changes, they are not allocated new memory location.
In Python, all these mutable objects are also passed by reference only. If any
value is changed inside the function block.
Example of Mutable Arguments
def fnt2(func_list):
# function block
func_list.append(30) #append an element
def fnt3(func_list):
# function block
del func_list[l] #delete 2nd element
def fnt4(func_list):
# function block
func_list[O] = 100 #change value of 1st element
# main or caller block
listl = [10, 20]
list2 = listl #listl and list2 point to same list
Mutable arguments in Python
object
print(‘ original list:’,list1)
print(‘listl id:’, id(listl))
print(‘value of list2:’, list2)
print(‘list2 id:’, id(list2))
fnt2(list1)
print(‘\nafter fnt2():’, listl)
print(‘listl id:’, id(listl))
print(‘value of list2:’, list2)
print(‘list2 id:’, id(list2))
fnt3(list1)
print(‘\nafter fnt3():’, listl)
print(‘listl id:’, id(listl))
print(‘value of list2:’, list2)
print(‘list2 id:’, id(list2))
fnt4(list1)
print(‘\nafter fnt4():’, listl)
print(‘listl id:’, id(listl))
print(‘value of list2:’, list2)
print(‘list2 id:’, id(list2))
Arguments in a function
The definition of an argument is basically a value that is passed on to a
function. As discussed earlier, the calling side it.
Key Value arguments
>>>def multiplication(a,b= 10):
print(“The multiplied value of a,b is :”, a*b)
>>>multiplication(4,b=15)
The multiplied value ofa,b is : 60
The added advantage in Python is that we can also change the order of
passing the arguments. In the above example, let’s
reverse the values of “a” and “b”.
>>>def multiplication(a,b =10):
print (“The given value of a is:”,a)
print(“ The given value of b is:”,b)
return a*b
>>> print (multiplication(b =20, a=5))
The given value of a is: 15
The given value of b is: 20
300
Arguments in a function
Apart from the above options, Python allows us to pass
multiple arguments in the form of an array
>>>def argument(*args):
print(args)
>>> argument(10,20,30,40,50)
(10, 20, 30, 40, 50)
Calling the function
Once we have defined a function, we can call it from another function,
program or
even the Python prompt. To call a function we simply type the function name
with
appropriate parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
Output:
Sum = 30.0
How does the function work?
def functionName(parameter):
The return statement:
The return statement is used to exit a function and go back to the place from
where it was called.
Calling the function

There are two types of functions according to return statement:


a. Function returning some value (non-void function)
b. Function not returning any value (void function)
a. Function returning some value (non-void function) :
Syntax:
return expression/value
Lambda Function
Python gives a flexibility of writing function without any name.
Those are called as anonymous function also known as Lambda
Functions. So far, we have used the key word ‘def’ to declare a function. In
case of an anonymous function, we use the keyword
‘lambda’ in Python and hence called are as lambda functions.
lambda function Syntax:
lambda arguments: expression
As shown above, the lambda function can accept any number of arguments
but can have only one expression. The given expression will be evaluated and
value will be returned back.
>>>s=lambda x,y: (x+y)
>>>print (s(5,10))
15
We have an anonymous function to add two numbers x, y. This function with
a keyword ‘lambda’ calculates the value of the expression and returns the
result to the variable s. In the print statement we call the function by passing
5,10 as the argument. The expression is evaluated and the result15 is given
back to the user.
Lambda Function
It is similar to writing a function as shown below:
def sum(x,y):
return(x+y)
>>>new=”hi,lambda”
>>>print(lambda new:print(new))
In the above code, we have defined a string variable ‘new’, we tried to print
out lambda. But we got the following as the
Output
<function<lambda> at 0x041B8270>
Basically, when we called the print function, the print didn’t call the lambda
function at all. Instead it printed the function object and its memory location.
So how print the string using the lambda function? We need to slightly tweet
the code as shown below:
>>>(lambda new:print(new))(“hi lambda”)
If you look at the above code, we call the lambda function first which in turn
calls the print function. We pass the string “hi lambda” immediately after the
call which will be printed as shown below:

hi lambda
Regular function Vs lambda Function
1. Regular functions can have many expressions to be evaluated whereas
lambda function will have only one expression in their body.
2. Regular functions have a name associated with them while lambda
functions are anonymous meaning nameless.
3. Regular function has a return statement to return the value.
Recursion Function
The term Recursion can be defined as the process of defining something in terms
of itself. In simple words, it is a process in which a function calls itself directly or
indirectly.
Advantages of using recursion
• A complicated function can be split down into smaller sub-problems utilizing
recursion.
• Sequence creation is simpler through recursion than utilizing any nested
iteration.
• Recursive functions render the code look simple and effective.

Disadvantages of using recursion


• A lot of memory and time is taken through recursive calls which makes it
expensive for use.
• Recursive functions are challenging to debug.
• The reasoning behind recursion can sometimes be tough to think through.
Recursion Function
Syntax:

def func(): <--


|
| (recursive call)
|
func() ----
Recursion Function
Example
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8….
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
Recursion Function
Output
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Functions using Libraries
Python also has other library functions, including:
abs(), aiter(), all(), anext(), any(), ascii(), bin(), and bool.

Python functions are pre-defined by the Python interpreter and can be used in
any program. Functions can return any type of objec
Variable Scope( Local, Global)-
Modules
Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is
recognized.
Parameters and variables defined inside a function is not visible from outside.
Hence, they have a local scope.
There are two types of scope for variables:
1. Local Scope
2. Global Scope
1. Local Scope:
Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the
function executes. They are destroyed once we return from the function.
Hence, a function does not remember the value of a variable from its previous
calls.
Variable Scope( Local, Global)-
Modules
2. Global Scope:
Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Variable Scope( Local, Global)-
Modules
Here, we can see that the value of x is 20 initially. Even though the function
my_func()changed the value of x to 10, it did not affect the value outside the
function.
This is because the variable x inside the function is different (local to the
function) from the one outside. Although they have the same names, they are
two different variables with different scope. On the other hand, variables
outside of the function are visible from inside. They have a global scope. We
can read these values from inside the function but cannot change (write)
them. In order to modify the value of variables outside the function, they
must be declared as global variables using the keyword global.
Topic/Title:String & String Manipulation

Name of the Paper : Programming in python


Semester : I
Department : Computer Science
Name of the Faculty : Dr.J.Vanathi
Designation : HEAD
UNIT – III
String & String Manipulation
A string represents a group of characters. In Python , the str datatype
represents a string. Python handles strings and characters in the same manner.

There is no separate datatype to represent individual characters in Python.

String Creation
S1 = “ Python Programming Language”
S1 = ‘Python Programming Language’

Strings can be created with double quotes an single quotes.


While printing strings , we can use escape characters like \t or\n inside the
strings.
S1 = “Python \t Programming \n Language”
print(S1)
Output
Python Programming
Language
String Manipulation
Length of a String
Length of a string represents the number of characters in a string. To know
the length of a string , we can use the len() function.

Example
012345
S1->
PYTHON
-6 -5 -4 -3 -2 -1
Here in s1[i], i is called the string index and refers to the ith element of the
string . For Example s1[0] = ‘P’, s[1] =’Y’ and so on.
When we use index as a negative number , it refers to elements in the reverse
order. This s1[-1] = ‘N’ , s1[-2] = ‘o’ and so on.
String Manipulation
Python Program to Access characters of String
String1 = “PYTHON”
print(“Initial String: “)
print(String1)
# Printing First character
print(“\nFirst character of String is: “)
print(String1[0])
# Printing Last character
print(“\nLast character of String is: “)
print(String1[-1])
Output:
Initial String:
PYTHON
First character of String is:
P
Last character of String is:
N
String Manipulation
Python strings are “immutable” which means they cannot be changed after
they are created. Since strings can’t be changed, we construct *new* strings
as we go to represent computed values. So for example the expression
(‘hello’ + ’there’) takes in the 2 strings ‘hello’ and ‘there’ and builds a new
string ‘hellothere’.
String Slicing
A slice represents a part or piece of string. The format of slicing is :
Stringname[start : stop : stepsize]
If start and stop are not specified , then slicing is done from 0th to n-1th
elements. If stepsize is not written then it is taken to be 1.
# Python Program to demonstrate String slicing
# Creating a String
String1 = “PYTHON PROGRAM”
print(“Initial String: “)
print(String1)
# Printing 3rd to 14th character
print(“\nSlicing characters from 3-14: “)
print(String1[3:14])
String Manipulation
# Printing characters between 3rd and 2nd last character
print(“\nSlicing characters between “ +
“3rd and 2nd last character: “)
print(String1[3:-2])
Output
Initial String:
PYTHON PROGRAM
Slicing characters from 3-1
Slicing characters between 3rd and 2nd last character:
HON PROGR
String Operations
➢ String is a sequence of characters. Python allows certain operations on string data
type,
such as concatenation, repetition, membership and slicing.
Concatenation
➢ To concatenate means to join. Python allows us to join two strings using
concatenation
operator plus which is denoted by symbol +
➢ >>> str1 = 'Hello' #First string
➢ >>> str2 = 'World!' #Second string
➢ >>> str1 + str2 #Concatenated strings
➢ 'HelloWorld!'
Repetition
➢ Python allows us to repeat the given string using repetition operator which is
denoted by
symbol *.
➢ #assign string 'Hello' to str1
➢ >>> str1 = 'Hello' #repeat the value of str1 2 times
➢ >>> str1 * 2 'HelloHello' #repeat the value of str1 5 times
➢ >>> str1 * 5
➢ 'HelloHelloHelloHelloHello’
String Operations
Membership
➢ Python has two membership operators 'in' and 'not in’.
➢ The 'in' operator takes two strings and returns True if the first string
appears as a
substring in the second string, otherwise it returns False.
➢ The 'not in' operator also takes two strings and returns True if the first
string does not
appear as a substring in the second string, otherwise returns False.
Traversing a String
➢ We can access each character of a string or traverse a string using for loop
and while loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!’
>>> for ch in str1:
print(ch,end = ‘’)
Hello World! #output of for loop
In the above code, the loop starts from the first character of the string str1 and
automatically ends when the last character is accessed.
String Traversal Using while Loop
>>> str1 = 'Hello World!’
>>> index = 0
#len(): a function to get length of string
>>> while index < len(str1):
print(str1[index],end = ‘’)
index += 1

Hello World! #output of while loop


Common Python String Methods
String Methods Description

upper() Converts all characters in a string to uppercase.

lower() Converts all characters in a string to lowercase.

find(substring) Returns the lowest index in the string where the


substring is found.

strip() Removes any leading and trailing characters


(space is the default).

replace(old, new) Replaces occurrences of a substring within the


string.

split(delimiter) Splits the string at the specified delimiter and


returns a list of substrings.

join(iterable) Concatenates elements of an iterable with a


specified separator.
List & List Manipulation
List
A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
Example:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
List Manipulation
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Example
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
List Manipulation
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the
list:
Example
This example returns the items from index -4 (included) to index -1
(excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Change Item Value
To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
List Manipulation
Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Check if Item Exists
To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Manipulation
Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
To add an item at the specified index, use the insert() method:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
List Manipulation
Remove Item

There are several methods to remove items from a list:

Example

The remove() method removes the specified item:

thislist = ["apple", "banana", "cherry"]


thislist.remove("banana")
print(thislist)
List Manipulation
The del keyword removes the specified index:thislist = ["apple", "banana",
"cherry"]
del thislist[0]
print(thislist)
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Tuple & Tuple Manipulation
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers
to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Tuple Manipulation
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new tuple with the specified
items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
Tuple Manipulation
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.
You can convert the tuple into a list, change the list, and convert the list back into a
tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Tuple Manipulation
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Tuple Manipulation
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can delete the
tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exist
Tuple Manipulation
Join Two Tuples
To join two or more tuples you can use the + operator:

Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

Tuple Methods
Python has two built-in methods that you can use on tuples.
count() - Returns the number of times a specified value occurs in a tuple
index() - Searches the tuple for a specified value and returns the position of
where it was
found.
Set & Set Manipulation
Set
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the
items has no index.
But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Set Manipulation
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.

Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Set Manipulation
Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)

Get the Length of a Set


To determine how many items a set has, use the len() method.
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Remove Item
To remove an item in a set, use the remove(), or the discard() method.

Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Set Manipulation
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both
sets, or the update() method that inserts all the items from one set into another:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Dictionaries & Dictionaries
Dictionary
Manipulation
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.

Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]
Dictionaries Manipulation
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Dictionaries Manipulation
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len()
function.

Example
Print the number of items in the dictionary:
print(len(thisdict))

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a
value to it:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Dictionaries Manipulation

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Dictionaries Manipulation
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

The del keyword can also delete the dictionary completely:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Dictionaries Manipulation

The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Topic/Title: GUI in Python using Tkinter

Name of the Paper : Programming in python


Semester : I
Department : Computer Science
Name of the Faculty : Dr.J.Vanathi
Designation : HEAD
UNIT – IV
GUI in Python using Tkinter
• Tkinter in Python helps in creating GUI Applications.

• Tkinter is pronounced as tea-kay-inter

• Among various GUI Frameworks, Tkinter is the only framework that is built-in
into Python's Standard Library.

• An important feature in favor of Tkinter is that it is cross-platform, so the same


code can easily work on Windows,
• macOS, and Linux.

• Tkinter is a lightweight module.

• It comes as part of the standard Python installation, so you don't have to install it
separately.

• It supports a lot of built-in widgets that can be used directly to create desktop
applications.
GUI in Python using Tkinter
Tkinter
Tkinter

Using Tkinter to Create Desktop Applications



The basic steps of creating a simple desktop application using the Tkinter
module in Python are as follows:
• First of all, import the Tkinter module.
• The second step would be to create a basic window for the desktop application.
• Then you can add different GUI components to the window and functionality to
these components or widgets.
• Then enter the main event loop using mainloop() function to run the Desktop
application
Tkinter
Tkinter
Tkinter

import tkinter
top = tkinter.Tk()

# Code to add widgets will go here...


top.mainloop()
Tkinter
First, import the tkinter module as tk to the program:
import tkinter as tk
Code language: Python (python)
Second, create an instance of the tk.Tk class that will create the application
window:
root = tk.Tk()
Code language: Python (python)
By convention, the main window in Tkinter is called root. But you can use
any other name like main.
Third, call the mainloop() method of the main window object:
root.mainloop()
The mainloop() method ensures the main window remains visible on the
screen.
If you don’t call the mainloop() method, the main window will display and
disappear almost instantly – too quickly to perceive its appearance.
Additionally, the mainloop() method ensures the main window continues to
display and run until you close it.
Typically, in a Tkinter program, you place the call to the mainloop() method
as the last statement after creating the widgets.
Tkinter Widgets
Tkinter Widgets
Tkinter Widgets
Tkinter
Tkinter
Tkinter
Tkinter Events are generally used to provide an interface that works as a bridge between
the User and the application logic.
We can use Events in any Tkinter application to make it operable and functional.
Tkinter events which are generally used for making the application interactive.
<Button> − Use the Button event in a handler for binding the Mouse wheels and Buttons.
<ButtonRelease> − Instead of clicking a Button, you can also trigger an event by
releasing the mouse buttons.
<Configure> − Use this event to change the widgets properties.
Destroy − Use this event to kill or terminate a particular widget.
<Enter> − It actually works like <return> event that can be used to get the focus on a
widget with mouse Pointer
<Expose> − The event occurs whenever a widget or some part of the application
becomes visible that covered by another window in the application.
<Focus In> − This event is generally used to get the focus on a particular widget.
<Focus Out> − To move the focus from the current widget.
<Key Press> − Start the process or call the handler by pressing the key.
<KeyRelease> − Start the process or call an event by releasing a key.
<Leave> − Use this event to track the mouse pointer when user switches from one widget
to another widget.
<Map> − Use Map event to show or display any widget in the application.
<Motion> − Track the event whenever the mouse pointer moves entirely within the
application.
Widgets Events
Layout Management
When you create graphical interfaces, the widgets in the window must have a way to
be arranged relative to each other.
For example, placing widgets can be accomplished using their relative positions to
other widgets or by defining their positions by specifying pixel locations.
In Tkinter there are three types of layout managers -- pack, place, and grid.
Geometry managers allow you to specify the positions of widgets inside a top-level or
parent window.
pack – show you how to use the pack geometry manager to arrange widgets on a
window.
grid – learn how to use the grid geometry manager to place widgets on a container.
place – show you how to use the place geometry manager to precisely position
widgets within its container using the
(x, y) coordinate system.
Tkinter widget size – understand how to control the size of the widget via the height
and width properties or the layout methods.
Widgets Events
The pack manager puts the widgets in horizontal and vertical boxes or blocks
in the parent window or widget.
Syntax:
widget.pack(options)
The possible options are
side: it represents the side to which the widget is to be placed on the
window. Side may be LEFT or RIGHT or TOP(default) or BOTTOM.
from tkinter import *
top = Tk()
top.geometry("300x200")
btn1 = Button(top, text = "Login")
btn1.pack( side = LEFT)
top.mainloop()
>>python tknpack.py
grid() method
Widgets Events
The grid() method organizes the widgets in the tabular form.
We can specify the rows and columns as the options in the method call.
This is a more organized way to place the widgets to the python application.

Syntax:
widget.grid (options)
The possible options are
• Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
• padx, pady It represents the number of pixels to pad the widget outside the widget's
border.
• row
The row number in which the widget is to be placed. The topmost row is represented
by 0
sticky -- specifies a value of S, N, E, W, or a combination of them
Widgets Events
grid() method:
The grid() method organizes the widgets in the tabular form.
We can specify the rows and columns as the options in the method call.
This is a more organized way to place the widgets to the python application.
Syntax:
widget.grid (options)
The possible options are
• Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
• padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
• row
The row number in which the widget is to be placed. The topmost row is represented
by 0
sticky -- specifies a value of S, N, E, W, or a combination of them
Widgets Events
Program
from tkinter import *
master = Tk()
# this will create a label widget
l1 = Label(master, text = "first")
l2 = Label(master, text = "second")
# grid method to arrange labels in respective
# rows and columns as specified
l1.grid(row = 0, column = 0, sticky = W, pady = 2)
l2.grid(row = 1, column = 0, sticky = W, pady = 2)
# entry widgets, used to take entry from user
e1 = Entry(master)
e2 = Entry(master)
# this will arrange entry widgets
e1.grid(row = 0, column = 1, pady = 2)
e2.grid(row = 1, column = 1, pady = 2)
mainloop()
Widgets Events
place() method:
The place() method organizes the widgets to the specific x and y coordinates.
Syntax:
widget.place(x,y)
• x, y: It refers to the horizontal and vertical offset in the pixels
To provide two keyword arguments, x and y, which specify the x- and y-coordinates
for the top-left corner of the widget. Both x and y are measured in pixels, not text
units.
import tkinter as tk
window = tk.Tk()
frame = tk.Frame(master=window, width=150, height=150)
frame.pack()
label1 = tk.Label(master=frame, text="I'm at (0, 0)", bg="red")
label1.place(x=0, y=0)
label2 = tk.Label(master=frame, text="I'm at (75, 75)", bg="yellow")
label2.place(x=75, y=75)
window.mainloop()
Program

import tkinter
from tkinter import *
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
tkinter.Checkbutton(top, text = "MachineLearning",variable=
CheckVar1,onvalue = 1, offvalue=0).grid(row=0,sticky=W)
tkinter.Checkbutton(top, text = "Deep Learning", variable =
CheckVar2, onvalue = 0, offvalue =1).grid(row=1,sticky=W)
top.mainloop()
Topic/Title: IDE & DATA VISUALIZATION

Name of the Paper : Programming in python


Semester : I
Department : Computer Science
Name of the Faculty : Dr.J.Vanathi
Designation : HEAD
UNIT – V
Introduction to Spyder
Spyder is an Integrated Development Environment (IDE) for scientific computing,
written in and for the Python programming language. It comes with an Editor to write
code, a Console to evaluate it and view the results at any time, a Variable Explorer to
examine the variables defined during evaluation, and several other facilities to help
you effectively develop the programs you need as a scientist.

Spyder IDE is an open-source integrated development environment (IDE) for Python


designed specifically for scientific computing. Spyder IDE includes a code editor,
console, debugger, and variable explorer, among other features, making it a powerful
and convenient tool for Python developers. Spyder IDE also supports many third-
party libraries commonly used in scientific computing and data analysis.
Introduction to Spyder

Installing Spyder IDE


Spyder IDE can be installed on Windows, macOS, and Linux operating
systems. There are several ways to install the software, and the process is
simple.

Running Python scripts in Spyder IDE


Once you have installed Spyder IDE, you can start writing and running
Python scripts. An environment for writing, testing, and debugging Python
code is provided by the Spyder IDE. The following steps outline how to
create a new Python script and run it in Spyder IDE:

Open the Spyder IDE application.


To create a new Python script, click the "New file" button on the toolbar or
choose "File" > "New file."
Introduction to Spyder

Fill out the new file using your Python code.


Save the file by going to "File" > "Save as" and give it a proper name with a
.py extension.
Click on the "Run" button on the toolbar or go to "Run" > "Run the file" to
run your Python script.
If your script has any errors, Spyder IDE will show the error message."
Spyder IDE has a console where you can see the output of your Python code.
By selecting the "Console" tab at the bottom of the Spyder IDE window, you
can access the console.
You can interact with the console and execute individual lines of code by
typing them directly into the console.
The Spyder IDE debugger can be used to debug your code. To start the
debugger, go to "Run" > "Debug file". This will open the debugger window.
You may place breakpoints in your code by clicking the line number adjacent
to the line where you wish to place the breakpoint in the debugger window.
Introduction to Spyder

The debugger will halt execution when your code reaches the breakpoint,
allowing you to step through your code line by line and check the values of
variables.
You can also use the variable explorer to view the values of variables in your
code. To open the variable explorer, go to "View" > "Variable explorer".
Spyder IDE also provides many other features to simplify your Python
development experiences, such as code completion, code highlighting, and
project management.
If you want to run Python scripts in Spyder IDE that require third-party
libraries, you can use the Anaconda package manager or pip to install the
required libraries.
Introduction to Spyder

To install a package using Anaconda, open the Anaconda Navigator


application, go to the "Environments" tab, select the environment where you
want to install the package, and search for the package in the search bar.
Click the "Install" button next to the package to install it.
To install a package using pip, open the terminal/command prompt and type
the following command:
pip install package_name
Once the package is installed, you can import it into your Python script and
use its functionality.
Open the Spyder IDE application. To create a new Python script, click the
"New file" button on the toolbar or choose "File" > "New file." Fill out the
new file using your Python code. Save the file by going to "File" > "Save as"
and give it a proper name with a.
Removing Variables from Environment
We can remove a variable by right-clicking it and selecting the option
Remove. After doing this, we can check in the IPython Console that the
variable was actually deleted. Finally, we are going to learn how to get help
for objects in two different ways.
Arithmetic and logical operators
Arithmetic operators in Python

These operators are used to perform mathematical operations on numeric


values.

The basic arithmetic operators include:

+ for addition
– for subtraction
* for multiplication
/ for division
% for modulus (remainder)
** for exponentiation or power
Arithmetic and logical operators

Logical operators in Python


These operators are used to perform logical operations and evaluate a
Boolean value (True or False).

The basic logical operators include:

and – True if both the operands are True.


or – True if at least one of the operands is True.
not – True if the operand is False and vice-versa.
Sequence data types and associated
operations
Sequence Data Types are used to store data in containers in the Python
computer language. The different types of containers used to store the data
are List, Tuple, and String. Lists are mutable and can hold data of any type,
whereas Strings are immutable and can only store data of the str type.
Pandas and data frame operations
Python Pandas Data operations
In Pandas, there are different useful data operations for DataFrame, which are
as follows :
Row and column selection
We can select any row and column of the DataFrame by passing the name of
the rows and column. When you select it from the DataFrame, it becomes
one-dimensional and considered as Series.
We can filter the data by providing some of the boolean expression in
DataFrame.
Null values
Pandas and data frame operations
A Null value can occur when no data is being provided to the items. The
various columns may contain no values which are usually represented as
NaN. In Pandas, several useful functions are available for detecting,
removing, and replacing the null values in Data Frame.
These functions are as follows:
isnull(): The main task of isnull() is to return the true value if any row has
null values.
notnull(): It is opposite of isnull() function and it returns true values for not
null value.
dropna(): This method analyzes and drops the rows/columns of null values.
fillna(): It allows the user to replace the NaN values with some other values.
replace(): It is a very rich function that replaces a string, regex, series,
dictionary, etc.
interpolate(): It is a very powerful function that fills null values in the
DataFrame or series.
Control structures using dataset

Control structures are commands that direct the flow of a program's execution
to process data. They are the building blocks of computer programs and are
used to make decisions about how to follow a path or another.

Sequence logic, or sequential flow


Selection logic, or conditional flow
Iteration logic, or repetitive flow
Numpy
• NumPy is a Python library used for working with arrays.
• It also has functions for working in domain of linear algebra, fourier transform,
and matrices.
• NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely.
• NumPy stands for Numerical Python.

Use NumPy
• In Python we have lists that serve the purpose of arrays, but they are slow to
process.
• NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
• The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
• Arrays are very frequently used in data science, where speed and resources are
very important.
Numpy
NumPy Faster Than Lists
NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called
ndarray.
We can create a NumPy ndarray object by using the array() function.
Numpy

Example
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

type(): This built-in Python function tells us the type of the object passed to
it. Like in above code it shows that arr is numpy.ndarray type.
Data visualization on dataset:
matplotlib, seaborn libraries
Data visualization is a crucial aspect of data analysis, enabling data scientists
and analysts to present complex data in a more understandable and insightful
manner. One of the most popular libraries for data visualization in Python is
Matplotlib.

Data Visualization With Pyplot in Matplotlib


Matplotlib provides a module called pyplot, which offers a MATLAB-like
interface for creating plots and charts. It simplifies the process of generating
various types of visualizations by offering a collection of functions that
handle common plotting tasks. Each function in Pyplot modifies a figure in a
specific way, such as:
Key Pyplot Functions
Seaborn libraries
Seaborn is a Python data visualization library based on matplotlib. It provides
a high-level interface for drawing attractive and informative statistical
graphics.

Seaborn is an amazing visualization library for statistical graphics plotting in


Python. It provides beautiful default styles and color palettes to make
statistical plots more attractive. It is built on top matplotlib library and is also
closely integrated with the data structures from pandas.

Seaborn aims to make visualization the central part of exploring and


understanding data. It provides dataset-oriented APIs so that we can switch
between different visual representations for the same variables for a better
understanding of the dataset.
Seaborn libraries
Different categories of plot in Seaborn
Plots are basically used for visualizing the relationship between variables.
Those variables can be either completely numerical or a category like a
group, class, or division.

Seaborn divides the plot into the below categories


Relational plots: This plot is used to understand the relation between two
variables.
Categorical plots: This plot deals with categorical variables and how they
can be visualized.
Distribution plots: This plot is used for examining univariate and bivariate
distributions
Regression plots: The regression plots in Seaborn are primarily intended to
add a visual guide that helps to emphasize patterns in a dataset during
exploratory data analyses.
Matrix plots: A matrix plot is an array of scatterplots.
Multi-plot grids: It is a useful approach to draw multiple instances of the
same plot on different subsets of the dataset.

You might also like