Write a Python program to create an array of 5 integers and display the array items. Access individual element through indexes.
from array import *
array_num = array('i', [1,3,5,7,9])
for i in array_num:
print(i)
print("Access first three items individually")
print(array_num[0])
print(array_num[1])
print(array_num[2])
Output:
1
3
5
7
9
Access first three items individually
1
3
5
Write a Python program to append a new item to the end of the array and insert the item to the specified position and reverese the order of array element.
from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: ",(array_num))
print("Append 11 at the end of the array:")
array_num.append(11)
print("New array: ",(array_num))
print("Insert new value 4 before 3:")
array_num.insert(1, 4)
print("New array: ",(array_num))
#reverse the array elements
array_num.reverse()
print("Reverse the order of the items:")
print("reversed array: ",(array_num))
Output:
Original array: array('i', [1, 3, 5, 7, 9])
Append 11 at the end of the array:
New array: array('i', [1, 3, 5, 7, 9, 11])
Insert new value 4 before 3:
New array: array('i', [1, 4, 3, 5, 7, 9, 11])
Reverse the order of the items:
reversed array: array('i', [11, 9, 7, 5, 3, 4, 1])
Write a Python program to get the number of occurrences of a specified element in an array.
from array import *
array_num = array('i', [1, 3, 5, 3, 7, 9, 3])
print("Original array: "+str(array_num))
print("Number of occurrences of the number 3 in the said array: ",(array_num.count(3)))
Output:
Original array: array('i', [1, 3, 5, 3, 7, 9, 3])
Number of occurrences of the number 3 in the said array: 3
Write a Python program to remove a specified item using the index from an array and to remove the first occurrence of a specified element from an array.
from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: ",(array_num))
print("Remove the third item form the array:")
array_num.pop(2)
print("New array: ",(array_num))
array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
print("Original array: "+str(array_num))
print("Remove the first occurrence of 3 from the said array:")
array_num.remove(3)
print("New array: "+str(array_num))
Output:
Original array: array('i', [1, 3, 5, 7, 9])
Remove the third item form the array:
New array: array('i', [1, 3, 7, 9])
Original array: array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Remove the first occurrence of 3 from the said array:
New array: array('i', [1, 5, 3, 7, 1, 9, 3])
Write a Python program to convert an array to an ordinary list with the same items.
from array import *
array_num = array('i', [1, 3, 5, 3, 7, 1, 9, 3])
print("Original array: "+str(array_num))
num_list = array_num.tolist()
print("Convert the said array to an ordinary list with the same items:")
print(num_list)
Output:
Original array: array('i', [1, 3, 5, 3, 7, 1, 9, 3])
Convert the said array to an ordinary list with the same items:
[1, 3, 5, 3, 7, 1, 9, 3]
Write a Python program to find the first duplicate element in a given array of integers. Return -1 If there are no such elements.
def find_first_duplicate(nums):
num_set = set()
no_duplicate = -1
for i in range(len(nums)):
if nums[i] in num_set:
return nums[i]
else:
num_set.add(nums[i])
return no_duplicate
print(find_first_duplicate([1, 2, 3, 4, 4, 5]))
print(find_first_duplicate([1, 2, 3, 4]))
print(find_first_duplicate([1, 1, 2, 3, 3, 2, 2]))
Output:
4
-1
1
Write a Python program to get the length of an array.
from array import array
num_array = array('i', [10,20,30,40,50])
print("Length of the array is:")
print(len(num_array))
Output:
Length of the array is:
5
Write a Python program to find the missing number in a given array of numbers between 10 and 20.
import array as arr
def test(nums):
return sum(range(10, 21)) - sum(list(nums))
array_num = arr.array('i', [10, 11, 12, 13, 14, 16, 17, 18, 19, 20])
print("Original array:")
for i in range(len(array_num)):
print(array_num[i], end=' ')
print("\nMissing number in the said array (10-20): ",test(array_num))
array_num = arr.array('i', [10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
print("\nOriginal array:")
for i in range(len(array_num)):
print(array_num[i], end=' ')
print("\nMissing number in the said array (10-20): ",test(array_num))
Output:
Original array:
10 11 12 13 14 16 17 18 19 20
Missing number in the said array (10-20): 15
Original array:
10 11 12 13 14 15 16 17 18 19
Missing number in the said array (10-20): 20
Write a bubble sort program.
# Creating a bubble sort function
def bubble_sort(list1):
# Outer loop for traverse the entire list
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))
Output:
The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]
Write a binary search program.
# Iterative Binary Search Function method Python Implementation
# It returns index of n in given list1 if present,
# else returns -1
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
while low <= high:
# for get integer result
mid = (high + low) // 2
# Check if n is present at mid
if list1[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif list1[mid] > n:
high = mid - 1
# If n is smaller, compared to the left of mid
else:
return mid
# element was not present in the list, return -1
return -1
# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45
# Function call
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
Output:
Element is present at index 4
Write a progfram to create a string.
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or docstrings.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Write a program to demostrate string indexing and slicing.
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is indexed as given in the below figure.
Program1:
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in Python to access the substring from the given string. Consider the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2, and so on. Consider the following image.
Program2:
# Given String
str = "PYTHON_PROGRAMMIONG"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-22])
Output:
PYTHON_PROGRAMMIONG
YTHO
TH
PYT
ON_
G
O
NG
ION
AMMIO
GNOIMMARGORP_NOHTYP
Traceback (most recent call last):
File "C:/Python31/W.PY", line 20, in <module>
print(str[-22])
IndexError: string index out of rangeTPO
Write a python program to reinitialize the string values.
Reassigning Strings:
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.
str = "HELLO"
print(str)
str = "hello"
print(str)
str = "HELLO"
str[0] = "h"
print(str)
Output:
HELLO
hello
Traceback (most recent call last):
File "C:/Python31/W.PY", line 6, in <module>
str[0] = "h"
TypeError: 'str' object does not support item assignment
Write a python program to delete the string values.
Deleting the String
As we know that strings are immutable. We cannot delete or remove the characters from the string. But we can delete the entire string using the del keyword.
str = "JAVATPOINT"
del str[1]
Output:
TypeError: 'str' object doesn't support item deletion
Now we are deleting entire string.
str1 = "JAVATPOINT"
del str1
print(str1)
Output:
NameError: name 'str1' is not defined
String Operators
Operator | Description |
+ | It is known as concatenation operator used to join the strings given either side of the operator. |
* | It is known as repetition operator. It concatenates the multiple copies of the same string. |
[] | It is known as slice operator. It is used to access the sub-strings of a particular string. |
[:] | It is known as range slice operator. It is used to access the characters from the specified range. |
in | It is known as membership operator. It returns if a particular sub-string is present in the specified string. |
not in | It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string. |
r/R | It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as "C://python". To define any string as a raw string, the character r or R is followed by the string. |
% | It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in python. We will discuss how formatting is done in python. |
Write a python program to perform different operations on strings.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
String Format:
we cannot combine strings and numbers like this:
Example 1:
age = 36
txt = "My name is John, I am " + age
print(txt)
Output:
Traceback (most recent call last):
File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int
But we can combine strings and numbers by using the format() method! The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are.
The format() method takes unlimited number of arguments, and are placed into the respective placeholders.
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders.
Write a python program to Use the format() method to insert numbers into strings.
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Output:
My name is John, and I am 36
I want 3 pieces of item 567 for 49.95 dollars.
I want to pay 49.95 dollars for 3 pieces of item 567.
String Methods:
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method | Description |
Converts the first character to upper case | |
Converts string into lower case | |
Returns a centered string | |
Returns the number of times a specified value occurs in a string | |
Returns an encoded version of the string | |
Returns true if the string ends with the specified value | |
Sets the tab size of the string | |
Searches the string for a specified value and returns the position of where it was found | |
Formats specified values in a string | |
format_map() | Formats specified values in a string |
Searches the string for a specified value and returns the position of where it was found | |
Returns True if all characters in the string are alphanumeric | |
Returns True if all characters in the string are in the alphabet | |
Returns True if all characters in the string are decimals | |
Returns True if all characters in the string are digits | |
Returns True if the string is an identifier | |
Returns True if all characters in the string are lower case | |
Returns True if all characters in the string are numeric | |
Returns True if all characters in the string are printable | |
Returns True if all characters in the string are whitespaces | |
Returns True if the string follows the rules of a title | |
Returns True if all characters in the string are upper case | |
Joins the elements of an iterable to the end of the string | |
Returns a left justified version of the string | |
Converts a string into lower case | |
Returns a left trim version of the string | |
Returns a translation table to be used in translations | |
Returns a tuple where the string is parted into three parts | |
Returns a string where a specified value is replaced with a specified value | |
Searches the string for a specified value and returns the last position of where it was found | |
Searches the string for a specified value and returns the last position of where it was found | |
Returns a right justified version of the string | |
Returns a tuple where the string is parted into three parts | |
Splits the string at the specified separator, and returns a list | |
Returns a right trim version of the string | |
Splits the string at the specified separator, and returns a list | |
Splits the string at line breaks and returns a list | |
Returns true if the string starts with the specified value | |
Returns a trimmed version of the string | |
Swaps cases, lower case becomes upper case and vice versa | |
Converts the first character of each word to upper case | |
Returns a translated string | |
Converts a string into upper case | |
Fills the string with a specified number of 0 values at the beginning |
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
Keys must be a single element
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Creating the dictionary:
Python provides the built-in function dict() method which is also used to create dictionary. The empty curly braces {} is used to create empty dictionary. The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and each key is separated from its value by the colon (:).The syntax to define the dictionary is given below.
Syntax:
Dict = {"Name": "Tom", "Age": 22}
Note: In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
1. write a program to create a dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Java', 2: 'python', 3:'network'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
#Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
#String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(thisdict)
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output:
Empty Dictionary:
{}
Create Dictionary by using dict():
{1: 'Java', 2: 'python', 3: 'network'}
Dictionary with each item as a pair:
{1: 'Devansh', 2: 'Sharma'}
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
{'brand': 'Ford', 'colors': ['red', 'white', 'blue'], 'electric': False, 'year': 1964}
<class 'dict'>
printing Employee data ....
{'salary': 25000, 'Age': 29, 'Company': 'GOOGLE', 'Name': 'John'}
2. write a program to create and Accesses the dictionary values.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
#for loop to print the values of the dictionary by using values() method.
for x in Employee.values():
print(x)
#for loop to print the items of the dictionary by using items() method.
for x in Employee.items():
print(x)
#Get a list of the keys:
x = Employee.keys()
print(x)
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
25000
29
John
('salary', 25000)
('Age', 29)
('Company', 'GOOGLE')
('Name', 'John')
dict_keys(['salary', 'Age', 'Company', 'Name'])
Adding dictionary values:
The dictionary is a mutable data type, and its values can be updated by using the specific keys. The value can be updated along with key Dict[key] = value. The update() method is also used to update an existing value.
Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the dictionary.
3. write a program to add new item and update the dictionary values.
# Creating an empty Dictionary
employee = {}
print("Empty Dictionary: ")
print(employee)
# Adding elements to dictionary one at a time
employee[0] = 'Peter'
employee[2] = 'Joseph'
employee[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(employee)
# Adding set of values
# with a single Key
# The Emp_ages doesn't exist to dictionary
employee['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(employee)
# Updating existing Key's Value
employee[3] = 'karan'
print("\nUpdated key value: ")
print(employee)
#using update( ) method inserting new item to dictionary
employee.update({1:'pavan'})
print(employee)
#using update( ) method updating the existing value
employee.update({0:'charan'})
print(employee)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}
Updated key value:
{0: 'Peter', 2: 'Joseph', 3: 'karan', 'Emp_ages': (20, 33, 24)}
{0: 'Peter', 1: 'pavan', 2: 'Joseph', 3: 'karan', 'Emp_ages': (20, 33, 24)}
{0: 'charan', 1: 'pavan', 2: 'Joseph', 3: 'karan', 'Emp_ages': (20, 33, 24)}
Deleting elements using del keyword:
The items of the dictionary can be deleted by using the del keyword as given below.
4. write a program to delete the items from the dictionary values.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
#The pop() method removes the item with the specified key name:
print("create a new dictionary")
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
#The popitem() method removes the last inserted item (in versions before 3.7, a random item is #removed instead):
thisdict.popitem()
print(thisdict)
thisdict.clear()
print(thisdict)
print("Deleting the dictionary: Employee")
del Employee
print("Lets try to print it again ")
print(Employee)
Output:
<class 'dict'>
printing Employee data ....
{'salary': 25000, 'Age': 29, 'Company': 'GOOGLE', 'Name': 'John'}
Deleting some of the employee data
printing the modified information
{'salary': 25000, 'Age': 29}
create a new dictionary
{'brand': 'Ford', 'year': 1964}
{'year': 1964}
{}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "C:/Python31/r.py", line 27, in <module>
print(Employee)
NameError: name 'Employee' is not defined
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
5. write a program to demostrate the nesting of dictionaries.
#Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
#Or, if you want to add three dictionaries into a new dictionary:
#Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
Output:
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Python Function
Functions are the most important aspect of an application. A function can be defined as the organized block of reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the Python program.
The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the program grows, function makes the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions, which can be called user-defined functions.
There are mainly two types of functions.
User-define functions - The user-defined functions are those define by the user to perform the specific task.
Built-in functions - The built-in functions are those functions that are pre-defined in Python.
In this tutorial, we will discuss the user define functions.
Advantage of Functions in Python
There are the following advantages of Python functions.
Using functions, we can avoid rewriting the same logic/code again and again in a program.
We can call Python functions multiple times in a program and anywhere in a program.
We can track a large Python program easily when it is divided into multiple functions.
Reusability is the main achievement of Python functions.
However, Function calling is always overhead in a Python program.
Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is given below.
Syntax:
def my_function(parameters):
function_block
return expression
Let's understand the syntax of functions definition.
The def keyword, along with the function name is used to define the function.
The identifier rule must follow the function name.
A function accepts the parameter (argument), and they can be optional.
The function block is started with the colon (:), and block statements must be at the same indentation.
The return statement is used to return the value. A function can have only one return
Write a Python function to calculate the sum of two variables.
#Python function to calculate the sum of two variables
#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = int(input("Enter a: "))
b = int(input("Enter b: "))
#printing the sum of a and b
print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
Python pass by reference vs pass by value:
Pass by reference – It is used in some programming languages, where values to the argument of the function are passed by reference which means that the address of the variable is passed and then the operation is done on the value stored at these addresses.
When we pass something by reference any change we make to the variable inside the function then those changes are reflected to the outside value as well.
Python program for Passing Immutable Object (List)
#defining the function
def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]
#calling the function
change_list(list1)
print("list outside function = ",list1)
Output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
Pass by value – It means that the value is directly passed as the value to the argument of the function. Here, the operation is done on the value and then the value is stored at the address. Pass by value is used for a copy of the variable.
When we pass something by value then the changes made to the function or copying of the variable are not reflected back to the calling function.
Python program for Passing mutable Object(strings)
#defining the function
def change_string (str):
str = str + " Hows you "
print("printing the string inside function :",str)
string1 = "Hi I am there"
#calling the function
change_string(string1)
print("printing the string outside function :",string1)
Output:
printing the string inside function : Hi I am there Hows you
printing the string outside function : Hi I am there
Write a program to calculate the SI.
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount: 5000
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0
Write a Python program to pass the default arguments to a function.
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
printme(age = 10,name="David")
Output:
My name is john and age is 22
My name is David and age is 10
Write a Python program to pass the variable length arguments to a function.
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")
Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
john
David
smith
nick
Write a Python program to use **kwargs in a function.
Python provides the facility to pass the multiple keyword arguments which can be represented as **kwargs. It is similar as the *args but it stores the argument in the dictionary format.
This type of arguments is useful when we do not know the number of arguments in advance.
def food(**kwargs):
print(kwargs)
food(a="Apple")
food(fruits="Orange", Vagitables="Carrot")
Output:
{'a': 'Apple'}
{'fruits': 'Orange', 'Vagitables': 'Carrot'}
Write a python program to calculate the sum of 3 numbers.
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output:
Output:
The sum is 60
Value of sum outside the function: 0
Write a python program to Calculate Factorial of given number using recursion function.
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
factorial(4)
Output:
24
sets
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can remove items and add new items.
Duplicates Not Allowed
Sets cannot have two items with the same value. Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also provides the set() method, which can be used to create the set by the passed sequence.
Write a python program to create a set.
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))
# Empty set using set() function
set4 = set()
print(type(set4))
#using curly braces.
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
#using set( ) method.
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Output:
<class 'dict'>
<class 'set'>
{'Monday', 'Tuesday', 'Friday', 'Wednesday', 'Thursday', 'Sunday', 'Saturday'}
<class 'set'>
looping through the set elements ...
Monday
Tuesday
Friday
Wednesday
Thursday
Sunday
Saturday
{'Monday', 'Tuesday', 'Friday', 'Wednesday', 'Thursday', 'Sunday', 'Saturday'}
<class 'set'>
looping through the set elements ...
Monday
Tuesday
Friday
Wednesday
Thursday
Sunday
Saturday
Python Built-in set methods
Python contains the following methods to be used with the sets.
SN | Method | Description |
1 | It adds an item to the set. It has no effect if the item is already present in the set. | |
2 | clear() | It deletes all the items from the set. |
3 | copy() | It returns a shallow copy of the set. |
4 | Difference_update(....) | It modifies this set by removing all the items that are also present in the specified sets. |
5 | It removes the specified item from the set. | |
6 | intersection() | It returns a new set that contains only the common elements of both the sets. (all the sets if more than two are specified). |
7 | Intersection_update(....) | It removes the items from the original set that are not present in both the sets (all the sets if more than one are specified). |
8 | Isdisjoint (....) | Return True if two sets have a null intersection. |
9 | Issubset(....) | Report whether another set contains this set. |
10 | Issuperset(....) | Report whether this set contains another set. |
11 | Remove and return an arbitrary set element that is the last element of the set. Raises KeyError if the set is empty. | |
12 | Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. | |
13 | symmetric_difference(....) | Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. |
14 | symmetric_difference_update(....) | Update a set with the symmetric difference of itself and another. |
15 | union(....) | Return the union of sets as a new set. |
16 | update() | update() method is used to add multiple elements to the set. |
Write a python program to add members in a set.
Python provides the add() method and update() method which can be used to add some particular item to the set. The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Consider the following example.
Definition and Usage of add():
The add() method adds an element to the set.
If the element already exists, the add() method does not add the element.
Syntax:
set.add(elmnt)
Parameter | Description |
elmnt | Required. The element to add to the set |
To add more than one item in the set, Python provides the update() method. It accepts iterable as an argument.
Definition and Usage of update():
The update() method updates the current set, by adding items from another set (or any other iterable).
If an item is present in both sets, only one appearance of this item will be present in the updated set.
Syntax:
set.update(set)
Parameter | Description |
set | Required. The iterable insert into the current set |
months1= set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months1)
print("\nAdding other months to the set...");
months1.add("July");
months1.add ("August");
print("\nPrinting the modified set...");
print(months1)
print("\nlooping through the set elements ... ")
for i in months1:
print(i)
months2= set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months2)
print("\nupdating the original set ... ")
months2.update(["July","August","September","October"]);
print("\nprinting the modified set ... ")
print(months2)
Output:
printing the original set ...
{'February', 'March', 'May', 'January', 'June', 'April'}
Adding other months to the set...
Printing the modified set...
{'February', 'March', 'August', 'May', 'January', 'June', 'April', 'July'}
looping through the set elements ...
February
March
August
May
January
June
April
July
printing the original set ...
{'February', 'March', 'May', 'January', 'June', 'April'}
updating the original set ...
printing the modified set ...
{'February', 'October', 'March', 'August', 'May', 'January', 'June', 'September', 'April', 'July'}
Write a program to remove the item from set.
Removing items from the set
Python provides the discard() method and remove() method which can be used to remove the items from the set. The difference between these function, using discard() function if the item does not exist in the set then the set remain unchanged whereas remove() method will through an error. The remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
Syntax
set.remove(item)
Parameter | Values |
item | Required. The item to search for, and remove |
remove( ) method:
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
Output:
printing the original set ...
{'February', 'March', 'May', 'January', 'June', 'April'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'June', 'April'}
discard( ) method:
The discard() method removes the specified item from the set. This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
Syntax:
set.discard(value)
Parameter | Values |
value | Required. The item to search for, and remove |
discard( ) method:
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)
print("\nlooping through the set elements ... ")
for i in months:
print(i)
Output:
printing the original set ...
{'February', 'January', 'March', 'April', 'June', 'May'}
Removing some months from the set...
Printing the modified set...
{'February', 'March', 'April', 'June'}
looping through the set elements ...
February
March
April
June
Difference between discard() and remove():
Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove(). If the key to be deleted from the set using discard() doesn't exist in the set, the Python will not give the error. The program maintains its control flow. On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the Python will raise an error.
Difference between discard() and remove():
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving items through discard() method...");
Months.discard("Feb"); #will not give an error although the key feb is not available in the set
print("\nprinting the modified set...")
print(Months)
print("\nRemoving items through remove() method...");
Months.remove("Jan") #will give an error as the key jan is not available in the set.
print("\nPrinting the modified set...")
print(Months)
Output:
printing the original set ...
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through discard() method...
printing the modified set...
{'March', 'January', 'April', 'June', 'February', 'May'}
Removing items through remove() method...
Traceback (most recent call last):
File "set.py", line 9, in
Months.remove("Jan")
KeyError: 'Jan'
Python Set Operations
Union of two Sets
The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all the items that are present in both the sets. Python also provides the union() method which can also be used to calculate the union of two sets.
union() method:
The union() method returns a set that contains all items from the original set, and all items from the specified set(s). You can specify as many sets you want, separated by commas. It does not have to be a set, it can be any iterable object. If an item is present in more than one set, the result will contain only one appearance of this item.
Syntax:
set.union(set1, set2...)
Parameter | Description |
set1 | Required. The iterable to unify with |
set2 | Optional. The other iterable to unify with. You can compare as many iterables as you like. Separate each iterable with a comma |
Write a program to calculate the union of two sets.
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Monday', 'Tuesday', 'Friday', 'Wednesday', 'Thursday', 'Sunday', 'Saturday'}
{'Sunday', 'Monday', 'Tuesday', 'Friday', 'Wednesday', 'Thursday', 'Saturday'}
Intersection of two sets:
The intersection of two sets can be performed by the and & operator or the intersection() function. The intersection of the two sets is given as the set of the elements that common in both sets.
intersection() method
The intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets
Syntax:
set.intersection(set1, set2 ... etc)
Parameter Values
Parameter | Description |
set1 | Required. The set to search for equal items in |
set2 | Optional. The other set to search for equal items in. You can compare as many sets you like. Separate the sets with a comma |
The intersection_update() method
The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified). The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set.
Syntax:
set.intersection_update(set1, set2 ... etc)
Parameter Values:
Parameter | Description |
set1 | Required. The set to search for equal items in |
set2 | Optional. The other set to search for equal items in.You can compare as many sets you like. Separate the sets with a comma |
Write a program to calculate the intersection of two sets.
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
Output:
{'Tuesday', 'Monday'}
{'Martin', 'David'}
{1, 2, 5}
{'castle'}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or difference()method. Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B.
difference() method:
The difference() method returns a set that contains the difference between two sets. Meaning: The returned set contains items that exist only in the first set, and not in both sets.
Syntax:
set.difference(set)
Parameter Values
Parameter | Description |
set | Required. The set to check for differences in |
difference_update() method:
The difference_update() method removes the items that exist in both sets. The difference_update() method is different from the difference() method, because the difference() method returns a new set, without the unwanted items, and the difference_update() method removes the unwanted items from the original set.
Syntax:
set.difference_update(set)
Parameter Values
Parameter | Description |
set | Required. The set to check for differences in |
Write a program to calculate the Difference between the two sets
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y)
print(x)
Output:
{'Wednesday', 'Thursday'}
{'Wednesday', 'Thursday'}
{'cherry', 'banana'}
Symmetric Difference of two sets:
The symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method. Symmetric difference of sets, it removes that element which is present in both sets.
symmetric_difference() method
The symmetric_difference() method returns a set that contains all items from both set, but not the items that are present in both sets. Meaning: The returned set contains a mix of items that are not present in both sets.
Syntax:
set.symmetric_difference(set)
Parameter Values:
Parameter | Description |
set | Required. The set to check for matches in |
symmetric_difference_update() method:
The symmetric_difference_update() method updates the original set by removing items that are present in both sets, and inserting the other items.
Syntax
set.symmetric_difference_update(set)
Parameter Values
Parameter | Description |
set | Required. The set to check for matches in |
Write a program to calculate the Symmetric Difference of two sets
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
Output:
{3, 4, 5, 6, 8, 9, 10}
{3, 4, 5, 6, 8, 9, 10}
{'cherry', 'google', 'banana', 'microsoft'}
Set comparisons:
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is returned depending upon the items present inside the sets.
Write a program for Set comparisons
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
Output:
True
False
False
Write a python program to create a tuple.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the small () brackets. The parentheses are optional but it is good practice to use. A tuple can be defined as follows.
Creating a tuple with single element:
Creating a tuple with single element is slightly different. We will need to put comma after the element to declare the tuple.
Program:
Output:
Write a python program to demonstrate Tuple indexing.
Output:
Output
Write a python program to demonstrate Tuple indexing and slicing.
A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using their specific index value.
The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Negative Indexing:
The tuple element can also access by using negative indexing. The index of -1 denotes the rightmost element and -2 to the second last item and so on.
The elements from left to right are traversed using the negative indexing.
Program:
Output:
Write a python program to demonstrate packing and unpacking of Tuple.
Unpacking a Tuple:
When we create a tuple, we normally assign values to it. This is called "packing" a tuple.
But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking"
Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list:
If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.
Program:
Output:
Write a program to add an item in a tuple.
Output:
Write a program to remove an item from a tuple.
Output:
