SlideShare une entreprise Scribd logo
1  sur  24
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

Contenu connexe

Tendances (20)

Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Python Lambda Function
Python Lambda FunctionPython Lambda Function
Python Lambda Function
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python basic
Python basicPython basic
Python basic
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Python set
Python setPython set
Python set
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
NUMPY
NUMPY NUMPY
NUMPY
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python list
Python listPython list
Python list
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 

En vedette

System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overviewRajKumar 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 cryptographyRajKumar Rampelli
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversRajKumar Rampelli
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginnersRajKumar Rampelli
 

En vedette (8)

System Booting Process overview
System Booting Process overviewSystem Booting Process overview
System Booting Process overview
 
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)
 
Network security and cryptography
Network security and cryptographyNetwork security and cryptography
Network security and cryptography
 
Linux Kernel I/O Schedulers
Linux Kernel I/O SchedulersLinux Kernel I/O Schedulers
Linux Kernel I/O Schedulers
 
Linux watchdog timer
Linux watchdog timerLinux watchdog timer
Linux watchdog timer
 
Introduction to Kernel and Device Drivers
Introduction to Kernel and Device DriversIntroduction to Kernel and Device Drivers
Introduction to Kernel and Device Drivers
 
Linux GIT commands
Linux GIT commandsLinux GIT commands
Linux GIT commands
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
 

Similaire à Learn python - for beginners - part-2

Similaire à Learn python - for beginners - part-2 (20)

Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptx
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 

Plus de 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 linuxRajKumar Rampelli
 
Introduction to Python - Running Notes
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running NotesRajKumar Rampelli
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewRajKumar Rampelli
 

Plus de 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
 
Introduction to Python - Running Notes
Introduction to Python - Running NotesIntroduction to Python - Running Notes
Introduction to Python - Running Notes
 
Linux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver OverviewLinux Kernel MMC Storage driver Overview
Linux Kernel MMC Storage driver Overview
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
Turing awards seminar
Turing awards seminarTuring awards seminar
Turing awards seminar
 
Higher education importance
Higher education importanceHigher education importance
Higher education importance
 
C compilation process
C compilation processC compilation process
C compilation process
 

Dernier

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 

Dernier (20)

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 

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