1. Computer Science with Python
Class: XII
Unit I: Computational Thinking and Programming -2
Chapter 1: Review of Python basics II (Revision Tour Class XI)
Mr. Vikram Singh Slathia
PGT Computer Science
2. Python
• In Slide I, we have learned about Python basic. In this s l i d e
we a re going to understand following concept with reference to
Python
Strings
Lists
Tuples
Dictionaries
3. String
Strings are arrays of bytes representing Unicode characters.
However, Python does not have a character data type, a single
character is simply a string with a length of 1. Square brackets
can be used to access elements of the string.
Strings in Python can be created using single quotes or double
quotes or even triple quotes.
# Creating a String with single Quotes
String1 = 'Welcome to World'
print("String with the use of Single Quotes: ")
print(String1)
4. # Creating a String with double Quotes
String1 = "I'm a boy"
print("nString with the use of Double Quotes: ")
print(String1)
# Creating a String with triple Quotes
String1 = '''I'm a boy'''
print("nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple Quotes allows multiple lines
String1 = '''India
For
Life'''
print("nCreating a multiline String: ")
print(String1)
5. Input ( ) always return input
in the form of a string.
String Literal
1. By assigning value directly to the variable
2. By taking Input
6. String Operators
There are 2operators that can be used to work upon
strings + and *.
» + (it is used to join two strings)
• “tea” + “pot” result “teapot”
• “1” + “2” result “12”
• “123” + “abc” result “123abc”
» * (it is used to replicate the string)
• 5*”@” result “@@@@@”
• “go!” * 3 result “go!go!go!”
7. String Slicing
• Look at following examples carefully-
word = “RESPONSIBILITY”
word[ 0 : 14 ] result ‘RESPONSIBILITY’
word[ 0 : 3] result ‘RES’
word[ 2 : 5 ] result ‘SPO’
word[ -7 : -3 ] result ‘IBIL’
word[ : 14 ] result ‘RESPONSIBILITY’
word[ : 5 ] result ‘RESPO’
word[ 3 : ] result ‘PONSIBILITY’
llhjh 1 2 3 4 5 6 7 8 9 10 11 12 13
E S P O N S I B I L I T Y
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
8. String Functions
• string.Isdecimal Returns true if all characters in a string are decimal
• String.Isalnum Returns true if all the characters in a given string are alphanumeric.
• string.Istitle Returns True if the string is a titlecased string
• String.partition splits the string at the first occurrence of the separator and returns a
tuple.
• String.Isidentifier Check whether a string is a valid identifier or not.
• String.len Returns the length of the string.
• String.rindex Returns the highest index of the substring inside the string if
substring is found.
• String.Max Returns the highest alphabetical character in a string.
• String.min Returns the minimum alphabetical character in a string.
• String.splitlines Returns a list of lines in the string.
• string.capitalize Return a word with its first character capitalized.
• string.find Return the lowest indexin a sub string.
9. • string.rfind find the highest index.
• string.count Return the number of (non-overlapping) occurrences of substring
sub in string
• string.lower Return a copy of s, but with upper case letters converted to lower
case.
• string.split Return a list of the words of the string,If the optional second
argument sep is absent or None
• string.rsplit() Return a list of the words of the string s, scanning s from the end.
• rpartition() Method splits the given string into three parts
• string.splitfields Return a list of the words of the string when only used with two
arguments.
• string.strip() It return a copy of the string with both leading and trailing
characters removed
• string.lstrip Return a copy of the string with leading characters removed.
• string.rstrip Return a copy of the string with trailing characters removed.
• string.swapcase Converts lower case letters to upper case and vice versa.
• string.upper lower case letters converted to upper case.
10. List
Lists are used to store multiple items in a single variable.
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.
Important Points:
➔ List is represented by square brackets [ ]
➔ List items are ordered, changeable, and allow duplicate values.
➔ List items are indexed, the first item has index [0], the second
item has index [1] etc.
11. ➔ 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.
For ex -
• [ ] Empty list
• [1, 2, 3] integers list
• [1, 2.5, 5.6, 9] numbers list (integer and float)
• [ ‘a’, ‘b’, ‘c’] characters list
• [‘a’, 1, ‘b’, 3.5, ‘zero’] mixed values list
• L = [ 3, 4, [ 5, 6 ], 7] Nested List
In Python, only list and dictionary are mutable data types, rest
of all the data types are immutable data types.
12. List slicing
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Output
['o', 'g', 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
13. append() and extend() method
We can add one item to a list using the append() method or
add several items using extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5] Output
odd.append(7)
print(odd) [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd) [1, 3, 5, 7, 9, 11, 13]
14. Operation of + and * operator
We can also use + operator to combine two lists. This is also
called concatenation.
The * operator repeats a list for the given number of times.
# Concatenating and repeating lists
odd = [1, 3, 5] Output
print(odd + [9, 7, 5]) [1, 3, 5, 9, 7, 5]
print(["re"] * 3) ['re', 're', 're']
16. Delete/Remove List Elements
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
• We can delete one or more items from a list using the
keyword del. It can even delete the list entirely.
del my_list[2] Output: ['p', 'r', 'b', 'l', 'e', 'm']
• We can use remove() method to remove the given item
17. my_list.remove('p') Output: ['r', 'o', 'b', 'l', 'e', 'm']
• The pop() method removes and returns the last item if
the index is not provided. This helps us implement lists
as stacks (first in, last out data structure).
print(my_list.pop(1)) Output: 'o'
• We can also use the clear() method to empty a list.
my_list.clear()
print(my_list) Output: []
18. Python List Methods
append() Add an element to the end of the list
extend() Add all elements of a list to the another list
insert() Insert an item at the defined index
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the number of items passed as
an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a shallow copy of the list
19. List Membership Test
We can test if an item exists in a list or not, using the keyword in.
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']
print('p' in my_list) Output: True
print('a' in my_list) Output: False
print('c' not in my_list) Output: True
20. Iterating Through a List
Using a for loop we can iterate through each item in a
list.
for fruit in ['apple','banana','mango']:
print("I like",fruit)
Output
I like apple
I like banana
I like mango
21. Difference between a List and a String
• Main difference between a List and a string is that
string is immutable whereas list is mutable.
• Individual values in string can’t be change whereas it is
possible with list.
22. Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage.
◦ A tuple is a collection which is ordered and unchangeable.
◦ Tuples are written with parentheses (), separated by commas.
◦ Tuple is an immutable sequence whose values can not be
changed.
23. Creation of Tuple
Look at following examples of tuple creation carefully:
Empty tuple my_tuple = ()
Tuple having integers my_tuple = (1, 2, 3)
Tuple with mixed datatypes my_tuple = (1, "Hello", 3.4)
nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
24. Tuple creation from list
Tuple creation from string
Creation of Tuple
tuple() function is used to create a tuple from other
sequences. See examples-
25. Tuple creation from input
All these elements are of character type. To have
these in different types, need to write following
statement.-
Tuple=eval(input(“Enter elements”))
26. Accessing a Tuple
• In Python, the process of tuple accessing is same as with list.
Like a list, we can access each and every element of a tuple.
• Similarity with List- like list, tuple also has index. All
functionality of a list and a tuple is same except mutability.
Forward index
Tuple
Backward index
• len ( ) function is used to get the length of tuple.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
R E S P O N S I B I L I T Y
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
27. Accessing a Tuple
• Indexing and Slicing:
• T[ i ] returns the item present at index i.
• T[ i : j ] returns a new tuple having all the
items of T from index i to j.
• T [ i : j : n ] returns a new tuple having difference of
n elements of T from index i to j.
28. Accessing a Tuple
• Accessing Individual elements-
• Traversal of a Tuple –
for <item> in <tuple>:
#to process every element.
30. Tuple will show till last element of list
irrespective of upper limit.
Every alternate element will be
shown.
Every third element will be
shown.
Tuple Slicing
31. Dictionary
Dictionaries are mutable, unordered collections with elements in
the form of a key:value pair that associate keys to value.
Dictionaries are also called associative array or mappings or
hashes.
To create a dictionary, you need to include the key:value pair
in curly braces.
Syntax:
<dictionary_name> ={<Key>:<Value>,<Key>:<Value>...}
32. Dictionary Creation
teachers={“Rajeev”: “Math”, “Ajay”: “Physics”, “Karan”: “CS”}
In above given example :
Name of the dictionary: teachers
Key-value pair Key Value
“Rajeev”:”Math” “Rajeev” “Math”
“Ajay”:”Physics” “Ajay” “Physics”
“Karan”:”CS” “Karan” “CS”
33. # this is an empty dictionary without any element.
Dict1= { }
Point to remember
◦ Keys should always be of immutable type.
◦ If you try to make keys as mutable, python shown error in
it.
◦ Internally, dictionaries are indexed on the basis of key.
34. Accessing a Dictionary
• To access a value from dictionary, we need to use key
similarly as we use an index to access a value from a list.
• We get the key from the pair of Key: value.
Syntax:
<dictionary_name> [key]
35. Here, notable thing is that every key of each
pair of dictionary d is coming in k variable of
loop. After this we can take output with the
given format and with print statement.
Traversal of a Dictionary
• To traverse a Dictionary, we use for loop. Syntax is-
for <item> in <dictionary>:
36. • To access key and value we need to use keys() and
values().
for example-
d.keys( ) function will display only key.
d.values ( ) function will display value only.
37. Creation of a Dictionary with the pair of name and value:
dict( ) constructor is used to create dictionary with the pairs
of key and value. There are various methods for this-
I. By passing Key:value pair as an argument:
The point to be noted is that here no inverted commas
were placed in
argument but they came automatically in dictionary.
II. By specifying Comma-separated key:value pair-
38. By passing tuple of
tuple
By passing tuple
of a list
By passing
List
III. By specifying Keys and values separately:
For this, we use zip() function in dict ( ) constructor-
IV. By giving Key:value pair in the form of separate sequence:
40. Nesting in Dictionary
look at the following example carefully in which element of a
dictionary is a dictionary itself.
41. Updation in a Dictionary
following syntax is used to update an element in Dictionary-
<dictionary>[<ExistingKey>]=<value>
42. Program to create a dictionary containing names of employee as
key and their salary as value.
output
43. Value did not return after
deletion.
Deletion of an element from a Dictionary
following two syntaxes can be used to delete an element form
a Dictionary. For deletion, key should be there otherwise
python will give error.
1. Del <dictionary>[<key>]
It only deletes the value and does not return deleted
value.
2. <dictionary>.pop(<key>)
It returns the deleted value after deletion.
44. <key> not in
<dictionary>
<key> in
<dictionary>
* in and not in
does not apply on
values, they can
only work with
keys.
Detection of an element from a Dictionary
Membership operator is used to detect presence of an element
in a Dictionary.
it gives true on finding the key
otherwise gives false.
it gives true on not finding the key
otherwise gives false.
45. json.dumps(<>,indent=
<n>)
Pretty Printing of a Dictionary
To print a Dictionary in a beautify manner, we need to
import json module.
After that following syntax of dumps ( ) will be used.
48. Dictionary Function and Method
1. len( ) Method : it tells the length of dictionary.
2. clear( ) Method : it empties the dictionary.
3. get( ) Method : it returns value of the given key.
4. items( ) Method : it returns all items of a dictionary in the
form of tuple of (key:value).
5. keys( ) Method : it returns list of dictionary keys.
6. values( ) Method : it returns list of dictionary values.
7. Update ( ) Method: This function merge the pair of key:value
of a dictionary into other dictionary.
Change and addition in this is possible as
per need.
49. Sorting
Sorting refer to arrangement of element in specific order.
Ascending or descending
In our syllabus there are only two sorting techniques:
1. Bubble Sort
The basic idea of bubble sort is to compare two adjoining values and
exchange them if they are not in proper order.
2. Insertion Sort
It is a sorting algorithm that builds a sorted list one element at a
time from the unsorted list by inserting the element at its
correct position in sorted list.
It take maximum n-1 passes to sort all the elements of an n-size array.
50. For reference you check out online
• https://www.programiz.com/python-
programming/first-program
• https://www.w3schools.com/python/
default.asp
51. Python Revision Tour of Class XI is covered.
In next Slide we are going to Discuss topic:
Working with Function