SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot (20)

Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Gui programming
Gui programmingGui programming
Gui programming
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Data types in python
Data types in pythonData types in python
Data types in python
 
DataFrame in Python Pandas
DataFrame in Python PandasDataFrame in Python Pandas
DataFrame in Python Pandas
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to Learn python - for beginners - part-2

Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slidesaiclub_slides
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxGaneshRaghu4
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In ScalaKnoldus Inc.
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology InitiativeBasil Bibi
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsSreedhar Chowdam
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptxChandanVatsa2
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 

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)
 
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 Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
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
 

More from 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
 

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
 
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
 

Recently uploaded

4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 

Recently uploaded (20)

4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 

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