SlideShare a Scribd company logo
Learn Python – for beginners
Part-2
Raj Kumar Rampelli
Outline
• Data Structures
– Lists
– Sets
– Dictionaries
– Tuples
• Difference Table List, Set, Dictionary and Tuple
• Exception Handling
– raise and assert
• Python sample programs
6/25/2016 Rajkumar Rampelli - Python 2
Lists
• Lists are used to store an indexed list of items
• A List is created using square brackets with commas separating
items
words = [“spam”, “eggs”, “world”]
- here, words is a List containing items “spam”, “eggs” and “world”
• Valid Lists are
– Words = []  empty list
– num = 3
Words = [“a”, [1, 2, num], 4.56]  Nested List
• Access items using index like arrays in C
Words = [“a”, [1, 2, 3], 4.56]
– Words[0]  “a”
– Words[1][1]  2
– Words[1]  [1, 2, 3]
6/25/2016 Rajkumar Rampelli - Python 3
List Errors
• Words = [1, 2, 3, 4]
• IndexError
– When try to access out of bound values
– Ex: Words[4] : IndexError
• TypeError
– When try to access integer or float types using index
– Ex: num = 456
num[0] : TypeError
• ValueError
– When try to access an item, but If the item isn't in the list, it raises a
ValueError.
– Words.index[10]  ValueError: 10 is not in the list.
• String Types can be accessed using index
– Ex: sample = “string”
sample[1]  ‘t’
6/25/2016 Rajkumar Rampelli - Python 4
List Operations
• Assignment
– The items at certain index in a list can be reassigned.
nums = [1, 2, 3]
nums[0] = 5
print(nums)  [5, 2, 3]
• Addition and Multiplication
– Lists can be added and multiplied in the same way as strings
– nums = [1, 2, 3]
print(nums + [4, 5, 6])  [1, 2, 3, 4, 5, 6]
print(nums * 2)  [1, 2, 3, 1, 2, 3]
List and Strings are common in many ways.
Strings can be thought of as Lists of characters that can’t be changed.
Ex: str = “Hello”
str[1] = “h” 
TypeError: 'str' object does not support item assignment.
6/25/2016 Rajkumar Rampelli - Python 5
List Functions
Function Description
list.append(item) Adds an item to the end of an existing list.
Nums = [1, 2, 3]
Nums.append(4)  [1, 2, 3, 4]
len() Get the number of items in a list. len(Nums)  4
list.insert(index, item) Allows to insert a new item at any position in the list.
Nums.insert(1, 10)  print(nums)  [1, 10, 2, 3, 4]
list.index(item) Finds the first occurrence of a list item and returns this index.
print(nums.index(10)) -> 1
print(nums.index(20)) -> ValueError: 20 is not in the list
max(list) Returns the list item with the maximum value
min(list) Returns the list item with the minimum value
list.count(item) Returns a count of how many times an item occurs in a list.
list.remove(item) Removes an item from a list
list.reverse() Reverses items in list
all and any Take a list as argument and return True if all or any (respectively) of their
arguments evaluate to True. Nums = [55, 44, 33]
If all([i>5 for i in nums]):
print("all are larger than 5")
If any([i%2 == 0 for i in nums]):
Print("atleast one is even")6/25/2016 Rajkumar Rampelli - Python 6
List Functions-2
List Function Usage
list(range(count)) Creates a sequential list of numbers. range by itself creates a range object,
and this must be converted to a list.
nums = list(range(5))
print(nums)  [0, 1, 2, 3, 4]
list(range(first, end)) Produces a list from first to the end.
nums = list(range(2, 7))
print(nums)  [2, 3, 4, 5, 6]
list(range(first, end, interval)) nums = list(range(2, 7, 2))
print(nums)  [2, 4, 6]
Enumerate() Used to iterate through the values and indices of list simultaneously.
nums = [55, 44, 33]
for v in enumerate(nums):
Print(v)
output:
(0, 55)
(1, 44)
(2, 33)
in operator To check if an item is in list or not.
print(55 in nums)  True
not operator To check if an item is not in list
print(22 not in nums)  True6/25/2016 Rajkumar Rampelli - Python 7
List Slice
• Provides a more advanced way of retrieving values from list
– Syntax: [start:end:step]
– If start is missing then it considers the list from start
– If end is missing then it considers till the last item
– If step value is missing then it consider as 1 by default
• squares = [0, 1, 4, 9, 16, 25]
squares[0:3]  [0, 1, 4]
squares[:4]  [0, 1, 4, 9]
squares[3:]  [9, 16, 25]
squares[0::2]  [0, 4, 16]
• Negative Indexing: When negative values are used for the first and
2nd values in a slice (or a normal index), they count from the end of
the list.
– squares[-3]  9
squares[-4:5]  [4, 9, 16]
squares[1:-3]  [1, 4]
– If the negative value used for step then the slice is done backwards
• [ : : -1]  is a common and idiomatic way to reverse a list.
6/25/2016 Rajkumar Rampelli - Python 8
List comprehension
• List comprehensions are a useful way of quickly creating lists whose
contents obey a simple rule.
Example:
cubes = [i**3 for i in range(5)]
print(cubes)  [0, 1, 8, 27, 64]
• A list comprehension can also contain an if statement to enforce a
condition on values in the list.
Example:
evens = [i**2 for i in range(10) if i**2 % 2 == 0]
print(evens)  [0, 4, 16, 36, 64]
• Trying to create a list in a very extensive range will result in a
MemoryError.
Example:
even = [2*i for i in range(10**1000)] -> MemoryError.
– This issue is solved by generators (will cover it in next slides)
6/25/2016 Rajkumar Rampelli - Python 9
Sets
• Sets are data structures similar to Lists
• Sets can created using set() call or curly braces { }
– nums = set()  Empty Set
Note: nums = { }  Creates an empty Dictionary
– nums = {1, 2, 3, 4}
• Sets are unordered, means they can’t be indexed.
• Sets doesn’t contain duplicate elements
• Function add() adds an item to the set.
• Function remove() removes an item from the set
• Function pop() removes an arbitrary item from set.
6/25/2016 Rajkumar Rampelli - Python 10
Sets – mathematical operations
• Sets can be combined with union, intersection and
other mathematical operators.
• union operator |
intersection operator &
difference operator –
symmetric difference ^
• first = {1, 2, 3, 4}
sec = {4, 5, 6}
print(first|sec)  {1, 2, 3, 4, 5, 6}
print(first&sec)  {4}
print(first-sec)  {1, 2, 3}
print(first^sec)  {1, 2, 3, 5, 6}
6/25/2016 Rajkumar Rampelli - Python 11
Dictionaries
• Dictionaries are data structures used to map arbitrary keys to values.
{"Key": Value}.
• Empty dictionary is { }
dict = { }
• Each element in a dictionary is represented by key:value pair
• Dictionary keys can be assigned to different values like lists.
• Trying to index a key that isn't part of the dictionary returns a KeyError.
• primary = {"red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255],}
print(primary["red"])  [255, 0, 0]
primary["white"]  [200, 140, 100]
primary["blue"]  [0, 0, 245]
print(primary["yellow"])  KeyError: "yellow“
• Dictionary can store any type of data as Value.
• Only immutable objects can be used as keys to dictionaries.
• List and dictionaries are mutable objects and hence can't be used as keys
in the dictionary.
• bad_dict = {[1, 2, 3]: "one two three",}  TypeError: unhashable type: list
6/25/2016 Rajkumar Rampelli - Python 12
Dictionary Functions
• Search : Use in and not in
Example:
nums = {1: "one", 2: "two", 3: "three",}
print(1 in nums) -> True
print(1 not in nums) -> False
print(4 not in nums) -> True
• get() : Used to get the values by its index, but if the key is not
found, it returns another specific value(2nd argument) instead
(None by default).
Example:
pairs = {1: "apple", "orange": [2, 3], True: False, None: "True",}
print(pairs.get("orange")) -> [2, 3]
print(pairs.get(7)) -> None
print(pairs.get(1234, "Not found")) -> Not found
6/25/2016 Rajkumar Rampelli - Python 13
Tuples
• Tuples are similar to lists, except that they are immutable (they can't be changed).
• Tuples are created using parenthesis, rather than square brackets.
words = () -> empty tuple
words = ("spam", "eggs")
or
words = "spam", "eggs"
• Tuple unpacking: It allows you to assign each item in an iterable to a variable.
numbers = (1, 2 ,3)
a, b, c = numbers
print(a) -> 1
print(b) -> 2
• Variable* : A variable that is prefaced with an asterisk(*) takes all values from the
iterable that are left over from the other variables
Example:
A, b, *c, d = [1, 2, 3, 4 ,5 ,6, 7]
print(a) -> 1
print(b) -> 2
print(c) ->[3, 4, 5, 6]
print(d) -> 7
6/25/2016 Rajkumar Rampelli - Python 14
List Vs Set Vs Dictionary Vs Tuple
Lists Sets Dictionaries Tuples
List = [10, 12, 15] Set = {1, 23, 34}
Print(set) -> {1, 23,24}
Set = {1, 1}
print(set) -> {1}
Dict = {"Ram": 26, "mary": 24} Words = ("spam", "egss")
Or
Words = "spam", "eggs"
Access: print(list[0]) Print(set).
Set elements can't be
indexed.
print(dict["ram"]) Print(words[0])
Can contains duplicate
elements
Can't contain duplicate
elements. Faster compared to
Lists
Can’t contain duplicate keys,
but can contain duplicate
values
Can contains duplicate
elements. Faster compared to
Lists
List[0] = 100 set.add(7) Dict["Ram"] = 27 Words[0] = "care" ->TypeError
Mutable Mutable Mutable Immutable - Values can't be
changed once assigned
List = [] Set = set() Dict = {} Words = ()
Slicing can be done
print(list[1:2]) -> [12]
Slicing: Not done. Slicing: Not done Slicing can also be done on
tuples
Usage:
Use lists if you have a
collection of data that doesn't
need random access.
Use lists when you need a
simple, iterable collection
that is modified frequently.
Usage:
- Membership testing and the
elimination of duplicate
entries.
- when you need uniqueness
for the elements.
Usage:
- When you need a logical
association b/w key:value
pair.
- when you need fast lookup
for your data, based on a
custom key.
- when your data is being
constantly modified.
Usage:
Use tuples when your data
cannot change.
A tuple is used in
comibnation with a
dictionary, for example, a
tuple might represent a key,
because its immutable.
6/25/2016 Rajkumar Rampelli - Python 15
Exception Handling
• Exceptions occur when something goes wrong, due to incorrect code or input. When an
exception occurs, the program immediately stops. How to Handle exceptions ?
• Use try and except statements. Useful when dealing with user input.
• The try block contains code that might throw an exception. If that exception occurs, the code
in the try block stops being executed, and the code in the except block is run. If no error
occurs, the code in the except block doesn't run.
Example:
try:
num1 = 7
num2 = 0
print(num1/num2)
except ZeroDivisionError:
print("An error occurred due to zero division")
except (ValueError, TypeError):
print("Error occurred")
finally:
print("This code will run no matters what")
Output: An error occurred due to zero division
This code will run no matters what
• The finally statement always runs after try/except blocks even in case of exception.
• An except statement without any exception specified will catch all errors.
6/25/2016 Rajkumar Rampelli - Python 16
Raise and Assert
• Raising exception: raise statement can be used to raise exception and specify the type of exception
raised. You can pass argument for details.
Example:
print(1)
raise ValueError
print(2)
raise NameError("Invalid name found")
• Assertions: An Assertion is a sanity-check that you can turn on or turn off when you have finished
testing the program. An expression is tested, and if the result comes up false, and exception is
raised. Programmers often place assertions at the start of a function to check for valid input, and
after a function call to check for valid output.
Example:
print(1)
assert 1 + 1 == 3
print(3)
Output:
1
AssertionError
• The assert can take a seconds argument that is passed to the AssertionError raised if the assertion
fails.
Example:
temp = -10
assert (temp >= 0), "Colder than absolute Zero!“
Output: o/p: AssertionError: Colder than absolute zero!
6/25/2016 Rajkumar Rampelli - Python 17
Generate Random Numbers
• Python module “random” will be used to
generate random numbers in program
– Need to import random module before using
• Example:
import random
for i in range(5):
val = random.randint(1, 6)
print(val)
Output: 5 random numbers will be printed in the
given range (1, 6)
6/25/2016 Rajkumar Rampelli - Python 18
Simple Calculator Program
# Calculator Program
while True:
print("Enter quit to exit the programn")
print("Enter 'add' for additionn")
print("Enter 'sub' for subtractionn")
print("Enter 'mul' for multiplicationn")
print("Enter 'div' for divisionn")
ip = input("Enter choice: ")
if ip == "quit":
print("exitn")
break;
else:
num1 = float(input())
num2 = float(input())
print("Output is: ")
if ip == "add":
print(num1+num2)
elif ip == "sub":
print(num1-num2)
elif ip == "mul":
print(num1*num2)
elif ip == "div":
try:
div = num1/num2
print(num1/num2)
except:
print("Exception occurred during divisionn")
Output:
Enter quit to exit the program
Enter 'add' for addition
Enter 'sub' for subtraction
Enter 'mul' for multiplication
Enter 'div' for division
Enter choice: add
100
200
Output is: 300.0
Output:
Enter quit to exit the program
Enter 'add' for addition
Enter 'sub' for subtraction
Enter 'mul' for multiplication
Enter 'div' for division
Enter choice: div
100
0
Output is: Exception occurred
during division
6/25/2016 Rajkumar Rampelli - Python 19
FizzBuzz Program: replacing any number divisible by three with the word
"fizz", and any number divisible by five with the word "buzz“ and if divisible
by three & five with word FizzBuzz
start = 1
end = 20
def is_divisible(start, div):
if start % div == 0:
return True
else:
return False
while start <= end:
if is_divisible(start, 3) and is_divisible(start, 5):
print("FizzBuzz")
elif is_divisible(start, 3):
print("Fizz")
elif is_divisible(start, 5):
print("Buzz")
else:
print(start)
start = start + 1
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
6/25/2016 Rajkumar Rampelli - Python 20
Dice Rolling Simulator program
import random
def get_random_integer(min, max):
return random.randint(min, max)
print("Dice Rolling Simulator Programn")
min = int(input("Enter minimum number: "))
max = int(input("Enter maximmum number: "))
inp = input("Do you want to roll the Dice, y or n ?: ")
while inp == "y":
print("Generated number: " + str(get_random_integer(min, max)))
inp = input("Do you want to roll the Dice, y or n ?: ")
Output:
Enter minimum number: 1
Enter maximum number: 6
Do you want to roll the Dice, y or n ?: y
Generated number: 3
Do you want to roll the Dice, y or n ?: y
Generated number: 5
Do you want to roll the Dice, y or n ?: n
6/25/2016 Rajkumar Rampelli - Python 21
Next: Part-3 will have followings. Stay Tuned..!!
• Python modules
• Regular expressions – tool for string
manipulations
• Standard libraries
• Object Oriented Programming
• Python Programs
6/25/2016 Rajkumar Rampelli - Python 22
References
• Install Learn Python (SoloLearn) from Google
Play :
https://play.google.com/store/apps/details?id
=com.sololearn.python&hl=en
• Learn Python the Harder Way :
http://learnpythonthehardway.org/
6/25/2016 Rajkumar Rampelli - Python 23
Thank you
• Have a look at
• My PPTs:
http://www.slideshare.net/rampalliraj/
• My Blog: http://practicepeople.blogspot.in/
6/25/2016 Rajkumar Rampelli - Python 24
Ad

More Related Content

What's hot (20)

Vector in R
Vector in RVector in R
Vector in R
venkata surya sunil Modekurthy
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
Megha V
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
Python Seaborn Data Visualization
Python Seaborn Data Visualization Python Seaborn Data Visualization
Python Seaborn Data Visualization
Sourabh Sahu
 
Python GUI
Python GUIPython GUI
Python GUI
LusciousLarryDas
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData
 
Introduction to Machine Learning with SciKit-Learn
Introduction to Machine Learning with SciKit-LearnIntroduction to Machine Learning with SciKit-Learn
Introduction to Machine Learning with SciKit-Learn
Benjamin Bengfort
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
Edureka!
 
Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
HarikaReddy115
 
Naive bayes
Naive bayesNaive bayes
Naive bayes
Ashraf Uddin
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
Siddique Ibrahim
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
Arockia Abins
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Machine Learning - Splitting Datasets
Machine Learning - Splitting DatasetsMachine Learning - Splitting Datasets
Machine Learning - Splitting Datasets
Andrew Ferlitsch
 
Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]
Alexander Hendorf
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
pandas: Powerful data analysis tools for Python
pandas: Powerful data analysis tools for Pythonpandas: Powerful data analysis tools for Python
pandas: Powerful data analysis tools for Python
Wes McKinney
 
Mining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsMining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and Correlations
Justin Cletus
 
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Edureka!
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
Megha V
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch
 
Python Seaborn Data Visualization
Python Seaborn Data Visualization Python Seaborn Data Visualization
Python Seaborn Data Visualization
Sourabh Sahu
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData
 
Introduction to Machine Learning with SciKit-Learn
Introduction to Machine Learning with SciKit-LearnIntroduction to Machine Learning with SciKit-Learn
Introduction to Machine Learning with SciKit-Learn
Benjamin Bengfort
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
Edureka!
 
Machine Learning - Splitting Datasets
Machine Learning - Splitting DatasetsMachine Learning - Splitting Datasets
Machine Learning - Splitting Datasets
Andrew Ferlitsch
 
Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]Introduction to Pandas and Time Series Analysis [PyCon DE]
Introduction to Pandas and Time Series Analysis [PyCon DE]
Alexander Hendorf
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
pandas: Powerful data analysis tools for Python
pandas: Powerful data analysis tools for Pythonpandas: Powerful data analysis tools for Python
pandas: Powerful data analysis tools for Python
Wes McKinney
 
Mining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and CorrelationsMining Frequent Patterns, Association and Correlations
Mining Frequent Patterns, Association and Correlations
Justin Cletus
 
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Python For Data Analysis | Python Pandas Tutorial | Learn Python | Python Tra...
Edureka!
 

Viewers also liked (8)

System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
RajKumar Rampelli
 
Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)
RajKumar Rampelli
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
RajKumar Rampelli
 
Linux Kernel I/O Schedulers
Linux Kernel I/O SchedulersLinux Kernel I/O Schedulers
Linux Kernel I/O Schedulers
RajKumar Rampelli
 
Linux watchdog timer
Linux watchdog timerLinux watchdog timer
Linux watchdog timer
RajKumar Rampelli
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
RajKumar Rampelli
 
Linux GIT commands
Linux GIT commandsLinux GIT commands
Linux GIT commands
RajKumar Rampelli
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
RajKumar Rampelli
 
Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)Tasklet vs work queues (Deferrable functions in linux)
Tasklet vs work queues (Deferrable functions in linux)
RajKumar Rampelli
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
RajKumar Rampelli
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
RajKumar Rampelli
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Ad

Similar to Learn python - for beginners - part-2 (20)

Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
Panimalar Engineering College
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Brief Explanation On List and Dictionaries of Python
Brief Explanation On List and Dictionaries of PythonBrief Explanation On List and Dictionaries of Python
Brief Explanation On List and Dictionaries of Python
nikhita4775
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
AnitaDevi158873
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
Programming with Python_Unit-3-Notes.pptx
Programming with Python_Unit-3-Notes.pptxProgramming with Python_Unit-3-Notes.pptx
Programming with Python_Unit-3-Notes.pptx
YugandharaNalavade
 
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffsR1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
sabari Giri
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptx
GaneshRaghu4
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
MihirDatir
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
Knoldus Inc.
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
Basil Bibi
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
datastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptxdatastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptxUNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
GaganRaj28
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Brief Explanation On List and Dictionaries of Python
Brief Explanation On List and Dictionaries of PythonBrief Explanation On List and Dictionaries of Python
Brief Explanation On List and Dictionaries of Python
nikhita4775
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
aiclub_slides
 
Programming with Python_Unit-3-Notes.pptx
Programming with Python_Unit-3-Notes.pptxProgramming with Python_Unit-3-Notes.pptx
Programming with Python_Unit-3-Notes.pptx
YugandharaNalavade
 
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffsR1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
R1-Intro (2udsjhfkjdshfkjsdkfhsdkfsfsffs
sabari Giri
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptx
GaneshRaghu4
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
MihirDatir
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
Knoldus Inc.
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
Basil Bibi
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
datastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptxdatastrubsbwbwbbwcturesinpython-3-4.pptx
datastrubsbwbwbbwcturesinpython-3-4.pptx
Farhana859326
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg  hghg hh ghg jh jhghj gj g.pptchap 06 hgjhg  hghg hh ghg jh jhghj gj g.ppt
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptxUNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
Ad

More from RajKumar Rampelli (7)

Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
RajKumar Rampelli
 
Introduction to Python - Running Notes
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running Notes
RajKumar Rampelli
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
RajKumar Rampelli
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
RajKumar Rampelli
 
Turing awards seminar
Turing awards seminarTuring awards seminar
Turing awards seminar
RajKumar Rampelli
 
Higher education importance
Higher education importanceHigher education importance
Higher education importance
RajKumar Rampelli
 
C compilation process
C compilation processC compilation process
C compilation process
RajKumar Rampelli
 
Writing Character driver (loadable module) in linux
Writing Character driver (loadable module) in linuxWriting Character driver (loadable module) in linux
Writing Character driver (loadable module) in linux
RajKumar Rampelli
 
Introduction to Python - Running Notes
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running Notes
RajKumar Rampelli
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
RajKumar Rampelli
 

Recently uploaded (20)

Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
National Information Standards Organization (NISO)
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Real GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for SuccessReal GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for Success
Mark Soia
 
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdfIntroduction-to-Communication-and-Media-Studies-1736283331.pdf
Introduction-to-Communication-and-Media-Studies-1736283331.pdf
james5028
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.03#UNTAGGED. Generosity in architecture.
03#UNTAGGED. Generosity in architecture.
MCH
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Real GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for SuccessReal GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for Success
Mark Soia
 

Learn python - for beginners - part-2

  • 1. Learn Python – for beginners Part-2 Raj Kumar Rampelli
  • 2. Outline • Data Structures – Lists – Sets – Dictionaries – Tuples • Difference Table List, Set, Dictionary and Tuple • Exception Handling – raise and assert • Python sample programs 6/25/2016 Rajkumar Rampelli - Python 2
  • 3. Lists • Lists are used to store an indexed list of items • A List is created using square brackets with commas separating items words = [“spam”, “eggs”, “world”] - here, words is a List containing items “spam”, “eggs” and “world” • Valid Lists are – Words = []  empty list – num = 3 Words = [“a”, [1, 2, num], 4.56]  Nested List • Access items using index like arrays in C Words = [“a”, [1, 2, 3], 4.56] – Words[0]  “a” – Words[1][1]  2 – Words[1]  [1, 2, 3] 6/25/2016 Rajkumar Rampelli - Python 3
  • 4. List Errors • Words = [1, 2, 3, 4] • IndexError – When try to access out of bound values – Ex: Words[4] : IndexError • TypeError – When try to access integer or float types using index – Ex: num = 456 num[0] : TypeError • ValueError – When try to access an item, but If the item isn't in the list, it raises a ValueError. – Words.index[10]  ValueError: 10 is not in the list. • String Types can be accessed using index – Ex: sample = “string” sample[1]  ‘t’ 6/25/2016 Rajkumar Rampelli - Python 4
  • 5. List Operations • Assignment – The items at certain index in a list can be reassigned. nums = [1, 2, 3] nums[0] = 5 print(nums)  [5, 2, 3] • Addition and Multiplication – Lists can be added and multiplied in the same way as strings – nums = [1, 2, 3] print(nums + [4, 5, 6])  [1, 2, 3, 4, 5, 6] print(nums * 2)  [1, 2, 3, 1, 2, 3] List and Strings are common in many ways. Strings can be thought of as Lists of characters that can’t be changed. Ex: str = “Hello” str[1] = “h”  TypeError: 'str' object does not support item assignment. 6/25/2016 Rajkumar Rampelli - Python 5
  • 6. List Functions Function Description list.append(item) Adds an item to the end of an existing list. Nums = [1, 2, 3] Nums.append(4)  [1, 2, 3, 4] len() Get the number of items in a list. len(Nums)  4 list.insert(index, item) Allows to insert a new item at any position in the list. Nums.insert(1, 10)  print(nums)  [1, 10, 2, 3, 4] list.index(item) Finds the first occurrence of a list item and returns this index. print(nums.index(10)) -> 1 print(nums.index(20)) -> ValueError: 20 is not in the list max(list) Returns the list item with the maximum value min(list) Returns the list item with the minimum value list.count(item) Returns a count of how many times an item occurs in a list. list.remove(item) Removes an item from a list list.reverse() Reverses items in list all and any Take a list as argument and return True if all or any (respectively) of their arguments evaluate to True. Nums = [55, 44, 33] If all([i>5 for i in nums]): print("all are larger than 5") If any([i%2 == 0 for i in nums]): Print("atleast one is even")6/25/2016 Rajkumar Rampelli - Python 6
  • 7. List Functions-2 List Function Usage list(range(count)) Creates a sequential list of numbers. range by itself creates a range object, and this must be converted to a list. nums = list(range(5)) print(nums)  [0, 1, 2, 3, 4] list(range(first, end)) Produces a list from first to the end. nums = list(range(2, 7)) print(nums)  [2, 3, 4, 5, 6] list(range(first, end, interval)) nums = list(range(2, 7, 2)) print(nums)  [2, 4, 6] Enumerate() Used to iterate through the values and indices of list simultaneously. nums = [55, 44, 33] for v in enumerate(nums): Print(v) output: (0, 55) (1, 44) (2, 33) in operator To check if an item is in list or not. print(55 in nums)  True not operator To check if an item is not in list print(22 not in nums)  True6/25/2016 Rajkumar Rampelli - Python 7
  • 8. List Slice • Provides a more advanced way of retrieving values from list – Syntax: [start:end:step] – If start is missing then it considers the list from start – If end is missing then it considers till the last item – If step value is missing then it consider as 1 by default • squares = [0, 1, 4, 9, 16, 25] squares[0:3]  [0, 1, 4] squares[:4]  [0, 1, 4, 9] squares[3:]  [9, 16, 25] squares[0::2]  [0, 4, 16] • Negative Indexing: When negative values are used for the first and 2nd values in a slice (or a normal index), they count from the end of the list. – squares[-3]  9 squares[-4:5]  [4, 9, 16] squares[1:-3]  [1, 4] – If the negative value used for step then the slice is done backwards • [ : : -1]  is a common and idiomatic way to reverse a list. 6/25/2016 Rajkumar Rampelli - Python 8
  • 9. List comprehension • List comprehensions are a useful way of quickly creating lists whose contents obey a simple rule. Example: cubes = [i**3 for i in range(5)] print(cubes)  [0, 1, 8, 27, 64] • A list comprehension can also contain an if statement to enforce a condition on values in the list. Example: evens = [i**2 for i in range(10) if i**2 % 2 == 0] print(evens)  [0, 4, 16, 36, 64] • Trying to create a list in a very extensive range will result in a MemoryError. Example: even = [2*i for i in range(10**1000)] -> MemoryError. – This issue is solved by generators (will cover it in next slides) 6/25/2016 Rajkumar Rampelli - Python 9
  • 10. Sets • Sets are data structures similar to Lists • Sets can created using set() call or curly braces { } – nums = set()  Empty Set Note: nums = { }  Creates an empty Dictionary – nums = {1, 2, 3, 4} • Sets are unordered, means they can’t be indexed. • Sets doesn’t contain duplicate elements • Function add() adds an item to the set. • Function remove() removes an item from the set • Function pop() removes an arbitrary item from set. 6/25/2016 Rajkumar Rampelli - Python 10
  • 11. Sets – mathematical operations • Sets can be combined with union, intersection and other mathematical operators. • union operator | intersection operator & difference operator – symmetric difference ^ • first = {1, 2, 3, 4} sec = {4, 5, 6} print(first|sec)  {1, 2, 3, 4, 5, 6} print(first&sec)  {4} print(first-sec)  {1, 2, 3} print(first^sec)  {1, 2, 3, 5, 6} 6/25/2016 Rajkumar Rampelli - Python 11
  • 12. Dictionaries • Dictionaries are data structures used to map arbitrary keys to values. {"Key": Value}. • Empty dictionary is { } dict = { } • Each element in a dictionary is represented by key:value pair • Dictionary keys can be assigned to different values like lists. • Trying to index a key that isn't part of the dictionary returns a KeyError. • primary = {"red": [255, 0, 0], "green": [0, 255, 0], "blue": [0, 0, 255],} print(primary["red"])  [255, 0, 0] primary["white"]  [200, 140, 100] primary["blue"]  [0, 0, 245] print(primary["yellow"])  KeyError: "yellow“ • Dictionary can store any type of data as Value. • Only immutable objects can be used as keys to dictionaries. • List and dictionaries are mutable objects and hence can't be used as keys in the dictionary. • bad_dict = {[1, 2, 3]: "one two three",}  TypeError: unhashable type: list 6/25/2016 Rajkumar Rampelli - Python 12
  • 13. Dictionary Functions • Search : Use in and not in Example: nums = {1: "one", 2: "two", 3: "three",} print(1 in nums) -> True print(1 not in nums) -> False print(4 not in nums) -> True • get() : Used to get the values by its index, but if the key is not found, it returns another specific value(2nd argument) instead (None by default). Example: pairs = {1: "apple", "orange": [2, 3], True: False, None: "True",} print(pairs.get("orange")) -> [2, 3] print(pairs.get(7)) -> None print(pairs.get(1234, "Not found")) -> Not found 6/25/2016 Rajkumar Rampelli - Python 13
  • 14. Tuples • Tuples are similar to lists, except that they are immutable (they can't be changed). • Tuples are created using parenthesis, rather than square brackets. words = () -> empty tuple words = ("spam", "eggs") or words = "spam", "eggs" • Tuple unpacking: It allows you to assign each item in an iterable to a variable. numbers = (1, 2 ,3) a, b, c = numbers print(a) -> 1 print(b) -> 2 • Variable* : A variable that is prefaced with an asterisk(*) takes all values from the iterable that are left over from the other variables Example: A, b, *c, d = [1, 2, 3, 4 ,5 ,6, 7] print(a) -> 1 print(b) -> 2 print(c) ->[3, 4, 5, 6] print(d) -> 7 6/25/2016 Rajkumar Rampelli - Python 14
  • 15. List Vs Set Vs Dictionary Vs Tuple Lists Sets Dictionaries Tuples List = [10, 12, 15] Set = {1, 23, 34} Print(set) -> {1, 23,24} Set = {1, 1} print(set) -> {1} Dict = {"Ram": 26, "mary": 24} Words = ("spam", "egss") Or Words = "spam", "eggs" Access: print(list[0]) Print(set). Set elements can't be indexed. print(dict["ram"]) Print(words[0]) Can contains duplicate elements Can't contain duplicate elements. Faster compared to Lists Can’t contain duplicate keys, but can contain duplicate values Can contains duplicate elements. Faster compared to Lists List[0] = 100 set.add(7) Dict["Ram"] = 27 Words[0] = "care" ->TypeError Mutable Mutable Mutable Immutable - Values can't be changed once assigned List = [] Set = set() Dict = {} Words = () Slicing can be done print(list[1:2]) -> [12] Slicing: Not done. Slicing: Not done Slicing can also be done on tuples Usage: Use lists if you have a collection of data that doesn't need random access. Use lists when you need a simple, iterable collection that is modified frequently. Usage: - Membership testing and the elimination of duplicate entries. - when you need uniqueness for the elements. Usage: - When you need a logical association b/w key:value pair. - when you need fast lookup for your data, based on a custom key. - when your data is being constantly modified. Usage: Use tuples when your data cannot change. A tuple is used in comibnation with a dictionary, for example, a tuple might represent a key, because its immutable. 6/25/2016 Rajkumar Rampelli - Python 15
  • 16. Exception Handling • Exceptions occur when something goes wrong, due to incorrect code or input. When an exception occurs, the program immediately stops. How to Handle exceptions ? • Use try and except statements. Useful when dealing with user input. • The try block contains code that might throw an exception. If that exception occurs, the code in the try block stops being executed, and the code in the except block is run. If no error occurs, the code in the except block doesn't run. Example: try: num1 = 7 num2 = 0 print(num1/num2) except ZeroDivisionError: print("An error occurred due to zero division") except (ValueError, TypeError): print("Error occurred") finally: print("This code will run no matters what") Output: An error occurred due to zero division This code will run no matters what • The finally statement always runs after try/except blocks even in case of exception. • An except statement without any exception specified will catch all errors. 6/25/2016 Rajkumar Rampelli - Python 16
  • 17. Raise and Assert • Raising exception: raise statement can be used to raise exception and specify the type of exception raised. You can pass argument for details. Example: print(1) raise ValueError print(2) raise NameError("Invalid name found") • Assertions: An Assertion is a sanity-check that you can turn on or turn off when you have finished testing the program. An expression is tested, and if the result comes up false, and exception is raised. Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output. Example: print(1) assert 1 + 1 == 3 print(3) Output: 1 AssertionError • The assert can take a seconds argument that is passed to the AssertionError raised if the assertion fails. Example: temp = -10 assert (temp >= 0), "Colder than absolute Zero!“ Output: o/p: AssertionError: Colder than absolute zero! 6/25/2016 Rajkumar Rampelli - Python 17
  • 18. Generate Random Numbers • Python module “random” will be used to generate random numbers in program – Need to import random module before using • Example: import random for i in range(5): val = random.randint(1, 6) print(val) Output: 5 random numbers will be printed in the given range (1, 6) 6/25/2016 Rajkumar Rampelli - Python 18
  • 19. Simple Calculator Program # Calculator Program while True: print("Enter quit to exit the programn") print("Enter 'add' for additionn") print("Enter 'sub' for subtractionn") print("Enter 'mul' for multiplicationn") print("Enter 'div' for divisionn") ip = input("Enter choice: ") if ip == "quit": print("exitn") break; else: num1 = float(input()) num2 = float(input()) print("Output is: ") if ip == "add": print(num1+num2) elif ip == "sub": print(num1-num2) elif ip == "mul": print(num1*num2) elif ip == "div": try: div = num1/num2 print(num1/num2) except: print("Exception occurred during divisionn") Output: Enter quit to exit the program Enter 'add' for addition Enter 'sub' for subtraction Enter 'mul' for multiplication Enter 'div' for division Enter choice: add 100 200 Output is: 300.0 Output: Enter quit to exit the program Enter 'add' for addition Enter 'sub' for subtraction Enter 'mul' for multiplication Enter 'div' for division Enter choice: div 100 0 Output is: Exception occurred during division 6/25/2016 Rajkumar Rampelli - Python 19
  • 20. FizzBuzz Program: replacing any number divisible by three with the word "fizz", and any number divisible by five with the word "buzz“ and if divisible by three & five with word FizzBuzz start = 1 end = 20 def is_divisible(start, div): if start % div == 0: return True else: return False while start <= end: if is_divisible(start, 3) and is_divisible(start, 5): print("FizzBuzz") elif is_divisible(start, 3): print("Fizz") elif is_divisible(start, 5): print("Buzz") else: print(start) start = start + 1 Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz 6/25/2016 Rajkumar Rampelli - Python 20
  • 21. Dice Rolling Simulator program import random def get_random_integer(min, max): return random.randint(min, max) print("Dice Rolling Simulator Programn") min = int(input("Enter minimum number: ")) max = int(input("Enter maximmum number: ")) inp = input("Do you want to roll the Dice, y or n ?: ") while inp == "y": print("Generated number: " + str(get_random_integer(min, max))) inp = input("Do you want to roll the Dice, y or n ?: ") Output: Enter minimum number: 1 Enter maximum number: 6 Do you want to roll the Dice, y or n ?: y Generated number: 3 Do you want to roll the Dice, y or n ?: y Generated number: 5 Do you want to roll the Dice, y or n ?: n 6/25/2016 Rajkumar Rampelli - Python 21
  • 22. Next: Part-3 will have followings. Stay Tuned..!! • Python modules • Regular expressions – tool for string manipulations • Standard libraries • Object Oriented Programming • Python Programs 6/25/2016 Rajkumar Rampelli - Python 22
  • 23. References • Install Learn Python (SoloLearn) from Google Play : https://play.google.com/store/apps/details?id =com.sololearn.python&hl=en • Learn Python the Harder Way : http://learnpythonthehardway.org/ 6/25/2016 Rajkumar Rampelli - Python 23
  • 24. Thank you • Have a look at • My PPTs: http://www.slideshare.net/rampalliraj/ • My Blog: http://practicepeople.blogspot.in/ 6/25/2016 Rajkumar Rampelli - Python 24