Lab Manual python
Lab Manual python
Experimental set-up/Equipment/Apparatus/Tools: -
1. Computer System
2. Google Colab /python Installed on system with editor (like pycharm,
jupyter)
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
Experimental Procedure-
1. Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
2. Type a python program using input, output and calculations
3. Save the program
4. Execute it.
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
The devices either computers or any other networking device should be handled
with due care and preserved carefully.
Results
Conclusions
We should know all the basic data types of python to start with it. Also to perform any
operation Input and output are very important so through this experiment we learnt to do the
same in the python.
Experimental set-up/Equipment/Apparatus/Tools: -
1. Computer System
2. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Experimental Procedure-
1 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
2 Type a python program using input, output and calculations
3 Save the program
4 Execute it.
Source code:
a=10; b=3
print("addition of a:",a,"&b:",b,"is:",a+b)
print("substraction of a:",a,"&b:",b,"is:",a-b)
print("multiplication of a:",a,"&b:",b,"is:",a*b)
print("division of a:",a,"&b:",b,"is:",a/b)
print("moduli of a:",a,"&b:",b,"is:",a%b)
print("exponent of a:",a,"&b:",b,"is:",a**b)
Results
Conclusions
Operators are the constructs which can manipulate the value of operands. Manipulation is
required in every application. So the basic knowledge of operator is mandatory
Experiment name: Write a program to create, concatenate and print a string and
accessing substring
from a given string.
Experimental set-up/Equipment/Apparatus/Tools: -
3. Computer System
4. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of
the tutorial, we will discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
Syntax:
1. str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
1. print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type; instead, a single character written as 'p' is treated as the string
of length 1.
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.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
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.
Consider the following example:
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. 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.
1. # Given String
2. str = "JAVATPOINT"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10. print(str[:3])
11. #Starts 4th to 6th index
12. print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
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.
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
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.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be assigned completely to a new content as
specified in the following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
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.
1. str = "JAVATPOINT"
2. del str[1]
Output:
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
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 range slice operator. It is used to access the characters from the specified
range.
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.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10. 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
Python String Formatting
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given
statement can be written in single quotes or double quotes but it will raise
the SyntaxError as it contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape
sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a
special character and it interpreted differently. The single quotes inside the string must be
escaped. We can apply the same as in the double quotes.
Example -
1. # using triple quotes
2. print('''''They said, "What's there?"''')
3.
4. # escaping single quotes
5. print('They said, "What\'s going on?"')
6.
7. # escaping double quotes
8. print("They said, \"What's going on?\"")
Output:
2. \\ Backslash print("\\")
Output:
'
"
Hello World
Hello
World!
World!
Hello World!
Hello
World!
Hello
1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
2. print("This is the \n multiline quotes")
3. print("This is \x48\x45\x58 representation")
Output:
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
This is HEX representation
We can ignore the escape sequence from the given string by using the raw string. We can do
this by writing r or R in front of the string. Consider the following example.
1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
C:\\Users\\DEVANSH SHARMA\\Python32
The format() method is the most flexible and useful method in formatting strings. The curly
braces {} are used as the placeholder in the string and replaced by the format() method
argument. Let's have a look at the given an example:
Output:
Python allows us to use the format specifiers used in C's printf statement. The format
specifiers in Python are treated in the same way as they are treated in C. However, Python
provides an additional operator %, which is used as an interface between the format specifiers
and their values. In other words, we can say that it binds the format specifiers to the values.
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ...
My value is %s"%(Integer,Float,String))
Output:
Python provides various in-built functions that are used for string handling. Many String fun
Method Description
center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.
decode(encoding = 'UTF8', Decodes the string using codec registered for encoding.
errors = 'strict')
endswith(suffix ,begin=0,end=le It returns a Boolean value if the string terminates with given suffix
n(string)) between begin and end.
expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The default space value
is 8.
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
format(value) It returns a formatted version of S, using the passed value.
isalnum() It returns true if the characters in the string are alphanumeric i.e.,
alphabets or numbers and there is at least 1 character. Otherwise, it
returns false.
isalpha() It returns true if all the characters are alphabets and there is at least
one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at least one
character, otherwise False.
istitle() It returns true if the string is titled properly and false otherwise. A
title string is the one in which the first character is upper-case
whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true
otherwise it returns false.
ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.
lstrip() It removes all leading whitespaces of a string and can also be used
to remove particular character from leading.
partition() It searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
replace(old,new[,count]) It replaces the old sequence of characters with the new sequence.
The max characters are replaced if max is given.
rjust(width,[,fillchar]) Returns a space padded string having original string right justified
to the number of characters specified.
rstrip() It removes all trailing whitespace of a string and can also be used
to remove particular character from trailing.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the backward
direction. It returns the list of words in the string. If Separator is
not specified then the string splits according to the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It returns
the list of substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str between
begin and end.
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
translate(table,deletechars = '') It translates the string according to the translation table passed in
the function .
rpartition()
Experimental Procedure-
5 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
6 Type a python program using input, output and calculations
7 Save the program
8 Execute it.
Results
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Conclusion:
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes Thorugh this experiment
we learnt to perform various operations on strings in python.
Experiment name: Write a python script to print the current date in the following format
“Sun May 29 02:26:23 IST 2017”
Experimental set-up/Equipment/Apparatus/Tools: -
5. Computer System
6. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Python provides the datetime module work with real dates and times. In real-world
applications, we need to work with the date and time. Python enables us to schedule our
Python script to run at a particular timing.
In Python, the date is not a data type, but we can work with the date objects by importing the
module named with datetime, time, and calendar.
In this section of the tutorial, we will discuss how to work with the date and time objects in
Python.
o date - It is a naive ideal date. It consists of the year, month, and day as attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has
hour, minute, second, microsecond, and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year, month,
day, hour, minute, second, microsecond, and tzinfo.
o timedelta - It represents the difference between two dates, time or datetime instances
to microsecond resolution.
o tzinfo - It provides time zone information objects.
o timezone - It is included in the new version of Python. It is the class that implements
the tzinfo abstract base class.
To work with dates as date objects, we have to import the datetime module into the python
source code.
Consider the following example to get the datetime object representation for the current
time.
Example
1. import datetime
2. #returns the current datetime object
3. print(datetime.datetime.now())
Output:
2020-04-04 13:18:35.252578
Example
1. import datetime
2. #returns the datetime object for the specified date
3. print(datetime.datetime(2020,04,04))
Output:
2020-04-04 00:00:00
We can also specify the time along with the date to create the datetime object. Consider the
following example.
Example
1. import datetime
2.
3. #returns the datetime object for the specified time
4.
5. print(datetime.datetime(2020,4,4,1,26,40))
Output:
2020-04-04 01:26:40
In the above code, we have passed in datetime() function year, month, day, hour, minute, and
millisecond attributes in a sequential manner.
Example
Experimental Procedure-
9 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
10 Type a python program using input, output and calculations
11 Save the program
12 Execute it.
Source code:
Results
Conclusions
A Python program can handle date and time in several ways. Converting between date formats is a
common chore for computers. Python's time and calendar modules help track dates and
times.Thorugh this experiment we learnt to work with date format in python.
Experimental set-up/Equipment/Apparatus/Tools: -
7. Computer System
8. Google Colab /python Installed on system with editor (like pycharm, jupyter)
List
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
List Items
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
List Length
To determine how many items a list has, use the len() function:
type()
From Python's perspective, lists are defined as objects with the data type 'list':
It is also possible to use the list() constructor when creating a new list.
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
There are four collection data types in the Python programming language:
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.
To change the value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values:
If you insert more items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
If you insert less items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
Insert Items
To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
To add an item to the end of the list, use the append() method:
Insert Items
Extend List
To append elements from another list to the current list, use the extend() method.
The extend() method does not have to append lists, you can add any iterable object (tuples,
sets, dictionaries etc.).
If you do not specify the index, the pop() method removes the last item.
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Experimental Procedure-
13 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
14 Type a python program using input, output and calculations
15 Save the program
16 Execute it.
Precaution and sources of error:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
abc = [2,3,4,5]
print (abc)
print(thislist)
print(thislist[5])
print(thislist[2:5])
print(thislist[:7])
print(thislist[3:])
print(thislist[-3:-1])
list6.extend(list5)
print(list6)
Experimental set-up/Equipment/Apparatus/Tools: -
9. Computer System
10. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar
to lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.
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.
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Note: The tuple which is created without using parentheses is also known as tuple packing.
1. tup1 = ("JavaTpoint")
2. print(type(tup1))
3. #Creating a tuple with single element
4. tup2 = ("JavaTpoint",)
5. print(type(tup2))
Output:
<class 'str'>
<class 'tuple'>
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.
Example - 1
1. tuple1 = (10, 20, 30, 40, 50, 60)
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %d"%(count, i))
6. count = count+1
Output:
Example - 2
1. tuple1 = tuple(input("Enter the tuple elements ..."))
2. print(tuple1)
3. count = 0
4. for i in tuple1:
5. print("tuple1[%d] = %s"%(count, i))
6. count = count+1
Output:
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.
We will see all these aspects of tuple in this section of the tutorial.
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.
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
element outside of tuple that raised an IndexError.
1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)
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. Consider the
following example:
1. tuple1 = (1, 2, 3, 4, 5)
2. print(tuple1[-1])
3. print(tuple1[-4])
4. print(tuple1[-3:-1])
5. print(tuple1[:-1])
6. print(tuple1[-2:])
Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are
immutable. To delete an entire tuple, we can use the del keyword with the tuple name.
1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. print(tuple1)
Output:
(1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
File "tuple.py", line 4, in <module>
print(tuple1)
NameError: name 'tuple1' is not defined
Experimental Procedure-
17 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
18 Type a python program using input, output and calculations
19 Save the program
20 Execute it.
is:",len(colleges))
if "SIIET" in colleges:
Results
Conclusions
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just
like lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as
simple as putting different comma-separated values. Thorugh this experiment we learnt to
perform various operations on tuple in python.
Experimental set-up/Equipment/Apparatus/Tools: -
11. Computer System
12. Google Colab /python Installed on system with editor (like pycharm, jupyter)
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.
Syntax:
5.3M
115
HTML Tutorial
In the above dictionary Dict, The keys Name and Age are the string that is an immutable
object.
Output
<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
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.
Output:
Empty Dictionary:
{}
However, the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values.
It would give the same result as given by the indexing.
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.
Example - 1:
Empty Dictionary:
{}
Example - 2:
Output:
Empty Dictionary:
{}
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined
The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.
The pop() method accepts the key as an argument and remove the associated value. Consider
the following example.
1. # Creating a Dictionary
2. Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
3. # Deleting a key
4. # using pop() method
5. pop_ele = Dict.pop(3)
6. print(Dict)
Output:
Python also provides a built-in methods popitem() and clear() method for remove elements
from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas
the clear() method removes all elements to the whole dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Output:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
Output:
John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by using values() method.
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by using items() method.
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"John"}
2. for x,y in Employee.items():
3. print(x,y)
Output:
Name John
Age 29
Salary 25000
Company GOOGLE
2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as
the key, but we cannot use any mutable object like the list as the key in the dictionary.
Output:
Experimental Procedure-
21 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
22 Type a python program using input, output and calculations
23 Save the program
24 Execute it.
}
print(college)
#adding items to dictionary college["location"] = "IBP" print(college)
#changing values of a key college["location"] = "sheriguda" print(college)
# to remove items use pop() college.pop("code") print(college)
#know the length using len() print("length of college is:",len(college)) #to copy the same
dictionary use copy() mycollege= college.copy() print(mycollege)
Precaution and sources of error:
The devices either computers or any other networking device should be handled
with due care and preserved carefully.
Results
Conclusions
A dictionary is a data structure in Python that is a mutable, or changeable, unordered elements. Keys
are unique within a dictionary while values may not be. The values of a dictionary can be of any type,
but the keys must be of an immutable data type such as strings, numbers, or tuples. Through this
experiment we learnt to perform various operations on dictionaries in python.
Experimental set-up/Equipment/Apparatus/Tools: -
13. Computer System
14. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages −
Python programming language assumes any non-zero and non-null values as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements.
Click the following links to check their detail.
1 if statements
2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute
a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
Experimental Procedure-
25 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
26 Type a python program using input, output and calculations
27 Save the program
28 Execute it.
Results
Conclusions
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise. Thorugh this experiment we learnt to work with
conditional statements in python.
Objectives: To learn how to convert to and from Celsius, Fahrenheit using formula
Experimental set-up/Equipment/Apparatus/Tools: -
15. Computer System
16. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following
the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute.
Experimental Procedure-
29 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
30 Type a python program using input, output and calculations
31 Save the program
32 Execute it.
while(1):
print("1.CELSIUS TO FAHRENHEIT\n2.FAHRENHEIT TO CELSIUS\n3.EXIT\n")
choice=input("ENTER YOUR CHOICE:")
ch=int(choice)
if(ch==1):
c=int(input("ENTER TEMPERATURE IN CELSIUS:"))
f=((9*c)/5)+32
print("converted temperature is:",f) elif(ch==2):
f=int(input("ENTER TEMPERATURE IN FAHRENHEIT:"))
c=((f-32)/9)*5
print("converted temperature is:",c) elif(ch==3):
exit()
else:
print("wrong choice")
Results
Conclusions
Thorugh this experiment we learnt about loops and conversion of temperatures to and from
Celsius, Fahrenheit.
in python.
Experiment name: Write a Python program to construct the following pattern, using a
nested for
loop
*
**
***
****
***
**
**
*
Experimental set-up/Equipment/Apparatus/Tools: -
17. Computer System
18. Google Colab /python Installed on system with editor (like pycharm, jupyter)
The outer loop can contain more than one inner loop. There is no limitation on the chaining
of loops.
In the nested loop, the number of iterations will be equal to the number of iterations in the
outer loop multiplied by the iterations in the inner loop.
In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an
outer loop the inner loop re-start and completes its execution before the outer loop can
continue to its next iteration.
Nested loops are typically used for working with multidimensional data structures, such as
printing two-dimensional arrays, iterating a list that contains a nested list.
A nested loop is a part of a control flow statement which helps you to understand the basics
of Python.
In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other
iterable objects such as range.
In this example, we are using a for loop inside a for loop. In this example, we
are printing a multiplication table of the first ten numbers.
The outer for loop uses the range() function to iterate over the first ten numbers
The inner for loop will execute ten times for each outer number
In the body of the inner loop, we will print the multiplication of the outer
number and current number
The inner loop is nothing but a body of an outer loop.
Nested Loop to Print Pattern
Another most common use of nested loop is to print various star and number pattern.
Let’s see how to use nested loop to print the following pattern in Python.
Pattern:
**
***
****
*****
Program:
rows = 5
# outer loop
for i in range(1, rows + 1):
# inner loop
for j in range(1, i + 1):
print("*", end=" ")
print('')
33 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
34 Type a python program using input, output and calculations
35 Save the program
36 Execute it.
n=int(input("ENTER A VALUE:"))
for x in range(0,n+1,1):
print(x*'*')
if(x==n):
for x in range(n,0,-1):
print(x*'*')
Results
Conclusions
Nested loops are typically used for working with multidimensional data structures,
such as printing two-dimensional arrays, iterating a list that contains a nested list..
Through this experiment we learnt about nested loop and how generate various patterns in
python.
Experiment name: Write a Python script that prints prime numbers less than 20.
Experimental set-up/Equipment/Apparatus/Tools: -
19. Computer System
20. Google Colab /python Installed on system with editor (like pycharm, jupyter)
The break is commonly used in the cases where we need to break the loop for a given
condition.
1. #loop statements
2. break;
Example 1
1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:
s Java
item matched
found at 2 location
Experimental Procedure-
37 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
38 Type a python program using input, output and calculations
39 Save the program
40 Execute it.
count=0
if(num%i==0):
if(count==0): print(num)
Results
Conclusions
The break is commonly used in the cases where we need to break the loop for a given condition.
Through this experiment we learnt to work with break statement in python.
Experimental set-up/Equipment/Apparatus/Tools: -
21. Computer System
22. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Syntax:
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms = 10
if n_terms <= 0:
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
Output:
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Experimental Procedure-
41 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
42 Type a python program using input, output and calculations
43 Save the program
44 Execute it.
Output:
Results
Conclusions
Recursive functions render the code look simple and effective.
Through this experiment we learnt to implement recursion in python.
Objectives: To learn to implement a program to check whether the triangle is right angle
triangle or not
Experimental set-up/Equipment/Apparatus/Tools: -
23. Computer System
24. Google Colab /python Installed on system with editor (like pycharm, jupyter)
pythagorean(a,b,c)
Experimental Procedure-
45 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
46 Type a python program using input, output and calculations
47 Save the program
48 Execute it.
print("yes!! the given inputs are triplets of a right angled triangle!!") print("height:",c**0.5,"\
nbase:",b**0.5,"\nhypotenuse:",a**0.5)
pythagorean(a,b,c) # calling function
Results
Conclusion
Experiment 14
Experiment name: Write a python program to define a module to find Fibonacci
Numbers and import the module to another program.
Experimental set-up/Equipment/Apparatus/Tools: -
25. Computer System
26. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Any non-trivial Python program would be organized in multiple files, connected with each
other using imports. Python, as most of the other programming languages, uses this modular
program structure, where functionalities are grouped in to reusable units. In general, we can
distinguish three types of files in a multi-file Python application:
top-level file: A Python file, or script, which is the main entry point of the program.
This file is run to launch your application.
user-defined modules: Python files which are imported in to the top-level file, or
among each other, and provide separate functionalities. These files are usually not
launched directly from your command prompt, and are custom-made for the purpose
of the project.
standard library modules: Pre-coded modules which are built-in to the Python
installation package, such as platform-independent tools for system interfaces,
Internet scripting, GUI construction, and others. These modules are not part of the
Python executable itself, but part of the standard Python library.
Figure 1 shows an example program structure with the three file types:
Figure 1: An example program structure including a top-level script, custom modules, and
standard library modules.
In this figure, the module 'top_module.py' is a top-level Python file which imports tools
defined in module 'module1', but also has access to tools in 'module2' through 'module1'. The
two custom modules use each other's resources, as well as other modules from the standard
Python library. The importing chain can go as deep as you want: there's no limit in the
number of imported files, and they can import each-other, although you need to be careful
with circular importing.
# top_module.py
import module1
module1.print_parameters()
print(module1.combinations(5, 2))
# module1.py
from module2 import k, print_parameters
from math import factorial
n = 5.0
def combinations(n, k):
return factorial(n) / factorial(k) / factorial(n-k)
# module2.py
import module1
k = 2.0
def print_parameters():
print('k = %.f n = %.f' % (k, module1.n))
In the above example, 'top_module.py' is a top-level module that will be run by the user, and
it imports tools from other modules through 'module1.py'. module1 and module2 are user-
defined modules, while the 'math' module is imported from the standard Python library.
When running the top-level script, we get:
$ python top_module.py
k=2n=5
10.0
When a top-level Python file is run, its source code statements, and the statements within
imported modules, are compiled in an intermediate format known as byte code, which is a
platform-independent format. Byte code files of imported modules are stored with a .pyc
extension in the same directory as the .py file for Python versions up to 3.2, and in
directory __pycache__ in the program's home directory in Python 3.2+.
$ ls __pycache__/
module1.cpython-36.pyc module2.cpython-36.pyc
Dual-Mode Code
As mentioned earlier, Python files can also be designed as both importable modules and top-
level scripts. That is, when run, the Python module will run as a stand-alone program, and
when imported, it will act as a importable module containing code definitions.
This is easily done using the attribute __name__ , which is automatically built into every
module. If the module is run as a top-level script the __name__ attribute will equal to the
string "__main__", otherwise if imported, it will contain the name of the actual module.
code:
# hiprinter.py
# Terminal window
$ python hiprinter.py
Hi!Hi!Hi!
# Python interpreter
The dual-mode code is very common in practice, and especially useful for unit-testing: while
variables and functions are defined as top-level names in the file, the part inside
the if statement can serve as a testing area of the above defined names.
Using a Module
Import Statements
The example in Section Program Architecture was useful to look at the difference between
two importing statements: import and from. The main difference is that import loads the
entire module as a single object, while from loads specific properties and functions from the
module. Importing names with the from statement can then be used directly in the importer
module, without calling the imported object name.
Using the from statement is only allowed in the top-level of the module file in Python 3.x,
and not within a function. Python 2.x allows to use it in a function, but issues a warning.
Performance-wise, the from statement is slower than import because it does all the work
that import does - going through all the content of the imported module, and then does an
extra step in selecting the appropriate names for importing.
There's also a third import statement from * which is used to import all top-level names from
the imported module and use them directly in the importer class. For example we could have
used:
This would import all names (variables and functions) from the module2.py file. This
approach is not recommended because of possible name duplication - the imported names
could overwrite already existing names in the importer module.
Experimental Procedure-
49 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
50 Type a python program using input, output and calculations
51 Save the program
52 Execute it.
Source code:
fibonacci.py
def fibonacci(n):
n1=0; n2=1;
print(n1)
print(n2)
for x in range(0,n):
n3=n1+n2
if(n3>=n):
break;
print(n3,end = ' ')
n1=n2
n2=n3
using_fibonacci.py
import fibonacci
n=int(input("enter range:"))
if(n<0):
print("enter correct range!!")
else:
fibonacci.fibonacci (n)
Conclusions
Python, as most of the other programming languages, uses this modular program structure,
where functionalities are grouped in to reusable units. Thorugh this experiment we learnt to
create and import module in python.
Experiment name: Write a python program to define a module and import a specific
function in that module to another program.
Objectives: To learn how to import a particular function of module into another program
Prerequisites: Algorithm and logics, basic knowledge of C++
Experimental set-up/Equipment/Apparatus/Tools: -
1. Computer System
2. Google Colab /python Installed on system with editor (like pycharm, jupyter)
import math
print(math.pi)
Output:
3.141592653589793
import module_name.member_name
In the above code module, math is imported, and its variables can be accessed by
considering it to be a class and pi as its object.
The value of pi is returned by __import__().
pi as a whole can be imported into our initial code, rather than importing the whole
module.
Output:
3.141592653589793
print(pi)
print(factorial(6))
Output:
3.141592653589793
720
As said above import uses __import__() to search for the module, and if not found, it
would raise ImportError
Experimental Procedure-
53 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
54 Type a python program using input, output and calculations
55 Save the program
56 Execute it.
fibonacci.py
def fibonacci(n):
n1=0; n2=1;
print(n1)
print(n2)
for x in range(0,n):
n3=n1+n2 if(n3>=n):
break;
print(n3,end = ' ')
n1=n2
n2=n3
using_fibonacci.py
Results
Conclusions
Through this experiment we learnt how to import specific function of a module into another
program in python.
Experiment name: Write a script named copyfile.py. This script should prompt the user
for the names of two text files. The contents of the first file should be input and written
to the second file.
Objectives: To learn how to take one file as a input to another file in python
Experimental set-up/Equipment/Apparatus/Tools: -
3. Computer System
4. Google Colab /python Installed on system with editor (like pycharm, jupyter)
file = open('geek.txt','w')
file.close()
The close() command terminates all the resources in use and frees the system of this
particular program.
For taking contents one from to another file
Program Explanation
1. The file input.txt is opened using the open() function using the f stream.
2. Another file output.txt is opened using the open() function in the write mode using the f1
stream.
3. Each line in the file is iterated over using a for loop (in the input stream).
4. Each of the iterated lines is written into the output file.
Experimental Procedure-
57 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
58 Type a python program using input, output and calculations
59 Save the program
60 Execute it.
Note: create a text file as “input.txt” and write some date in it. This will be used in the
program.
print("JOB DONE!!")
Results
Conclusions
Thorugh this experiment we learnt how to take one take one file data input into other file in
python.
Experiment name: Write a program that inputs a text file. The program should print all
of the unique words in the file in alphabetical order.
Objectives: To learn how to read a file through python program and print unique words.
Experimental set-up/Equipment/Apparatus/Tools: -
5. Computer System
6. Google Colab /python Installed on system with editor (like pycharm, jupyter)
readline() function is used to read a line in the document. It can be used like:
>>> myFile.readline()
Copy
where myFile is the instance of the file. readline() function will simply print the whole line
starting from the cursor's position.
In order to print the whole content of the file, iterating line by line, we can use a for loop:
print (line)
Copy
Beside using iteration, there is another way of reading the whole file,
using readlines() function(notice it is readlines, which is different from readline). Using the
function will return a list that will contain each line of the file. Because of this, one should be
careful while using this function. In case there is lots of data in the file, the list may take lots
of space, and thus making the whole reading time longer. Thus, it is recommended to use this
function only for reading shorter files which can be stored in a list efficiently.
It is used pretty much like readlines() only, except that in this case we need to store the
returned value in some variable:
Copy
content = []
content.append(line)
Copy
This will iteratively append each line of the file on content list.
write() function is used to write a single string into the file. For example, there is a string
>>> myFile.write(content)
Copy
or
Copy
Write can't be used for writing the content of list or tuple. In such cases, writelines() function
is used.
>>> myFile.writelines(content)
Copy
Python 3.x
Experimental Procedure-
61 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
62 Type a python program using input, output and calculations
63 Save the program
64 Execute it.
if element in our_list:
continue
else:
our_list.append(element)
our_list.sort()
print(our_list)
Results
Conclusions
Thorugh this experiment we learnt to read a file into other file and print unique words from it
in python.
Experimental set-up/Equipment/Apparatus/Tools: -
7. Computer System
8. Google Colab /python Installed on system with editor (like pycharm, jupyter)
A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class creates a
new type of object, allowing new instances of that type to be made. Each class instance can
have attributes attached to it for maintaining its state. Class instances can also have methods
(defined by their class) for modifying their state.
To understand the need for creating a class let’s consider an example, let’s say you wanted to
track the number of dogs that may have different attributes like breed, age. If a list is used,
the first element could be the dog’s breed while the second element could represent its age.
Let’s suppose there are 100 different dogs, then how would you know which element is
supposed to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it’s the exact need for classes.
Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like
a blueprint for an object.
Class Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
Class Objects
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed
pug who’s seven years old. You can have many dogs to create many different instances, but
without the class as a guide, you would be lost, not knowing what information is required.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an
object.
Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Declaring an object –
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
Experimental Procedure-
65 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
66 Type a python program using input, output and calculations
67 Save the program
68 Execute it.
class roman_solution:
def int_to_Roman(num):
syb = ["M", "CM", "D", "CD", "C", "XC", "L", "XL","X", "IX", "V", "IV", "I” ]
roman_num = “”
i=0
if(n<1 or n>3999):
if(num-val[i]>=0):
roman_num+=syb[i] num-=val[i]
else:
i+=1
return roman_num
n=int(input("ENTER A NUMBER:"))
print("roman numeral of given number is:",roman_solution.int_to_Roman(n))
Results
Conclusions
A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class creates a
new type of object, allowing new instances of that type to be made. Thorugh this
experiment we learnt to use class in python.
Experimental set-up/Equipment/Apparatus/Tools: -
Computer System
Google Colab /python Installed on system with editor (like pycharm, jupyter)
Syntax
pow(x, y, z)
Parameter Values
Parameter Description
69 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
70 Type a python program using input, output and calculations
71 Save the program
72 Execute it.
class py_power:
def power(x,n):
print("power of given literals:\nx:",x,"\nn\n:",n,"is:",x**n)
x=float(input("ENTER X(BASE) VALUE:"))
n=float(input("ENTER N(POWER) VALUE:"))
py_power.power(x,n)
Results
Conclusions
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
Each element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [ ] . Thorugh this
experiment we learnt to perform various operations on lists in python.
Related short question:
Write syntax of pow() function
In which library pow() function is present
Experiment 20
Objectives: To learn how to how to use string class for reversing a string
Experimental set-up/Equipment/Apparatus/Tools: -
9. Computer System
10. Google Colab /python Installed on system with editor (like pycharm, jupyter)
Python has a built-in string class named "str" with many handy features (there is an older
module named "string" which you should not use). String literals can be enclosed by either
double or single quotes, although single quotes are more commonly used. Backslash escapes
work the usual way within both single and double quoted literals -- e.g. \n \' \". A double
quoted string literal can contain single quotes without any fuss (e.g. "I didn't do it") and
likewise single quoted string can contain double quotes. A string literal can span multiple
lines, but there must be a backslash \ at the end of each line to escape the newline. String
literals inside triple quotes, """ or ''', can span multiple lines of text.
Python strings are "immutable" which means they cannot be changed after they are created
(Java strings also use this immutable style). 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'.
Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++,
Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'. If the index is out of bounds for
the string, Python raises an error. The Python style (unlike Perl) is to halt if it can't tell what
to do, rather than just make up a default value. The handy "slice" syntax (below) also works
to extract any substring from a string. The len(string) function returns the length of a string.
The [ ] syntax and the len() function actually work on any sequence type -- strings, lists, etc..
Python tries to make its operations work consistently across different types. Python newbie
gotcha: don't use "len" as a variable name to avoid blocking out the len() function. The '+'
operator can concatenate two strings. Notice in the code below that variables are not pre-
declared -- just assign to them and go.
s = 'hi'
print s[1] ## i
print len(s) ## 2
print s + ' there' ## hi there
Unlike Java, the '+' does not automatically convert numbers or other types to string form. The
str() function converts values to a string form so they can be combined with other strings.
pi = 3.14
##text = 'The value of pi is ' + pi ## NO, does not work
text = 'The value of pi is ' + str(pi) ## yes
For numbers, the standard operators, +, /, * work in the usual way. There is no ++ operator,
but +=, -=, etc. work. If you want integer division, it is most correct to use 2 slashes -- e.g.
6 // 5 is 1 (previous to python 3, a single / does int division with ints anyway, but moving
forward // is the preferred way to indicate that you want int division.)
The "print" operator prints out one or more python items followed by a newline (leave a
trailing comma at the end of the items to inhibit the newline). A "raw" string literal is
prefixed by an 'r' and passes all the chars through without special treatment of backslashes, so
r'x\nx' evaluates to the length-4 string 'x\nx'. A 'u' prefix allows you to write a unicode string
literal (Python has lots of other unicode support features -- see the docs below).
String Methods
Here are some of the most common string methods. A method is like a function, but it runs
"on" an object. If the variable s is a string, then the code s.lower() runs the lower() method on
that string object and returns the result (this idea of a method running on an object is one of
the basic ideas that make up Object Oriented Programming, OOP). Here are some of the most
common string methods:
s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
s.strip() -- returns a string with whitespace removed from the start and end
s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes
s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the
first index where it begins or -1 if not found
s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a
regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special
case s.split() (with no arguments) splits on all whitespace chars.
s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the
delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
A google search for "python str" should lead you to the official python.org string
methods which lists all the str methods.
Python does not have a separate character type. Instead an expression like s[8] returns a
string-length-1 containing the character. With that string-length-1, the operators ==, <=, ... all
work as you would expect, so mostly you don't need to know that Python does not have a
separate scalar "char" type.
String Slices
The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings and
lists. The slice s[start:end] is the elements beginning at start and extending up to but not
including end. Suppose we have s = "Hello"
s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way to
copy a sequence like a string or list)
s[1:100] is 'ello' -- an index that is too big is truncated down to the string length
The standard zero-based index numbers give easy access to chars near the start of the string.
As an alternative, Python uses negative numbers to give easy access to the chars at the end of
the string: s[-1] is the last char 'o', s[-2] is 'l' the next-to-last char, and so on. Negative index
numbers count back from the end of the string:
It is a neat truism of slices that for any index n, s[:n] + s[n:] == s. This works even for n
negative or out of bounds. Or put another way s[:n] and s[n:] always partition the string into
two string parts, conserving all the characters. As we'll see in the list section later, slices work
with lists too.
Experimental Procedure-
73 Start Google Colab /python Installed on system with editor (like pycharm, jupyter)
74 Type a python program using input, output and calculations
75 Save the program
76 Execute it.
our_list=list()
word=fname.split()
for element in word:
our_list.append(element)
Results
Conclusions
Python has a built-in string class named "str" with many handy features Thorugh this experiment
we learnt to perform various operations on strings in python.