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

Dictionary Tuples Functions

Dictionaries in Python are collections that store data in key:value pairs, are ordered as of Python 3.7, and are mutable, meaning items can be changed, added, or removed. They do not allow duplicate keys, and values can be of any data type. The document also covers basic operations, properties, and practical applications of dictionaries, such as counting occurrences of words in a file.

Uploaded by

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

Dictionary Tuples Functions

Dictionaries in Python are collections that store data in key:value pairs, are ordered as of Python 3.7, and are mutable, meaning items can be changed, added, or removed. They do not allow duplicate keys, and values can be of any data type. The document also covers basic operations, properties, and practical applications of dictionaries, such as counting occurrences of words in a file.

Uploaded by

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

UNIT-3

Dictionaries
Introduction
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered, changeable and do not
allow duplicates.
• Dictionaries are written with curly brackets, and have keys and
values:
Example: Output:
Dictionary Items

Dictionary items are presented in key:value pairs, and can be referred


to by using the key name.

Example: Output:
Dictionary Basics
d1 = {} Empty dictionary
d2 = {‘spam’ : 2, ‘eggs’ : 3} Two-item dictionary
d3 = {‘food’ : {‘ham’ : 1, ‘egg’ : 2}} Nesting
d2[‘eggs’], d3[‘food’][‘ham’] Indexing by key
d2.keys(), d2.values() Methods: membership test, keys list, values
list, etc.
len(d1) Length (number stored entries)
d2[key] = new, del d2[key] Adding/changing, deleting
Dictionaries Basics
Comparing Lists and Dictionaries
Dictionaries are like lists except that they use keys instead of positions to look up values

>>> lst = list() >>> ddd = dict()


>>> lst.append(21) >>> ddd['age'] = 21
>>> lst.append(183) >>> ddd['course'] = 182
>>> print(lst) >>> print(ddd)
[21, 183] {'age': 21, 'course': 182}
>>> lst[0] = 23 >>> ddd['age'] = 23
>>> print(lst) >>> print(ddd)
[23, 183] {'age': 23, 'course': 182}

Dept. of ISE 5
Basic operations

Dept. of ISE 6
Dictionary properties
•They are mutable.
•They do not allow duplicates to be stored.
•The keys and values can be of any data type.
•The keys are always unique.
Dictionary
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 do not have a defined order, you cannot refer to an
item by using an index.
Dictionary …
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:

Duplicate values will overwrite existing values:


Example:
Dictionary Length

To determine how many items a dictionary has, use the len() function:
Print the number of items in the dictionary:
Dictionary Items - with Data Types

The values in dictionary items can be of any data type:


Dictionary …
type()
From Python's perspective, dictionaries are defined as objects with
the data type 'dict':
Creating a dictionary using dict()
Using the dict() method to make a dictionary:

The function dict creates a new dictionary with no items. Because dict is the
name of a built-in function, you should avoid using it as a variable name.

The curly brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use
square brackets:
Different ways of creating a dictionary
Access Dictionary Items
You can access the items of a dictionary by referring to its key name, inside square brackets:

There is also a method called get() that will give you the same result:
Get keys, Get values from a dictionary
in operator
The in operator works on dictionaries; it tells you whether something
appears as a key in the dictionary (appearing as a value is not good
enough).

To see whether something appears as a value in a dictionary, you can


use the method values, which returns the values as a list, and then use
the in operator:
Dictionary as a set of counters
Suppose you are given a string and you want to count how many times each letter appears.
There are several ways you could do it:
● You could create 26 variables, one for each letter of the alphabet. Then you could
traverse the string and, for each character, increment the corresponding counter,
probably using a chained conditional.
● You could create a list with 26 elements. Then you could convert each character to a
number (using the built-in function ord), use the number as an index into the list, and
increment the appropriate counter.
● You could create a dictionary with characters as keys and counters as the corresponding
values. The first time you see a character, you would add an item to the dictionary. After
that you would increment the value of an existing item.
An advantage of the dictionary implementation is that, we don’t have to know ahead of time
which letters appear in the string and we only have to make room for the letters that do
appear.
Dictionaries and files
One of the common uses of a dictionary is to count the occurrence of words in a file
with some written text.
Let’s start with a very simple file of words taken from the text of Romeo and Juliet.

But soft what light through yonder window breaks


It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

We will write a Python program to read through the lines of the file, break each line
into a list of words, and then loop through each of the words in the line and count
each word using a dictionary.
Write a program to count the occurrence of words in a file with some written text

fname = input('Enter the file name: ')


try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()

counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1

print(counts)
Looping and dictionaries
If you use a dictionary as the sequence in a for statement, it traverses
the keys of the dictionary.
This loop prints each key and the corresponding value:

Output:
chuck 1
annie 42
jan 100
Loop Through a Dictionary
Print all key names in the dictionary, one by one:
Print all values in the dictionary, one by one:
We can also use the values() function to return values
of a dictionary:
Loop through both keys and values, by using the
items() function
For example, if we wanted to find all the entries in a dictionary
with a value above ten, we could write the following code:
Write a python code to print the keys in alphabetical order.
To print the keys in alphabetical order, you first make a list of the keys in the dictionary
using the keys method available in dictionary objects, and then sort that list and loop
through the sorted list, looking up each key and printing out key-value pairs in sorted order.
Advanced text parsing
import string
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for line in fhand:
line = line.rstrip()
# First two parameters are empty strings
line = line.translate(line.maketrans("", "", string.punctuation))
line = line.lower()
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)
Advanced text parsing(Contd.)
Input File: romeo.txt
But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,
Output:
Advanced text parsing(Contd.)
● Since the Python split function looks for spaces and treats words as tokens separated by
spaces, we would treat the words “soft!” and “soft” as different words and create a
separate dictionary entry for each word.
● Also since the file has capitalization, we would treat “who” and “Who” as different words
with different counts.
● We can solve both these problems by using the string methods lower, punctuation, and
translate.
● The translate is the most subtle of the methods.
○ line.translate(str.maketrans(fromstr, tostr, deletestr))
● Replace the characters in fromstr with the character in the same position in tostr and
delete all characters that are in deletestr.
● The fromstr and tostr can be empty strings and the deletestr parameter can be omitted.
● We will use the deletechars parameter to delete all of the punctuation.
● To know the list of characters that Python considers “punctuation”
>>> import string Output:
>>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
Lab programs on Dictionary
1. Write a program to count the numbers of occurrence of each character in the string and
store them in a dictionary data structure.
2. Write a program to use split and join methods in the string and trace a birthday with a
dictionary data structure.
3. Write a program that combines two lists into a dictionary.
Lab programs on Dictionary
Write a program to use split and join methods in the string and trace a birthday with a dictionary data structure.
Lab programs on Dictionary
Write a program that combines two lists into a dictionary.

keys = ['a', 'b', 'c','d']


values = [1, 2, 3]

if len(keys) != len(values):
print("The two lists must have the same length.")
else:
combined_dict = {}
for i in range(len(keys)):
combined_dict[keys[i]] = values[i]
print(combined_dict)
Lab programs on Dictionary
Write a program that combines two lists into a dictionary.
# Two lists to combine into a dictionary
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']

combined_dict = {}

for i in range(len(keys)):
combined_dict[keys[i]] = values[i]

print("Combined dictionary:", combined_dict)

Combined dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}


Lab programs on Dictionary
word = 'Python Programming'
d = dict()
for c in word:
if c==' ':
continue
elif c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)

{'P': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 1}
Programs
Write a program to find the sum and average of dictionary values.
In a class of 10 students, it is required to store the marks scored along
with their USNs. Use an appropriate data structure to store the marks.
Also, retrieve the students who have scored marks above average.
Given a list of names, create a dictionary with key as a starting letter and
value as all names starting with that letter.
Merge the contents of 2 dictionaries.
Sort the elements in the dictionary based on the keys.
Add a key value pair at the beginning of the given dictionary.
Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are the square of the
keys.
Programs
1. Add a key value pair at the beginning of the given dictionary

d1={'name':'John','Dept':'Advertising','salary':50000}
key=input("Enter the key to be added ")
value=input("Enter the value ")
d2={}
d2[key]=value
for key in d1: Enter the key to be added place
d2[key]=d1[key] Enter the value Bengaluru
print(d2) {'place': 'Bengaluru', 'name': 'John', 'Dept': 'Advertising', 'salary': 50000}
Programs
Merge the contents of 2 dictionaries.
Programs
Sort the elements in the dictionary based on the keys

myDict = {'Kavi': 10, 'Rajnish': 9, 'Sanjeev': 15, 'Yash': 2, 'Suraj': 32}

myKeys = list(myDict.keys())
myKeys.sort()
sorted_dict=dict()

for key in myKeys:


print(key,myDict[key])
sorted_dict[key]=myDict[key]

print(sorted_dict)
Programs
Write a program to find the sum and average of dictionary values
data = { "key1": 10, "key2": 20, "key3": 30,
"key4": 40}

values_sum = sum(data.values())

values_avg = values_sum / len(data)

print("Sum of dictionary values:", values_sum)


print("Average of dictionary values:", values_avg)
Programs
In a class of 10 students, it is required to store the marks scored along with their USNs. Use an appropriate
data structure to store the marks. Also, retrieve the students who have scored marks above average
Programs
Given a list of names, create a dictionary with key as a starting letter and value as all names starting with that letter.

my_string=input("Enter the string :") namelist=['anuj','ankit','arjun','bhavya','bharat','chetan','chirag','abhay','dhruv']


d={}
split_string = my_string.split() for name in namelist:
key=name[0]
my_dict={} if key not in d:
d[key]=[]
for elem in split_string: d[key].append(name)
if(elem[0] not in my_dict.keys()): print(d)
my_dict[elem[0]]=[]
Output:
my_dict[elem[0]].append(elem) {'a': ['anuj', 'ankit', 'arjun', 'abhay'], 'b': ['bhavya', 'bharat'], 'c': ['chetan', 'chirag'],
'd': ['dhruv']}
else:
if(elem not in my_dict[elem[0]]):
my_dict[elem[0]].append(elem)
Output:
print("The dictionary created is") Enter the string :hello how are you man
for k,v in my_dict.items(): The dictionary created is
h : ['hello', 'how']
print(k,":",v) a : ['are']
y : ['you']
m : ['man']
Programs
Write a Python script to print a dictionary where the keys are numbers between 1 and 10 (both included) and the values are the
square of the keys.

d = dict()
for x in range(1, 11):
d[x] = x ** 2
print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Write a Python script to print a dictionary where the keys are based on the length of the strings from the list.

l1=['anuj','atith','ajith','bhuvi','dhruv','Vani','Rani','Rajeshwari']
d={}
for name in l1:
length=len(name)
if length not in d:
d[length]=[]
d[length].append(name)
print(d)
{4: ['anuj', 'Vani', 'Rani'], 5: ['atith', 'ajith', 'bhuvi', 'dhruv'], 10: ['Rajeshwari']}
Chapter 2: Tuples
Tuples
•Tuples are a sequence of values separated by commas.
•The values stored in the tuple can be of any type.
•They can be indexed by integers just like list.
•Tuples are immutable unlike lists.
•Defining tuples:
t=‘a’,’b’,’c’
or
t=(‘a’,’b’,’c’)
To create a tuple with a single element, you have
to include the final comma:

Without the comma Python treats (‘a’) as an expression


with a string in parentheses that evaluates to a string:
Another way to construct a tuple is the built-in function tuple.

If the argument is a sequence (string,


With no argument, it creates an list, or tuple), the result of the call to
empty tuple: tuple is a tuple with the elements of the
sequence:
Tuple
A tuple is accessed in the same way as a list.
But if we try to modify one of the elements of the tuple, we get an
error:

We can’t modify the elements of a tuple, but we can replace one tuple
with another:
Comparing Tuples
In Python, tuples are compared lexicographically, meaning they are compared element
by element, starting from the first one. When comparing two tuples:
1. Python first compares the first elements of each tuple.
2. If the first elements are equal, it proceeds to compare the second elements.
3. This process continues until a pair of elements is found that is not equal, or one
of the tuples ends.

For example:
Here, the first elements are both 0. Since they are equal, Python
moves to compare the second elements. The second element of
the first tuple, 3, is less than the second element of the second
tuple, 4. Therefore, (0, 3, 4) is considered smaller than (0, 4, 5).
Comparing Tuples …
Here, the first elements are both 0, and the second
● Similarly, elements are 3 and 4, respectively. Since 3 is less
than 4, the first tuple is considered smaller.

In this case, both tuples start with 0, 1, and 2, and the


first tuple has an additional element, 3. Since the
second tuple ends earlier, it is considered smaller.

Both tuples start with 1, 2, and 3. The second tuple


has an additional element, 4. Since it extends
further, the first tuple is considered smaller.

Remember, if any element comparison is true, the whole comparison is


considered true, and Python stops further comparison.
Comparing Tuples
Tuple Assignment
Python allows tuple to be written on the left side of the
assignment operator.

- The assignment takes place


element by element from right
hand side to left hand side.
- Given an e-mail id, find the username and the domain name.
Dictionaries and Tuples
•We can create a list of key-value pairs, using the items()
function.
•In this list, each element is a tuple.
Sorting dictionary elements by Key.
- Consider the below example:
d={2:200,4:2399,1:3748}

- Hence, converting a dictionary to a list of tuples, is a way


to output the contents of a dictionary sorted by key.
Multiple Assignment with Dictionaries

For each iteration through the loop, both key and value are advanced to
the next key-value pair in the dictionary.
Sorting the Dictionary by values

Output:
Count the occurrences of words
Given a text file, write a program to count the number of occurrences of
each word in it.
- We make use of string translate(), to remove any punctuation marks in the
text.
- Syntax:
string.translate(table)
- Here, the table is a mapping table, that contains the ‘from’ pattern and the
to ‘pattern’.
- To create this mapping table, we make use of the maketrans() function.
D1= str.maketrans(x, y, z)
- If only one parameter is mentioned, it must be a dictionary containing the
mapping of values.
- If x and y mentioned, the x will be replaced with y.
- z is the value that needs to be deleted from the string.
- Returns a dictionary containing a mapping of key values. Each key will be
replaced with the corresponding value.
Convert tuple into a dictionary

Output:
Remove empty tuple from a list of tuples

Output:
List Tuple
[] ()

List are mutable Tuples are immutable

Iterations are time-consuming Iterations are comparatively Faster

Inserting and deleting items is easier with a list. Accessing the elements is best accomplished with a tuple
data type.

Lists consume more memory Tuple consumes less than the list

Lists have several built-in methods. A tuple does not have many built-in methods because of
immutability

A unexpected change or error is more likely to occur in In a tuple, changes and errors don't usually occur
a list because of immutability.

If the content is not fixed keeps on changing, then it is If the content is fixed, then it is better to opt list.
better to opt list Ex: name, usn, emp_id, latitude and longitude of a
Ex: student marks, age, employee salary, weather, location
List Tuple Dictionaries
A list is a non-homogeneous data A Tuple is also a A dictionary is also a non-homogeneous data
structure that stores the elements in non-homogeneous data structure structure that stores key-value pairs.
columns of a single row or multiple that stores elements in columns
rows. of a single row or multiple rows.

The list can be represented by [ ] Tuple can be represented by ( ) The dictionary can be represented by { }

The list allows duplicate elements Tuple allows duplicate elements The dictionary doesn’t allow duplicate keys.

Example: [1, 2, 3, 4, 5] Example: (1, 2, 3, 4, 5) Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”}

A list can be created using the list() Tuple can be created using the A dictionary can be created using the dict()
function tuple() function. function.

A list is mutable i.e we can make any A tuple is immutable i.e we can A dictionary is mutable, ut Keys are not
changes in the list. not make any changes in the duplicated.
tuple.

List is ordered Tuple is ordered Dictionary is ordered (Python 3.7 and above)

Creating an empty list Creating an empty Tuple Creating an empty dictionary


l=[] t=() d={}
Programs
• Write a program to sort the list of words from longest to shortest.
• Write a Python program to add an item in a tuple.
• Write a Python program to convert a tuple to a string.
• Write a Python program to get the 4th element and 4th element from last of a tuple.
• Write a Python program to find the repeated items of a tuple.
• Write a Python program to check whether an element exists within a tuple.
• Write a Python program to convert a list to a tuple.
• Write a Python program to remove an item from a tuple.
• Write a Python program to find the index of an item of a tuple.
• Write a Python program to find the length of a tuple.
• Write a program to count the occurrence of each word in the given text file. And sort
the result based on the word length
Programs
Write a program to sort the list of words from longest to shortest.
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]

# Sort the list of words from longest to shortest


sorted_words = sorted(words, key=len, reverse=True)

print("Words sorted from longest to shortest:")


print(sorted_words)
Programs
Write a Python program to add an item in a tuple.
original_tuple = (1, 2, 3, 4, 5) original_tuple = (1, 2, 3, 4, 5)
new_item = 6 new_item = 6
updated_tuple = original_tuple + (new_item,)
temp_list = list(original_tuple) print(updated_tuple)
temp_list.append(new_item)
updated_tuple = tuple(temp_list)

print(updated_tuple)
Programs
Write a Python program to convert a tuple to a string.
original_tuple = ('a', 'b', 'c', 'd', 'e') tup = ('h', 'e', 'l', 'l', 'o')
str = ''
tuple_string = ''.join(original_tuple) for item in tup:
str = str + item
print(tuple_string) print(str)
Programs
Write a Python program to get the 4th element and 4th element from last of a tuple.
sample_tuple = (10, 20, 30, 40, 50, 60, 70, 80, 90, 100)

fourth_ele = sample_tuple[3]

fourth_from_last = sample_tuple[-4]

print("The 4th element is:", fourth_ele)


print("The 4th element from the last is:", fourth_from_last)
Programs
Write a Python program to find the repeated items of a tuple.
sample_tuple = (1, 2, 3, 2, 4, 5, 6, 3, 2, 7, 8, 6)

item_counts = {}

for item in sample_tuple:


if item in item_counts:
item_counts[item] += 1
else:
item_counts[item] = 1

repeated_items = []
for item, count in item_counts.items():
if count > 1:
repeated_items.append(item)

print("The repeated items are:", repeated_items)


Programs
Write a Python program to check whether an element exists within a tuple.
tuple = (10, 20, 30, 40, 50)
check = 30

if check in tuple:
print("The element exists in the tuple.")
else:
print("The element does not exist in the tuple.")

Write a Python program to convert a list to a tuple.

listx = [5, 10, 7, 4, 15, 3]


print(listx)
tuplex = tuple(listx)
print(tuplex)
Programs : Write a Python program to remove an item from a tuple.
tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
rm='c'
# Convert the 'tuplex' tuple to a list
listx = list(tuplex)
if 'c' in listx:
listx.remove("c")
# Convert the modified list back to a tuple to obtain 'tuplex' with the item removed
tuplex = tuple(listx)
print(tuplex)

('w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e')


('w', 3, 's', 'o', 'u', 'r', 'c', 'e')
('w', 3, 's', 'o', 'u', 'r', 'e')
Programs : Write a Python program to find the index of an item of a tuple
tuplex = "w","a", "r", "s", "o", "u", "r", "c", "s"
print(tuplex)
check='z'
# Get the index of the first occurrence of the character "p" in the 'tuplex' tuple
if check in tuplex:
index = tuplex.index(check)
print("element found at index: ", index)
else:
print("element not found")

('w', 'a', 'r', 's', 'o', 'u', 'r', 'c', 's') ('w', 'a', 'r', 's', 'o', 'u', 'r', 'c', 's')
element not found element found at index: 3
Programs : Write a Python program to find the index of an item of a tuple
Tuple =( 1, 0, 4, 2, 5, 6, 7, 5) sample_tuple = (90, 70, 50, 20, 50)
print(len(Tuple)) length = 0
for item in sample_tuple:
length += 1

print("The length of the tuple is:", length)


Programs : Write a program to count the occurrence of each word in the
given text file. And sort the result based on the word length
Unit-3:
Chapter 3: FUNCTIONS
Topics
Functions:
Function calls, Built-in functions, Type conversion functions,
Random numbers, Math functions, Adding new functions,
Definitions and uses, Flow of execution, Parameters and
arguments, Fruitful functions and void functions, Why functions
Python Function
• It is a block of statements that return the specific task.
• The idea is to put some commonly or repeatedly done tasks
together and make a function.
• So that instead of writing the same code again and again for
different inputs, we can do the function calls to reuse code
contained in it over and over again.
Some Benefits of Using Functions
• Increase Code Readability

• Increase Code Reusability


Python Function Declaration
Stored (and reused) Steps
Types of Functions

There are two kinds of functions in Python.


• Built-in functions that are provided as part of Python - print(),
input(), type(), float(), int() ...
• user defined: Functions that we define ourselves and then use

• We treat function names as “new” reserved words


(i.e., we avoid them as variable names)
Function calls
• When we define a function, we specify the name and the sequence of
statements.
• Later, we can “call” the function by name.
• Example of a function call:
>>> type(32)
<class 'int'>
• The name of the function is type.
• The expression in parentheses is called the argument of the function.
• The argument is a value or variable that we are passing into the function
as input to the function.
• The result, for the type function, is the type of the argument.
• A function “takes” an argument and “returns” a result.
• The result is called the return value.
Built-in functions
• Python provides a number of important built-in functions that we can use
without needing to provide the function definition.
• The max and min functions give us the largest and smallest values in a list,
respectively:
>>> max('Hello world')
'w'
>>> min('Hello world')
' '
• The max function tells us the “largest character” in the string (which turns out
to be the letter “w”) and the min function shows us the smallest character
(which turns out to be a space).
len function
• Another very common built-in function is the len function which
tells us how many items are in its argument.
• If the argument to len is a string, it returns the number of characters
in the string.
>>> len('Hello world')
11
• We must treat the names of built-in functions as reserved words
Type conversion functions
• Python also provides built-in functions that convert values from one type
to another.
• The int function takes any value and converts it to an integer, if it can, or
complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
• int can convert floating-point values to integers, but it doesn’t round off;
it chops off the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
Type conversion functions
• float converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
• Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'
When you put an integer and floating point in an expression, the
integer is implicitly converted to a float. We can control this with the
built-in functions int() and float()
>>> print(float(99) / 100)
0.99
>>> i = 42
>>> type(i)
<class 'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class 'float'>
>>> print(1 + 2 * float(3) / 4 – 5)
-2.5
String Conversions
• We can also use int() and float() to convert between strings and integers
• We will get an error if the string does not contain numeric characters
>>>sval='123'
>>> ival = int(sval)
>>> type(ival)
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last): File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Random numbers
• The function random returns a random float between 0.0 and 1.0
(including 0.0 but not 1.0).
• Each time you call random, you get the next number in a long series.

Example:
Output:
import random 0.35049533360156915
for i in range(10): 0.21611787782104575
0.37947439590473364
x = random.random() 0.27303912066907343
print(x) 0.9734623420745635
0.22753483960775467
0.6689999577883523
0.6448529221258081
0.7170635550607704
0.3191037057631271
Random numbers (contd..)
The function randint takes the parameters low and high, and returns
an integer between low and high (including both).
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
Random numbers (contd..)
To choose an element from a sequence at random, you can use choice:
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
Math functions
• Python has a math module that provides most of the familiar
mathematical functions.
• Before we can use the module, we have to import it:
>>> import math
>>> math.sqrt(2) / 2.0
0.7071067811865476
Adding new functions
• A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
• Once we define a function, we can reuse the function over and over
throughout our program.
• We create a new function using the def keyword followed by
optional parameters in parentheses
• We indent the body of the function
• This defines the function but does not execute the body of the
function
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
• This is the store and reuse pattern
Flow of execution
• In order to ensure that a function is defined before its first use, we
have to know the order in which statements are executed, which is
called the flow of execution.
• Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.
Flow of execution
• When the function greet() is called, the program's control transfers
to the function definition.
• All the code inside the function is executed.
• The control of the program jumps to the next statement after the
function call.
Arguments
• An argument is a value we pass into the function as its input when
we call the function
• We use arguments so we can direct the function to do different
kinds of work when we call it at different times
• We put the arguments in parentheses after the name of the
function
Functions
Parameters
A parameter is a variable which we use in the function definition. It is a
“handle” that allows the code in the function to access the arguments for
a particular function invocation.
def greet(lang):
if lang == ‘hi':
print(‘Namaste')
elif lang == ‘kn':
print(‘Namaskara')
else:
print('Hello')
>>> greet(‘kn')
Namaskara
>>> greet(‘en')
Hello
>>> greet(‘hi')
Namaste
Arguments and Parameters in Python
• Both arguments and parameters are variables/ constants passed into a function.
The difference is that:
• Arguments are the variables passed to the function in the function call.
• Parameters are the variables used in the function definition.
• The number of arguments and parameters should always be equal except for the
variable length argument list.
def add_func(a,b):
sum = a + b
return sum
num1 = int(input("Enter the value of the first number: "))
num2 = int(input("Enter the value of the second number: "))
print("Sum of two numbers: ",add_func(num1, num2))
• (num1, num2) are in the function call, and (a, b) are in the function definition.
• (num1, num2) are arguments and (a, b) are parameters.
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the calling
expression. The return keyword is used for this.

Example:
def greet():
return "Hello"

print(greet(), “Raj") #Output: Hello Raj


print(greet(), “Khushi") #Output: Hello Khushi
Fruitful functions
• A “fruitful” function is one that produces a result (or return value)
• The return statement ends the function execution and “sends back” the
result of the function

Example:
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)

Output: 8
Void functions
Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you try to assign
the result to a variable, you get a special value called None.
Example:
def addtwo(a, b):
added = a + b
print(added)
addtwo(3, 5) #output: 8
a=addtwo(3,5)
print(a) #output: None
Why functions
Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read,
understand, and debug.
Functions can make a program smaller by eliminating repetitive
code. Later, if you make a change, you only have to make it in one
place.
Dividing a long program into functions allows you to debug the parts
one at a time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.
Function Reusability
We reuse the function written in one program in another program.

To create a custom module with importable functions, we need to:


1. Create a new Python file with the .py extension and give it a descriptive name
(e.g., myfunctions.py).
2. Define one or more functions in the file using the def keyword and a function name
(e.g., mod_function).
3. Save the file.
4. Import the function(s) from the file into another Python script using
the import keyword and the file name without the .py extension (e.g. import
myfunctions).
5. Call the imported function(s) in the script using the function name as defined in the
file (e.g., myfunctions.mod_function()).
Function Reusability (Contd..)
Example: # <calc.py> # importing all functions defined in calc.py in another pgm

import calc

def addNumbers(a, b): # calling functions


calc.addNumbers(2, 5)
print("Sum is ", a + b) calc.multiplyNumbers(5, 4)
def subtractNumbers(a, b): # importing all functions defined in calc.py in another pgm
print("Difference is ", a-b) from calc import *
def multiplyNumbers(a, b): # calling functions
print("Product is ", a * b) addNumbers(2, 5)
multiplyNumbers(5, 4)
def divideNumbers(a, b):
# importing limited functions defined in calc.py in another
print("Division is ", a / b) pgm
def modulusNumbers(a, b): from calc import addNumbers, multiplyNumbers
print("Remainder is ", a % b) # calling functions
addNumbers(2, 5)
multiplyNumbers(5, 4)
Function to interchange first and last elements in a list
def swapList(List1): #swap first and last element in list
# Swap function
size = len(List1) def swapList(list):

first = list.pop(0)
last = list.pop(-1)
temp = List1[0] list.insert(0, last)
list.append(first)
List1[0] = List1[size - 1] return list
List1[size - 1] = temp li = [1, 9, 2, 10, 19, 30]
print(li)
print("Swapped list: ",swapList(li))
return List1

newList = [12, 35, 9, 56, 24]


print(swapList(newList))
Function to find biggest number in list
def myMax(list1):
max = list1[0]
for x in list1:
if x > max:
max = x
return max
list1 = [10, 20, 4, 45, 99]
print("Largest element is:", myMax(list1))
Function to find biggest of 3 number
def maximum(a, b, c):
def maximum(a, b, c): list = [a, b, c]
return max(list)
if (a >= b) and (a >= c): a,b,c = 10,14,12
largest = a print(maximum(a, b, c))

elif (b >= a) and (b >= c):


largest = b
else:
largest = c
return largest
a = 10
b = 14
c = 12
print(maximum(a, b, c))
Function to find sum of numbers in tuple
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))
Function to add two list elementwise
def add_lists(l1,l2):
if len(l1)==len(l2):
for i in range(len(l1)):
l1[i]=l1[i]+l2[i]
else:
print("Lists cannot be added")
exit()

l1=[1,2,3,4]
l2=[5,6,7,8]
add_lists(l1,l2)
print("Resulting list is:",l1)
Function to print upper and lower case(count)
def case_letter(s):
c1=0
c2=0
for c in s:
if c>='A' and c<='Z':
c1+=1
elif c>='a' and c<='z':
c2+=1
return c1,c2

s1="Welcome to BMSCE"
c1,c2=case_letter(s1)
print("Uppercase:",c1,"lowercase:",c2)
Assignment
Function to find factorial of a number
def factorial(n):
def factorial(n):
if n < 0: res = 1
return 0 for i in range(2, n+1):
elif n == 0 or n == 1: res *= i
return 1 return res
else: # Driver Code
num = 5
fact = 1 print("Factorial of", num,
while(n > 1): "is",factorial(num))
fact *= n
n -= 1
return fact
num = 5
print("Factorial of",num,"is",
factorial(num))
Function to check prime or not
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Check for factors from 3 to sqrt(n)
for i in range(3, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

number = 29
if is_prime(number):
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Function to Check if a String is Palindrome or Not
def isPalindrome(s): def isPalindrome(x):
return s == s[::-1] w = ""
for i in x:
w=i+w
s = "malayalam" if (x == w):
ans = isPalindrome(s) print("Yes")
if ans: else:
print("Yes") print("No")
else: str1 = input("enter a string to check polidrome: ")
isPalindrome(str1)
print("No")
def sort_words(seq):
words = seq.split('-')
words.sort()

sorted_seq = '-'.join(words)

return sorted_seq

input_sen = input("Enter a hyphen-separated sequence of words: ")


sorted_seq = sort_words(input_sen)
print("Sorted sequence:", sorted_seq)
Assignment(Contd..)
What will the following Python program print out?
def fred():
print("Zap")
def jane():
print("ABC")
jane()
fred()
jane()
Assignment (Contd..)
Write the grade program using a function called computegrade that
takes a score as its parameter and returns a grade as a string.
Score Grade
> 0.9 A
> 0.8 B
> 0.7 C
> 0.6 D
<= 0.6 F
Assignment (Contd..)
def computegrade(score):
if score > 1.0 or score < 0.0:
return 'Invalid score'
elif score > 0.9:
return 'A'
elif score > 0.8:
return 'B'
elif score > 0.7:
return 'C'
elif score > 0.6:
return 'D'
else:
return 'F'

print(computegrade(0.95))
print(computegrade(0.85))

You might also like