Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
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

More Related Content

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