SlideShare ist ein Scribd-Unternehmen logo
1 von 51
Downloaden Sie, um offline zu lesen
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
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
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)
# 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)
Input ( ) always return input
in the form of a string.
String Literal
1. By assigning value directly to the variable
2. By taking Input
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!”
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
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.
• 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.
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.
➔ 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.
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']
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]
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']
insert() Method
Demonstration of list insert() method
odd = [1, 9] Output
odd.insert(1,3)
print(odd) [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) [1, 3, 5, 7, 9]
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
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: []
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
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
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
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.
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.
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))
Tuple creation from list
Tuple creation from string
Creation of Tuple
tuple() function is used to create a tuple from other
sequences. See examples-
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”))
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
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.
Accessing a Tuple
• Accessing Individual elements-
• Traversal of a Tuple –
for <item> in <tuple>:
#to process every element.
OUTPU
T
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
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>...}
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”
# 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.
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]
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>:
• 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.
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-
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:
Adding an element in Dictionary
Nesting in Dictionary
look at the following example carefully in which element of a
dictionary is a dictionary itself.
Updation in a Dictionary
following syntax is used to update an element in Dictionary-
<dictionary>[<ExistingKey>]=<value>
Program to create a dictionary containing names of employee as
key and their salary as value.
output
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.
<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.
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.
Program to create a dictionary by counting words in a line
Here a
dictionary is
created of
words and
their
frequency.
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.
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.
For reference you check out online
• https://www.programiz.com/python-
programming/first-program
• https://www.w3schools.com/python/
default.asp
Python Revision Tour of Class XI is covered.
In next Slide we are going to Discuss topic:
Working with Function

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
List in Python
List in PythonList in Python
List in Python
 
12 SQL
12 SQL12 SQL
12 SQL
 
Python list
Python listPython list
Python list
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Python Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular ExpressionsPython Programming - XI. String Manipulation and Regular Expressions
Python Programming - XI. String Manipulation and Regular Expressions
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
Array in c
Array in cArray in c
Array in c
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
11 Unit 1 Problem Solving Techniques
11  Unit 1 Problem Solving Techniques11  Unit 1 Problem Solving Techniques
11 Unit 1 Problem Solving Techniques
 
Data Handling
Data HandlingData Handling
Data Handling
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Strings in C
Strings in CStrings in C
Strings in C
 
C tokens
C tokensC tokens
C tokens
 

Ähnlich wie Python revision tour II

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Python Collections
Python CollectionsPython Collections
Python Collectionssachingarg0
 
Python data type
Python data typePython data type
Python data typeJaya Kumari
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptxmohitesoham12
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxGaneshRaghu4
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningTURAGAVIJAYAAKASH
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat SheetVerxus
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfElNew2
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdfking931283
 

Ähnlich wie Python revision tour II (20)

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Python data type
Python data typePython data type
Python data type
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptx
 
2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf2. Python Cheat Sheet.pdf
2. Python Cheat Sheet.pdf
 
python cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learningpython cheat sheat, Data science, Machine learning
python cheat sheat, Data science, Machine learning
 
Beginner's Python Cheat Sheet
Beginner's Python Cheat SheetBeginner's Python Cheat Sheet
Beginner's Python Cheat Sheet
 
beginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdfbeginners_python_cheat_sheet_pcc_all (1).pdf
beginners_python_cheat_sheet_pcc_all (1).pdf
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdf
 
Numpy
NumpyNumpy
Numpy
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 

Mehr von Mr. Vikram Singh Slathia (13)

Marks for Class X Board Exams 2021 - 01/05/2021
Marks for Class X Board Exams 2021 - 01/05/2021Marks for Class X Board Exams 2021 - 01/05/2021
Marks for Class X Board Exams 2021 - 01/05/2021
 
Parallel Computing
Parallel Computing Parallel Computing
Parallel Computing
 
Online exam series
Online exam seriesOnline exam series
Online exam series
 
Online examination system
Online examination systemOnline examination system
Online examination system
 
Parallel sorting
Parallel sortingParallel sorting
Parallel sorting
 
Changing education scenario of india
Changing education scenario of indiaChanging education scenario of india
Changing education scenario of india
 
Gamec Theory
Gamec TheoryGamec Theory
Gamec Theory
 
Multiprocessor system
Multiprocessor system Multiprocessor system
Multiprocessor system
 
Sarasvati Chalisa
Sarasvati ChalisaSarasvati Chalisa
Sarasvati Chalisa
 
Pushkar
PushkarPushkar
Pushkar
 
Save girl child to save your future
Save girl child to save your futureSave girl child to save your future
Save girl child to save your future
 
 Reuse Plastic Bottles.
 Reuse Plastic Bottles. Reuse Plastic Bottles.
 Reuse Plastic Bottles.
 
5 Pen PC Technology (P-ISM)
5 Pen PC Technology (P-ISM)5 Pen PC Technology (P-ISM)
5 Pen PC Technology (P-ISM)
 

Kürzlich hochgeladen

4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 

Kürzlich hochgeladen (20)

4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 

Python revision tour II

  • 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']
  • 15. insert() Method Demonstration of list insert() method odd = [1, 9] Output odd.insert(1,3) print(odd) [1, 3, 9] odd[2:2] = [5, 7] print(odd) [1, 3, 5, 7, 9]
  • 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:
  • 39. Adding an element in Dictionary
  • 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.
  • 46. Program to create a dictionary by counting words in a line
  • 47. Here a dictionary is created of words and their frequency.
  • 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