SlideShare a Scribd company logo
Day 1


String, Control Flow, Data Structure




                                       Day 1
String
Introduction
String Methods
Multi-line String
String Formating
Unicode String
Iterating, Searching, Comparison



                                   Day 1
String : Introduction
Python has a built-in string class named "str"
A "raw" string literal is prefixed by an 'r'
Python strings are "immutable"
Characters in a string can be accessed using
[index]
Unlike Java, the '+' does not automatically convert
numbers or other types to string form


                                                 Day 1
String : Methods
s.lower(), s.upper()
s.strip()
s.isalpha(), s.isdigit(), s.isspace()
s.find('other')
s.replace('old', 'new')
s.split('delim')
s.join(list)
s.center(width[, fillchar])
                                        Day 1
String : Multi-Line
Declare String
  Using Single Quotes (')
  Using Double Quotes (")
  Using Triple Quotes (''' or """)
raw = r'thistn and that'
multi = r"""It was the best of times.
It was the worst of times."""


                                        Day 1
String : Formating
str.format(*args, **kwargs)
% operator
  text = ("%d little pigs come out or I'll %s and %s and
    %s" % (3, 'huff', 'puff', 'blow down'))
  '%(language)s has %(number)03d quote types.' %
    {"language": "Python", "number": 2}
String = 'What's' 'your name?'



                                                       Day 1
String : Unicode
Define Unicode string
  ustring = u'A unicode u018e string xf1'
  type(ustring)
     <type 'unicode'>

Unicode to UTF-8
  nstr = ustring.encode('utf-8')
  type(nstr)
     <type 'str'>

UTF-8 to Unicode
                                              Day 1
String : Iterating, Searching, Comparison
Loop on string
  for s in str:
Check existence of sting
  s in str ?
Comparison of 2 strings
  ==
  <=
  >=
  !=
                                            Day 1
Control Flow
Condition checking
Loops
  For
  While
break, continue, else and pass statement
Range
  Range(10)
  Range(1, 10)
  Range(0, 10, 3)
                                           Day 1
Control Flow : Condition checking
>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...   x=0
...   print 'Negative changed to zero'
... elif x == 0:
...   print 'Zero'
... elif x == 1:
                                                Day 1
Control Flow : for loop
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...   print x, len(x)
...


>>> for x in a[:]: # make a slice copy of the entire
 list
                                                  Day 1
Control Flow : break, continue and else
Loop statements may have an else clause;
it is executed when the loop terminates through
   exhaustion of the list - (with for)
when the condition becomes false - (with while)
not when the loop is terminated by a break
 statement




                                              Day 1
Control Flow : for …. else
for n in range(2, 10):
...   for x in range(2, n):
...     if n % x == 0:
...           print n, 'equals', x, '*', n/x
...           break
...   else:
...     # loop fell through without finding a factor
...     print n, 'is a prime number'
                                                  Day 1
Control Flow : pass
The pass statement does nothing
Pass in loops
  >>> while True:
  ...   pass # Busy-wait for keyboard interrupt (Ctrl+C)
Empty Class
  >>> class MyEmptyClass:
  ...   pass
  ...

                                                     Day 1
Control Flow : pass
Empty Method
  >>> def initlog(*args):
  ...   pass # Remember to implement this!
  ...




                                             Day 1
Control Flow : range
>>> range(5, 10)
  [5, 6, 7, 8, 9]
>>> range(0, 10, 3)
  [0, 3, 6, 9]
>>> range(-10, -100, -30)
  [-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
         ...   print i, a[i]
                                                 Day 1
Data Structure
Python built-in types
  Tuple
  List
  Dict
Usage
  List Methods
  Dict Methods
  Dict Formatting

                        Day 1
Data Structure : tuple
Tuples, like strings, are immutable:
it is not possible to assign to the individual items
   of a tuple
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
                                                  Day 1
Data Structure : tuple reverse assignment
Creating Tuple
>>> t = 12345, 54321, 'hello!'
>>> type(t)
<type 'tuple'>
>>> t
(12345, 54321, 'hello!')
Reverse Operation
>>> x, y, z = t
                                            Day 1
Data Structure : list
Python has a great built-in list type named "list"
lst = [], <type 'list'>
Create a new list
  colors = ['red', 'blue', 'green']
  print colors[0]   ## red
  print colors[2]   ## green
  print len(colors) ## 3
Assignment of list
  b = colors ## Does not copy the list
                                                     Day 1
Data Structure : working with list
L is t B u ild U p
list = []         ## Start as the empty list
list.append('a') ## Use append() to add
   elements
list.append('b')
L is t S lic e s
list = ['a', 'b', 'c', 'd']
print list[1:-1] ## ['b', 'c']
                                               Day 1
Data Structure : list methods
>>> list = ['larry', 'curly', 'moe']
>>> list.append('shemp')               ## append elem
 at end
>>> list.insert(0, 'xxx')       ## insert elem at
 index 0
>>> list.extend(['yyy', 'zzz']) ## add list of
 elems at end
>>> print list ## ['xxx', 'larry', 'curly', 'moe',
 'shemp', 'yyy', 'zzz']                              Day 1
Data Structure : iterations over list
Using for loop
  for var in list


>>> squares = [1, 4, 9, 16]
>>> sum = 0
>>> for num in squares:
>>> … sum += num
>>> … print sum ## 30
                                        Day 1
Data Structure : dict
Python's efficient key/value hash table structure
 is called a "dict"
The contents of a dict can be written as a series
 of key:value pairs
e.g. dict = {key1:value1, key2:value2, ... }
The "empty dict" is just an empty pair of curly
 braces {}
Looking up or setting a value in a dict uses
 square brackets. e.g. dict['foo']
                                                  Day 1
Data Structure : creating dict
## Can build up a dict by starting with the the
 empty dict {}
## and storing key/value pairs into the dict like
 this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'                                 Day 1
Data Structure : Iteration on key or value
## By default, iterating over a dict iterates over its
 keys.
## Note that the keys are in a random order.
for key in dict: print key
## prints a g o


## Exactly the same as above
for key in dict.keys(): print key
                                                   Day 1
Data Structure: Iteration on key and value
## This loop syntax accesses the whole dict by
 looping
## over the .items() tuple list, accessing one (key,
 value)
## pair on each iteration.
for k, v in dict.items():
print k, '>', v
## a > alpha      o > omega   g > gamma

                                                 Day 1
Data Structure : del an item
var = 6
del var # var no more!


list = ['a', 'b', 'c', 'd']
del list[0]      ## Delete first element
del list[-2:] ## Delete last two elements
print list      ## ['b']

                                            Day 1
Data Structure : sorting
The easiest way to sort is with the sorted(list)
 function
The sorted() function seems easier to use
 compared to sort()
The sorted() function can be customized though
 optional arguments
The sorted() optional argument reverse=True
Custom Sorting With key=

                                                   Day 1
Data Structure : working with sorted( )
S o r t in g N u m b e r s
a = [5, 1, 4, 3]
print sorted(a) ## [1, 3, 4, 5]
print a ## [5, 1, 4, 3]
S o r t in g S t r in g
strs = ['aa', 'BB', 'zz', 'CC']
print sorted(strs) ## ['BB', 'CC', 'aa', 'zz'] (case
  sensitive)
                                                       Day 1
Data Structure : Custom Sorting with key
strs = ['ccc', 'aaaa', 'd', 'bb']
print sorted(strs, key=len) ## ['d', 'bb', 'ccc',
  'aaaa']




                                                    Day 1
Data Structure : Custom comparator
## Say we have a list of strings we want to sort by the
  last letter of the string.

strs = ['xc', 'zb', 'yd' ,'wa']


## Write a little function that takes a string, and returns
  its last letter.
## This will be the key function (takes in 1 value, returns
  1 value).

def MyComparator(s):
                                                          Day 1
Next Session ?
Function
  Dynamic Functions
Object Oriented
  Class
  Inheritance
  Method Overload, Override
Python Packaging
  __init__.py

                              Day 1
Contact me...

           Mantavya Gajjar

           Phone : 94263 40093

      Email : mail@mantavyagajjar.in

     Website : www.opentechnologies.in

    Follow on Twitter : @mantavyagajjar

                                          Day 1

More Related Content

What's hot

Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
sxw2k
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
Chan Shik Lim
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v PythonuJirka Vejrazka
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Matt Harrison
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
Tendayi Mawushe
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Hammurabi
HammurabiHammurabi
Hammurabi
Mario Fusco
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
Dr. Volkan OBAN
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
Sayed Ahmed
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
osfameron
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
Saeid Zebardast
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
Benjamin Waye
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
Suyeol Jeon
 

What's hot (20)

Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v Pythonu
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 

Similar to Python Day1

R programming
R programmingR programming
R programming
Pramodkumar Jha
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
Josh Doyle
 
R Basics
R BasicsR Basics
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
Kevin Chun-Hsien Hsu
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
Chaithanya89350
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
MihirDatir
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
Alicia Pérez
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
AnirudhaGaikwad4
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
Raji Engg
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 

Similar to Python Day1 (20)

R programming
R programmingR programming
R programming
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
R Basics
R BasicsR Basics
R Basics
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
 
R교육1
R교육1R교육1
R교육1
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Becoming a Pythonist
Becoming a PythonistBecoming a Pythonist
Becoming a Pythonist
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 

More from Mantavya Gajjar

Python day2
Python day2Python day2
Python day2
Mantavya Gajjar
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
Mantavya Gajjar
 
FDP Event Report
FDP Event Report FDP Event Report
FDP Event Report
Mantavya Gajjar
 
Demonstrate OpenERP
Demonstrate OpenERPDemonstrate OpenERP
Demonstrate OpenERP
Mantavya Gajjar
 
ERP Implementation cycle
ERP Implementation cycleERP Implementation cycle
ERP Implementation cycle
Mantavya Gajjar
 
Point of Sale - OpenERP 6.1
Point of Sale - OpenERP 6.1Point of Sale - OpenERP 6.1
Point of Sale - OpenERP 6.1Mantavya Gajjar
 
Project Management
Project ManagementProject Management
Project Management
Mantavya Gajjar
 
Order to cash flow
Order to cash flowOrder to cash flow
Order to cash flow
Mantavya Gajjar
 
Installation
Installation Installation
Installation
Mantavya Gajjar
 
Education Portal
Education PortalEducation Portal
Education Portal
Mantavya Gajjar
 
Subscription
SubscriptionSubscription
Subscription
Mantavya Gajjar
 
Payroll
PayrollPayroll
Account voucher
Account voucherAccount voucher
Account voucher
Mantavya Gajjar
 
Send Mail
Send MailSend Mail
Send Mail
Mantavya Gajjar
 

More from Mantavya Gajjar (16)

Python day2
Python day2Python day2
Python day2
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
FDP Event Report
FDP Event Report FDP Event Report
FDP Event Report
 
Demonstrate OpenERP
Demonstrate OpenERPDemonstrate OpenERP
Demonstrate OpenERP
 
ERP Implementation cycle
ERP Implementation cycleERP Implementation cycle
ERP Implementation cycle
 
Point of Sale - OpenERP 6.1
Point of Sale - OpenERP 6.1Point of Sale - OpenERP 6.1
Point of Sale - OpenERP 6.1
 
About OpenEPR
About OpenEPRAbout OpenEPR
About OpenEPR
 
Project Management
Project ManagementProject Management
Project Management
 
Order to cash flow
Order to cash flowOrder to cash flow
Order to cash flow
 
Installation
Installation Installation
Installation
 
Education Portal
Education PortalEducation Portal
Education Portal
 
Tiny-Sugar Guide
Tiny-Sugar GuideTiny-Sugar Guide
Tiny-Sugar Guide
 
Subscription
SubscriptionSubscription
Subscription
 
Payroll
PayrollPayroll
Payroll
 
Account voucher
Account voucherAccount voucher
Account voucher
 
Send Mail
Send MailSend Mail
Send Mail
 

Recently uploaded

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 

Python Day1

  • 1. Day 1 String, Control Flow, Data Structure Day 1
  • 2. String Introduction String Methods Multi-line String String Formating Unicode String Iterating, Searching, Comparison Day 1
  • 3. String : Introduction Python has a built-in string class named "str" A "raw" string literal is prefixed by an 'r' Python strings are "immutable" Characters in a string can be accessed using [index] Unlike Java, the '+' does not automatically convert numbers or other types to string form Day 1
  • 4. String : Methods s.lower(), s.upper() s.strip() s.isalpha(), s.isdigit(), s.isspace() s.find('other') s.replace('old', 'new') s.split('delim') s.join(list) s.center(width[, fillchar]) Day 1
  • 5. String : Multi-Line Declare String Using Single Quotes (') Using Double Quotes (") Using Triple Quotes (''' or """) raw = r'thistn and that' multi = r"""It was the best of times. It was the worst of times.""" Day 1
  • 6. String : Formating str.format(*args, **kwargs) % operator text = ("%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')) '%(language)s has %(number)03d quote types.' % {"language": "Python", "number": 2} String = 'What's' 'your name?' Day 1
  • 7. String : Unicode Define Unicode string ustring = u'A unicode u018e string xf1' type(ustring) <type 'unicode'> Unicode to UTF-8 nstr = ustring.encode('utf-8') type(nstr) <type 'str'> UTF-8 to Unicode Day 1
  • 8. String : Iterating, Searching, Comparison Loop on string for s in str: Check existence of sting s in str ? Comparison of 2 strings == <= >= != Day 1
  • 9. Control Flow Condition checking Loops For While break, continue, else and pass statement Range Range(10) Range(1, 10) Range(0, 10, 3) Day 1
  • 10. Control Flow : Condition checking >>> x = int(raw_input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x=0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: Day 1
  • 11. Control Flow : for loop >>> # Measure some strings: ... a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ... >>> for x in a[:]: # make a slice copy of the entire list Day 1
  • 12. Control Flow : break, continue and else Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list - (with for) when the condition becomes false - (with while) not when the loop is terminated by a break statement Day 1
  • 13. Control Flow : for …. else for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' Day 1
  • 14. Control Flow : pass The pass statement does nothing Pass in loops >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) Empty Class >>> class MyEmptyClass: ... pass ... Day 1
  • 15. Control Flow : pass Empty Method >>> def initlog(*args): ... pass # Remember to implement this! ... Day 1
  • 16. Control Flow : range >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] Day 1
  • 17. Data Structure Python built-in types Tuple List Dict Usage List Methods Dict Methods Dict Formatting Day 1
  • 18. Data Structure : tuple Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple >>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') Day 1
  • 19. Data Structure : tuple reverse assignment Creating Tuple >>> t = 12345, 54321, 'hello!' >>> type(t) <type 'tuple'> >>> t (12345, 54321, 'hello!') Reverse Operation >>> x, y, z = t Day 1
  • 20. Data Structure : list Python has a great built-in list type named "list" lst = [], <type 'list'> Create a new list colors = ['red', 'blue', 'green'] print colors[0] ## red print colors[2] ## green print len(colors) ## 3 Assignment of list b = colors ## Does not copy the list Day 1
  • 21. Data Structure : working with list L is t B u ild U p list = [] ## Start as the empty list list.append('a') ## Use append() to add elements list.append('b') L is t S lic e s list = ['a', 'b', 'c', 'd'] print list[1:-1] ## ['b', 'c'] Day 1
  • 22. Data Structure : list methods >>> list = ['larry', 'curly', 'moe'] >>> list.append('shemp') ## append elem at end >>> list.insert(0, 'xxx') ## insert elem at index 0 >>> list.extend(['yyy', 'zzz']) ## add list of elems at end >>> print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz'] Day 1
  • 23. Data Structure : iterations over list Using for loop for var in list >>> squares = [1, 4, 9, 16] >>> sum = 0 >>> for num in squares: >>> … sum += num >>> … print sum ## 30 Day 1
  • 24. Data Structure : dict Python's efficient key/value hash table structure is called a "dict" The contents of a dict can be written as a series of key:value pairs e.g. dict = {key1:value1, key2:value2, ... } The "empty dict" is just an empty pair of curly braces {} Looking up or setting a value in a dict uses square brackets. e.g. dict['foo'] Day 1
  • 25. Data Structure : creating dict ## Can build up a dict by starting with the the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' Day 1
  • 26. Data Structure : Iteration on key or value ## By default, iterating over a dict iterates over its keys. ## Note that the keys are in a random order. for key in dict: print key ## prints a g o ## Exactly the same as above for key in dict.keys(): print key Day 1
  • 27. Data Structure: Iteration on key and value ## This loop syntax accesses the whole dict by looping ## over the .items() tuple list, accessing one (key, value) ## pair on each iteration. for k, v in dict.items(): print k, '>', v ## a > alpha o > omega g > gamma Day 1
  • 28. Data Structure : del an item var = 6 del var # var no more! list = ['a', 'b', 'c', 'd'] del list[0] ## Delete first element del list[-2:] ## Delete last two elements print list ## ['b'] Day 1
  • 29. Data Structure : sorting The easiest way to sort is with the sorted(list) function The sorted() function seems easier to use compared to sort() The sorted() function can be customized though optional arguments The sorted() optional argument reverse=True Custom Sorting With key= Day 1
  • 30. Data Structure : working with sorted( ) S o r t in g N u m b e r s a = [5, 1, 4, 3] print sorted(a) ## [1, 3, 4, 5] print a ## [5, 1, 4, 3] S o r t in g S t r in g strs = ['aa', 'BB', 'zz', 'CC'] print sorted(strs) ## ['BB', 'CC', 'aa', 'zz'] (case sensitive) Day 1
  • 31. Data Structure : Custom Sorting with key strs = ['ccc', 'aaaa', 'd', 'bb'] print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa'] Day 1
  • 32. Data Structure : Custom comparator ## Say we have a list of strings we want to sort by the last letter of the string. strs = ['xc', 'zb', 'yd' ,'wa'] ## Write a little function that takes a string, and returns its last letter. ## This will be the key function (takes in 1 value, returns 1 value). def MyComparator(s): Day 1
  • 33. Next Session ? Function Dynamic Functions Object Oriented Class Inheritance Method Overload, Override Python Packaging __init__.py Day 1
  • 34. Contact me... Mantavya Gajjar Phone : 94263 40093 Email : mail@mantavyagajjar.in Website : www.opentechnologies.in Follow on Twitter : @mantavyagajjar Day 1