Programming in Python- Unit1-Merged
Programming in Python- Unit1-Merged
To write and run (execute) a Python program, we need to have a Python interpreter
The symbol >>> is the Python prompt, which indicates that the interpreter is ready
In the script mode, we can write a Python program in a file, save it and then use the
Python scripts are saved as files where file name has extension “.py”.
While working in the script mode, after saving the file, click [Run]->[Run Module]
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.
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
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
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).
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
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
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)
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
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
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
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
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.
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
String Creation
S1 = “ Python Programming Language”
S1 = ‘Python Programming Language’
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
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:])
Example
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)
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
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)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Topic/Title: GUI in Python using Tkinter
• Among various GUI Frameworks, Tkinter is the only framework that is built-in
into Python's Standard Library.
• 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
import tkinter
top = tkinter.Tk()
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
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
+ for addition
– for subtraction
* for multiplication
/ for division
% for modulus (remainder)
** for exponentiation or power
Arithmetic and logical operators
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.
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.
Example
import numpy as np
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.