You are on page 1of 28

Procedure

List
1. Create a variable numberlist and assign it the value of [5,4,2,1,3].
numberlist = [5,4,2,1,3];
print(numberlist);

[5, 4, 2, 1, 3]

1. Print the following values below:


a. len(numberlist)
b. numberlist[0]
c. numberlist[1]
d. numberlist[2]
e. numberlist[3]
f. numberlist[4]
g. numberlist[5]
h. numberlist[-1]
i. numberlist[-2]
j. numberlist[-3]
k. numberlist[-4]
l. numberlist[-5]
m. numberlist[-6]
len(numberlist)

numberlist[0]

numberlist[1]

numberlist[2]

numberlist[3]
1

numberlist[4]

numberlist[5]

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/710259485.py in <module>
----> 1 numberlist[5]

IndexError: list index out of range

numberlist[-1]

numberlist[-2]

numberlist[-3]

numberlist[-4]

numberlist[-5]

numberlist[-6]

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/2890405402.py in <module>
----> 1 numberlist[-6]

IndexError: list index out of range

1. Write your observation after printing all the values. = It was accurate.
1. Create a variable named itemlist and assign it the value of [1,-2.0,[1,2,3],”Word”]
itemlist = [1,-2.0,[1,2,3],"Word"]
print(itemlist)
[1, -2.0, [1, 2, 3], 'Word']

1. Print the following values below:


a. len(itemlist)
b. itemlist [0]
c. itemlist [1]
d. itemlist [2]
e. itemlist [3]
f. len(itemlist[2])
g. itemlist [2][0]
h. itemlist [2][1]
i. itemlist [2][2]
j. itemlist [-1]
k. itemlist [-2]
l. itemlist [-3]
m. itemlist [-4]
n. len(itemlist[-2])
o. itemlist[-2][0]
p. itemlist[-2][1]
q. itemlist[-2][2]
r. itemlist[-2][-3]
s. itemlist[-2][-2]
t. itemlist[-2][-1]
len(itemlist)

itemlist [0]

itemlist [1]

-2.0
itemlist [2]

[1, 2, 3]

itemlist [3]

'Word'

len(itemlist[2])

itemlist [2][0]

itemlist [2][1]

itemlist [2][2]

itemlist [-1]

'Word'

itemlist [-2]

[1, 2, 3]

itemlist [-3]

-2.0

itemlist [-4]

len(itemlist[-2])

itemlist[-2][0]

itemlist[-2][1]

itemlist[-2][2]

3
itemlist[-2][-3]

itemlist[-2][-2]

itemlist[-2][-1]

1. Write your observation after printing all the values. What does len() do? = It inputs
the number of variables present based on the code.

Index Slicing
1. Create a new variable longlist and assign it the value of numberlist + itemlist.
longlist = [numberlist, itemlist]
print(longlist)

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

1. Print the following values below and write your observation for each of the
following sub-groups (sub-headings):
a. len(longlist)
b. longlist [:]
c. longlist[:9]
d. longlist[0:]
e. longlist[1:]
f. longlist[2:]
len(longlist)

longlist [:]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

longlist[:9]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

longlist[0:]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

longlist[1:]
[[1, -2.0, [1, 2, 3], 'Word']]

longlist[2:]

[]

g. longlist[2:5]
h. longlist[5:2]
i. longlist[8:]
j. longlist[9:]
longlist[2:5]

[]

longlist[5:2]

[]

longlist[8:]

[]

longlist[9:]

[]

k. longlist[-9:]
l. longlist[-8:]
m. longlist[-8:-7]
n. longlist[-1:]
longlist[-9:]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

longlist[-8:]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

longlist[-8:-7]

[]

longlist[-1:]

[[1, -2.0, [1, 2, 3], 'Word']]

o. longlist[10:20]
p. longlist[-7:5]
longlist[10:20]

[]

longlist[-7:5]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

q. longlist[::1]
r. longlist[::2]
s. longlist[1:8:2]
t. longlist[9:1:-1]
u. longlist[-1::1]
v. longlist[-1::-1]
longlist[::1]

[[5, 4, 2, 1, 3], [1, -2.0, [1, 2, 3], 'Word']]

longlist[::2]

[[5, 4, 2, 1, 3]]

longlist[1:8:2]

[[1, -2.0, [1, 2, 3], 'Word']]

longlist[9:1:-1]

[]

longlist[-1::1]

[[1, -2.0, [1, 2, 3], 'Word']]

longlist[-1::-1]

[[1, -2.0, [1, 2, 3], 'Word'], [5, 4, 2, 1, 3]]

1. Write your main observation about index slicing as a whole. = syntax that extracts a
portion from a list.

List Methods and the Mutable Property of Lists


1. Create a new variable numberlist2 and assign it to be equal to numberlist.
numberlist2 = [numberlist]

1. Print the value of numberlist.


print(numberlist)
[5, 4, 2, 1, 3]

1. Print the value of numberlist2.


print(numberlist2)

[[5, 4, 2, 1, 3]]

1. Assign the value of numberlist[0] to be equal to 6.


numberlist[0] = 6

1. Print the value of numberlist.


print(numberlist)

[6, 4, 2, 1, 3]

1. Print the value of numberlist2.


print(numberlist2)

[[6, 4, 2, 1, 3]]

1. Observe how numberlist2 is affected by changes in numberlist due to the


assignment.
2. Change the value of numberlist2 and assign it the value of numberlist.copy()
numberlist2 = [1,2,3,4,5]

numberlist2 = numberlist.copy()

1. Print the value of numberlist2


2. Assign the value of numberlist[0] to be equal to 5.

3. Print the value of numberlist.


4. Print the value of numberlist2.
print(numberlist)

[6, 4, 2, 1, 3]

print(numberlist2)

[6, 4, 2, 1, 3]

1. Write your observation about the immutable property and the difference of
assigning numberlist2 to be equal to numberlist and the numberlist.copy() method.
= In simple words, an immutable object can't be changed after it is created.

Exploring some List Functions and Methods


1. Print the value of numberlist
print(numberlist)

[6, 4, 2, 1, 3]
1. Run the command numberlist.append(6)
numberlist.append(6)

1. Print the value of numberlist


print(numberlist)

[6, 4, 2, 1, 3, 6]

1. Run the command numberlist.pop()


numberlist.pop()

1. Print the value of numberlist


print(numberlist)

[6, 4, 2, 1, 3]

1. Run the command numberlist.sort()


numberlist.sort()

1. Print the value of numberlist


print(numberlist)

[1, 2, 3, 4, 6]

1. Run the command itemlist.sort()


itemlist.sort()

----------------------------------------------------------------------
-----
TypeError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/1809657090.py in <module>
----> 1 itemlist.sort()

TypeError: '<' not supported between instances of 'list' and 'float'

1. Print the values: min(numberlist) and max(numberlist)


min(numberlist)

max(numberlist)

1. Print the value of longlist


print(longlist)

[[1, 2, 3, 4, 6], [1, -2.0, [1, 2, 3], 'Word']]


1. Print the value of longlist.count(1)
print(longlist.count(1) )

1. Print the value of longlist[7].count(1)


print(longlist[7].count(1) )

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/3243768911.py in <module>
----> 1 print(longlist[7].count(1) )

IndexError: list index out of range

The in operator
1. Type the code as shown: print(3 in longlist)
print(3 in longlist)

False

1. Type the code as shown: print(15 in longlist)


print(15 in longlist)

False

1. Type the code as shown below: num = int(input(“Enter a number: ”)) if num in
longlist: print(“The number is in longlist”) else: print(“The number is not in
longlist”)
num = int(input("Enter a number:") )
if num in longlist:
print("The number is in longlist")
else:
print("The number is not in longlist")

Enter a number:7
The number is not in longlist

1. Write your observations on the in operator. = it was accurate

Using a list in an iterative statement


1. Type the code as shown below: for item in longlist: print(item)
for item in longlist:
print(item)

[1, 2, 3, 4, 6]
[1, -2.0, [1, 2, 3], 'Word']
1. Type the code as shown below: i=0 while i<len(longlist): print(longlist[i]) i+=1
i=0
while i<len(longlist):
print(longlist[i])
i+=1

[1, 2, 3, 4, 6]
[1, -2.0, [1, 2, 3], 'Word']

Strings
1. Create a variable named message and assign it the value of “Hello World”
message = "Hello World"

1. Print the value of message


print(message)

Hello World

1. Print the value: len(message)


len(message)

11

1. Apply the concept of index values in the List section and individually display the
characters “H”, “E”, “L”, “L”, “O” using the print() function.
print(message[:1])

print(message[1:2])

print(message[2:3])

print(message[3:4])

print(message[4:5])

1. Apply the concept of index values in the List section and display the string “Hold”
using the Concatenate (+) operator on individual characters.
print(message[0]+ message[1]+ message[2]+ message[3]+ message[4])

Hello
1. Apply the concept of index slicing in the Index Slicing section and display the word
“Hello” as a whole string.
print(message[0:5])

Hello

1. Apply the concept of index slicing in the Index Slicing section and display the word
“World” as a whole string.
print(message[6:11])

World

String Methods
1. Type the command and print the value message.upper()
print(message.upper())

HELLO WORLD

1. Type the command and print the value message.lower()


print(message.lower())

hello world

1. Type the command and print the value message.title()


print(message.title())

Hello World

1. Print the value “Value 1 is {}, and value 2 is {}”.format(-1,True)


'Value 1 is {}, and value 2 is {}'.format(-1,True)

'Value 1 is -1, and value 2 is True'

1. Print the value message.split(' ')


message.split(' ')

['Hello', 'World']

1. Print the value message.count(‘l’)


message.count("l")

1. Print the value message.replace(‘World’,‘CPE009’)


message.replace("World","CPE009")

'Hello CPE009'

1. Assign the value message.replace(‘World’,‘CPE009’) to message


message = message.replace("World","CPE009")
1. Type the command: help(“”)
help("")

Help on class str in module builtins:

class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by
format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case
and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless
comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is
a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring
sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore',
'replace' and
| 'xmlcharrefreplace' as well as any other name registered
with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False
otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using
spaces.
|
| If tabsize is not given, a tab size of 8 characters is
assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args
and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from
mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False
otherwise.
|
| A string is alpha-numeric if all characters in the string are
alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False
otherwise.
|
| A string is alphabetic if all characters in the string are
alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False
otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False
otherwise.
|
| A string is a decimal string if all characters in the string
are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are
digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False
otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a
reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False
otherwise.
|
| A string is lowercase if all cased characters in the string
are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False
otherwise.
|
| A string is numeric if all characters in the string are
numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered
printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False
otherwise.
|
| A string is whitespace if all characters in the string are
whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False
otherwise.
|
| In a title-cased string, upper- and title-case characters may
only
| follow uncased characters and lowercase characters only cased
ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False
otherwise.
|
| A string is uppercase if all cased characters in the string
are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each
given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is
a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars
instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given
separator.
|
| This will search for the separator in the string. If the
separator is found,
| returns a 3-tuple containing the part before the separator,
the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing
the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return
string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is
not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the
original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced
by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count
occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is
a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given
separator.
|
| This will search for the separator in the string, starting at
the end. If
| the separator is found, returns a 3-tuple containing the part
before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing
two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the
delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any
whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| Splits are done starting at the end of the string and working
to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars
instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the words in the string, using sep as the
delimiter string.
|
| sep
| The delimiter according which to split the string.
| None (the default value) means split according to any
whitespace,
| and discard empty strings from the result.
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line
boundaries.
|
| Line breaks are not included in the resulting list unless
keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False
otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing
whitespace removed.
|
| If chars is given and not None, remove characters in chars
instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase
characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and
all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given
translation table.
|
| table
| Translation table, which must be a mapping of Unicode
ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for
instance a
| dictionary or list. If this operation raises LookupError, the
character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field
of the given width.
|
| The string is never truncated.
|
|
----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate
signature.
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping
Unicode
| ordinals (integers) or characters to Unicode ordinals, strings
or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal
length, and
| in the resulting dictionary, each character in x will be
mapped to the
| character at the same position in y. If there is a third
argument, it
| must be a string, whose characters will be mapped to None in
the result.

The in operator for Strings


1. Type the code as shown: print(‘W’ in message)
print('W' in message)

False

1. Type the code as shown: print(‘old’ in message)


print('old' in message)

False
1. Type the codes below: word = input(“Enter a word: ”) if word in “The big brown fox
jump over the lazy dog”: print(“The word is in the text”) else: print(“The word is not
in the text”)
word = input('Enter a word: ')
if word in 'The big brown fox jump over the lazy dog':
print('The word is in the text')
else:
print('The word is not in the text')

Enter a word: for


The word is not in the text

Using a String in an iterative statement


1. Type the code as shown below: for character in message: print(character)
for character in message:
print(character)

H
e
l
l
o

C
P
E
0
0
9

1. Type the code as shown below: i = 0 while i<len(message): print(message[i]) i+=1


i = 0
while i<len(message):
print(message[i])
i+=1

H
e
l
l
o

C
P
E
0
0
9
Tuples
1. Create a variable named tuplelist and assign the value of (1,2,3,4,5)
tuplelist = [1,2,3,4,5]

1. Print the following values:


a. numberlist[0]
b. numberlist[1]
c. numberlist[2]
d. numberlist[3]
e. numberlist[4]
f. numberlist[5]
numberlist[0]

numberlist[1]

numberlist[2]

numberlist[3]

numberlist[4]

numberlist[5]

----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/710259485.py in <module>
----> 1 numberlist[5]

IndexError: list index out of range

1. Print the output of tuplelist + (1,2,3)


tuplelist = [tuplelist, (1,2,3)]
print(tuplelist)

[[1, 2, 3, 4, 5], (1, 2, 3)]


1. Assign tuplelist[0] = 15
tuplelist[0] = 15

Dictionaries
1. Create a dictionary named
contactinfo = {‘id’:1, ’first_name’:’John’, ’last_name’:’Doe’,
’contact_number’:’09060611233’}
contactinfo = {'id':1, 'first_name':'John', 'last_name':'Doe',
'contact_number':'09060611233'}

1. Print the following values:


a. contactinfo[‘id’]
b. contactinfo[‘first_name’]
c. contactinfo[‘last_name’]
d. contactinfo[‘contact_number’]
e. contactinfo[‘age’]
contactinfo['id']

contactinfo['first_name']

'John'

contactinfo['last_name']

'Doe'

contactinfo['contact_number']

'09060611233'

contactinfo['age']

----------------------------------------------------------------------
-----
KeyError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/955849085.py in <module>
----> 1 contactinfo['age']

KeyError: 'age'

1. Type the code: for k,v in contactinfo: print(k)


for k,v in contactinfo:
print(k,)
i

----------------------------------------------------------------------
-----
ValueError Traceback (most recent call
last)
~\AppData\Local\Temp/ipykernel_2292/3266456221.py in <module>
----> 1 for k,v in contactinfo:
2 print(k,)

ValueError: too many values to unpack (expected 2)

1. Type the code: for k,v in contactinfo.items(): print(k,v)


for k,v in contactinfo.items():
print(k,v)

id 1
first_name John
last_name Doe
contact_number 09060611233

1. Assign the values:


a. contactinfo[‘id’] = 2
b. contactinfo[‘first_name’] = ‘Max’
contactinfo['id'] = 2

contactinfo['first_name'] = 'Max'

1. Print contactinfo
print(contactinfo)

{'id': 2, 'first_name': 'Max', 'last_name': 'Doe', 'contact_number':


'09060611233'}

Supplementary Activity:
Tasks
Distance Formula
Make a program that would calculate the distance between two points given a list of
coordinates. Use the distance formula
x1=int(input("enter x1 : "))

x2=int(input("enter x2 : "))

y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))

result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)

print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)

enter x1 : 1
enter x2 : 2
enter y1 : 4
enter y2 : 5
distance between (1, 2) and (4, 5) is : 1.4142135623730951

Simple Word Filler


For a given string input, replace all the words “stupid” with an asterisk * equal to the length
of the string. The new string value should be displayed with the asterisks.
i = "stupid"

j = str(input("Enter a phrase: "))

if i in j:

k = '*' * len(i)
print(j.replace('stupid',k))

else:
print(j)

Enter a phrase: I don't want to look stupid but every time I am with
you I will look stupid and do stupid things
I don't want to look ****** but every time I am with you I will look
****** and do ****** things

Phonebook
Create a simple phonebook program that can read from a list of dictionaries. The program
should be able to display a person’s name, contact, and address based from a user input
which is the id of the record.
id = str(input("Enter your ID:"))
name = str(input("Enter your Name:"))
contactinfo = str(input("Enter your Contact Number:"))
address = str(input("Enter your Address:"))

mylist = [{'ID':id}, {'Name':name}, {'Contact Number':contactinfo},


{"Address":address}]
print(mylist)

Enter your ID:123


Enter your Name:Kobe
Enter your Contact Number:091823533912
Enter your Address:Luzon
[{'ID': '123'}, {'Name': 'Kobe'}, {'Contact Number': '091823533912'},
{'Address': 'Luzon'}]

Questions
How do we display elements of lists, tuples, and strings? = In the case of lists or tuples,
they are made up of elements, which are values of any Python datatype, including other
lists and tuples. Lists are enclosed in square brackets ( [ and ] ) and tuples in parentheses
( ( and ) ).
What is the difference between a list, tuple, string and dictionary? Give possible use
case for each. = A list is a collection of ordered data. Lists are declared with square braces.
A tuple is an ordered collection of data. Tuples are enclosed within parenthesis. Strings are
arrays of bytes representing Unicode characters. A dictionary is an unordered collection of
data that stores data in key-value pairs. Dictionaries are enclosed in curly brackets in the
form of key-value pairs.
Discuss the various string methods that were used in the activity. What does each of
the methods do? index()-Searches the string for a specified value and returns the position
of where it was found, title()-Converts the first character of each word to upper case,
upper()-Converts a string into upper case, lower()-Converts a string into lower case,
count()-Returns the number of times a specified value occurs in a string, replace()-Returns
a string where a specified value is replaced with a specified value, split()-Splits the string at
the specified separator, and returns a list

Conclusion
I learned about working with strings, which are objects that contain sequences of character
data. Processing character data is integral to programming. It is a rare application that
doesn’t need to manipulate strings to at least some extent.
Python provides a rich set of operators, functions, and methods for working with strings. I
now know how to, use operators with strings, access and extract portions of strings, use
built-in Python functions with characters and strings, and use methods to manipulate and
modify string data

You might also like