SlideShare a Scribd company logo
Learn Python The Hard Way


                   Utkarsh Sengar




  Contents taken from © Copyright 2010, Zed A. Shaw.
Resources
• Learn Python The Hard Way, 2nd Edition
  – http://bit.ly/python-lug (Free online)
  – Paperback book costs $15.99
  – http://learncodethehardway.org
• Google python class:
  – http://code.google.com/edu/languages/google-
    python-class/
• MIT Open courseware:
  – http://academicearth.org/courses/introduction-to-
    computer-science-and-programming
It’s Easy.
 5 most important things:
  – Do Not Copy-Paste
  – Code
  – Practice
  – Practice
  – Practice
Prerequisites
 Python v2.5 +
   python

 Any text editor.
   gEdit (Linux)
   TextMate (OSX)

 Settings
   Tabs Width: 4
   Insert spaces instead of tabs

 Your Mind.
TODO: today
   Total of 52 chapters
   We will cover: 1-22, 28-35, 39-42
   Basic constructs, data structures, OOP
   Solve two simple python problems.

 Homework: Another problem. What did you think?
Lets code…..
       etherPad
http://ip-address:9001
But first……..Pip, pep8, iPython
• pip install simplejson
  – For python packages in Python package index
• pep8 script.py
  – Python style guide. Your best friend
• Python Easter egg
  – import this
• Ipython
• Open pydocs :
  docs.python.org/library/index.html
comments

   Single line comments only
   '#' (an octothorpe) notifies beginning
   Ends with a newline
Printing statements

   print is builtin function
   Usage: print ”Hello, world!”
   Appends a newline automatically
   To avoid new line, use a comma (,)
   Usage: print ”Hello”,
            print ”roopesh”
Basic math

   * / % + - < > <= >=
   Same as C operator precedence
   / does a integer division
   Example:
       print "Hens", 25 + 30 / 6
       print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
       print "What is 5 - 7?", 5 – 7
       print "Is it greater or equal?", 5 >= -2
More operators

• Basic ones: + - * / %
• Try:
  – x // y
  – abs(x)
  – int(x), long(x), float(x)
  – complex(re, im)
  – c.conjugate()
  – pow(x, y) or x ** y
variables

   No need of types
   Duck typing
       cars = 100
       space_in_car = 4.0
       result = cars + space_in_car
       cars_not_driven = cars
   Can assign one var to another
   Tip: type(cars)
Variables and printing

   Can use placeholders in print statements
       print ”let's talk about %s” % my_name
       print "There are %d types of people." % 10
       print "Those who know %s and those who %s." %
        (binary, do_not)
   Also can use names for placeholders
       print ”my name is %(name)s” % {'name':
        my_name}
Text (String)

   There are 3 types of notation
   Single quotes, double quotes, multiline text
   Multiline text stores the text, whitespaces and escape
    characters as well
       val = ’hello world’
       val = ”hello again!”
       val = ”Hello n
         World 
         !!”
       val = ”””no need to ’escape’ anything – ”ok?” ”””
       Interesting functions:
        upper(), lower(), title(), swapcase(),strip()
Booleans

   True and False
   Can use in print with placeholders as well
   Anything that has a value is true, anything like
    0, zero length string, zero length list or dictionary
    is false
   val = ’Hi my friend’
    if val:
       print ”yo!”
   If ’Hi’ in val:
        print ’this keeps getting better!’
Input

   There are two functions: input(), raw_input()
   raw_input() contains string and input() could
    contain object
       first = raw_input("Please enter your age ")
        second = input("Please enter your age again")
       print "You said you are", first
        print "Then you said you are", second
       Try again, pass 40+2 in second
Working with python prog files

   Any arguments passed to python prog files is
    stored in argv
   Zero based arguments, first one is always
    script name
       import sys
        print sys.argv[0]
        print sys.argv[1]
       Run: python file.py 4
Working with files
   open(filename, mode) : returns file handle
   read() : to read the whole file
   readline() and readlines(): to read each line
   write(data) : writes to file
   close() : to close the file handle
       from sys import argv
        script, filename = argv
        txt = open(filename, 'r+') #r or w
        print "Here's your script %r:" % script
        print "Here's your file %r:" % filename
        print txt.read()
        txt.write('42')
        txt.close()
functions

   def keyword to declare a function
   Arguments don't need function type
   Can skip return value
   No return implies it returns a None value
       Always do: x is None and not, x == None
       None is similar to null
   To take unlimited number of arguments: use *arg
    as argument, it is packing method for arguments
functions cont…

   def print_none():pass
   def print_one(arg1):
        print ”got one arg: %s” % arg1
   def print_two(arg1, arg2):
        print ”got two args: %s, %s” %(arg1, arg2)
   def print_two_2(*args):
        print args
        return args
Logics

   and, or, not, ==, !=, >, >=, <, <=
   and returns last value which makes the
    statement true
   or returns first value which makes the
    statement false
   Both are short-circuit operator
       test = True
        result = test and 'Test is True' or 'Test is False'
Data Structures

   List: [1, 2, 3, 2]
   Tuples: (1, 2, 3, 2)
   Set: {1,2,3}
   Dictionary: {’name’ : ’utkarsh’, ’age’ : 42}
Lists and loops

   Lists: [1, 2, 3]
       append(elem), extend(list), insert(idx, elem), rem
        ove(x), pop(i), count(i), sort(), reverse(),len(l)
   Tuples: (1, 2, 3)
   Difference:
       lists are mutable,
       tuples are immutable
       Ideally lists should have same data types
Lists and loops

   for element in list:
        print element
   for i in range(i):
        print i
   for i, val in enumerate(list):
        print i, val
   sorted_list = sorted(list)
   sort(list)
   List comprehensions for ease of use (later..)
Lists and loops

   Lists from strings:
       a = ”A B C D E F”.split()
        #['A', 'B', 'C', 'D', 'E', 'F’]
        a.pop()
        ' '.join(a) #joins lists to form a string
   List slicing: list[start:end]
       a[0:len(a)]
       a[:4]
       a[3:]
       a[-1]
Dictionaries

   {'name': 'Roopesh’, ’age’ : 42}
   Key-value pairs / lookup table
   Can be accessed with a['name']
   Can add new values with same syntax
        a['city'] = 'San Jose'
   Can remove an item with 'del'
        del a['city']
   Add a bunch using: dict.update(another_dict)
Classes and Objects

   Class keyword, inherits from object
   Constructor: def __init__
   All methods take first arg as the instance of
    class
   Denoted with word 'self'
   Any number of args have to follow self
          def func(self, val)
Classes and Objects

   Instantiating classes with ClassName() syntax
   There is no 'new' keyword
   Some examples in code given.
   To override operators, override functions like
    __eq__, __lt__, __gt__, __lte__ etc
Class example
class MyClass:
   answer = 42
   def a_method(self):
     print “I am a method”

instance = MyClass ()
instance.a_method()
hasattr(MyClass, “answer”)
List comprehensions (bonus)

   [each for each in range(100) if each % 2 == 0]
   [some_func(each) for each in range(100)]
   iter(list) produces a list iterator
   Gives ability to get next item with
    iterator.next()
   When iterator gets exhausted, it produces
    StopIteration exception
Handling Exceptions

Try:
    … do some handling
except Error as e:
    print e
finally:
    … do some final clean up
Problem 1

Write a function char_freq() that takes a string
and builds a frequency listing of the characters
contained in it. Represent the frequency listing
as a Python dictionary.

Try it with something like
char_freq("abbabcbdbabdbdbabababcbcbab”)
Problem 2
In cryptography, a Caesar cipher is a very simple encryption techniques in which each
letter in the plain text is replaced by a letter some fixed number of positions down the
alphabet. For example, with a shift of 3, A would be replaced by D, B would become
E, and so on. The method is named after Julius Caesar, who used it to communicate
with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar
cipher where the shift is 13. In Python, the key for ROT-13 may be represented by
means of the following dictionary:

key =
{'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'
a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', '
B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A'
, 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}

Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're
done, you will be able to read the following secret message:

Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
Homework


 Integer to Roman
numerals converter
Want more?
• Go here:
  – 15 Exercises to Know A Programming Language:
    Part 1
  – http://www.knowing.net/index.php/2006/06/16/
    15-exercises-to-know-a-programming-language-
    part-1
A lot more…
   List comprehensions, decorators, lambda
functions, effective unit tests, network and web
                  programming,

           Some popular modules like
urlib, simplejson, ElementTree and lxml for xml
parsing, SQLAlchemy, sciPy, NumPy, mechanize
At the end……
“I'll say that learning to create software changes
you and makes you different. Not better or
worse, just different.”

“The world needs more weird people who know
how things work and who love to figure it all out.”

                                                            ~ Zed Shaw

Source: http://learnpythonthehardway.org/book/advice.html

More Related Content

What's hot (20)

Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
Elewayte
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
Kanchilug
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Edureka!
 
Python idle introduction(3)
Python idle introduction(3)Python idle introduction(3)
Python idle introduction(3)
Fahad Ashrafi
 
Python by Rj
Python by RjPython by Rj
Python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Python Basics
Python BasicsPython Basics
Python Basics
tusharpanda88
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
primeteacher32
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Python PPT
Python PPTPython PPT
Python PPT
Edureka!
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
Mukul Kirti Verma
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ayshwarya Baburam
 
Python ppt.pdf
Python ppt.pdfPython ppt.pdf
Python ppt.pdf
kalai75
 
Programming
ProgrammingProgramming
Programming
monishagoyal4
 
1.python interpreter and interactive mode
1.python interpreter and interactive mode1.python interpreter and interactive mode
1.python interpreter and interactive mode
ManjuA8
 
Introduction to Basics of Python
Introduction to Basics of PythonIntroduction to Basics of Python
Introduction to Basics of Python
Elewayte
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
Kanchilug
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Edureka!
 
Python idle introduction(3)
Python idle introduction(3)Python idle introduction(3)
Python idle introduction(3)
Fahad Ashrafi
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Python PPT
Python PPTPython PPT
Python PPT
Edureka!
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
Python ppt.pdf
Python ppt.pdfPython ppt.pdf
Python ppt.pdf
kalai75
 
1.python interpreter and interactive mode
1.python interpreter and interactive mode1.python interpreter and interactive mode
1.python interpreter and interactive mode
ManjuA8
 

Similar to Python Workshop - Learn Python the Hard Way (20)

Python Part 1
Python Part 1Python Part 1
Python Part 1
Mohamed Ramadan
 
Python
PythonPython
Python
Vishal Sancheti
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdfPython Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ahmed Salama
 
Practical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptxPractical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptx
trwdcn
 
ppt_pspp.pdf
ppt_pspp.pdfppt_pspp.pdf
ppt_pspp.pdf
ShereenAhmedMohamed
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
Iccha Sethi
 
Python: An introduction A summer workshop
Python: An  introduction A summer workshopPython: An  introduction A summer workshop
Python: An introduction A summer workshop
ForrayFerenc
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
Giovanni Della Lunga
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
PYTHON
PYTHONPYTHON
PYTHON
JOHNYAMSON
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Andrea Gangemi
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
Sushant Mane
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdfPython Cheatsheet_A Quick Reference Guide for Data Science.pdf
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ahmed Salama
 
Practical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptxPractical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptx
trwdcn
 
Python: An introduction A summer workshop
Python: An  introduction A summer workshopPython: An  introduction A summer workshop
Python: An introduction A summer workshop
ForrayFerenc
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
Giovanni Della Lunga
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Mohamed Abdallah
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
Andrea Gangemi
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
Sushant Mane
 
Ad

More from Utkarsh Sengar (7)

Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
Utkarsh Sengar
 
Linux Interview Questions Quiz
Linux Interview Questions QuizLinux Interview Questions Quiz
Linux Interview Questions Quiz
Utkarsh Sengar
 
Begin With Linux Basics
Begin With Linux BasicsBegin With Linux Basics
Begin With Linux Basics
Utkarsh Sengar
 
Linux Commands
Linux CommandsLinux Commands
Linux Commands
Utkarsh Sengar
 
Linux User Group @ SJSU Meeting#1
Linux User Group @ SJSU Meeting#1Linux User Group @ SJSU Meeting#1
Linux User Group @ SJSU Meeting#1
Utkarsh Sengar
 
Hackers The Anarchists Of Our Time
Hackers The Anarchists Of Our TimeHackers The Anarchists Of Our Time
Hackers The Anarchists Of Our Time
Utkarsh Sengar
 
SharePoint in Enterprise Collaboration (Education)
SharePoint in Enterprise Collaboration (Education)SharePoint in Enterprise Collaboration (Education)
SharePoint in Enterprise Collaboration (Education)
Utkarsh Sengar
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
Utkarsh Sengar
 
Linux Interview Questions Quiz
Linux Interview Questions QuizLinux Interview Questions Quiz
Linux Interview Questions Quiz
Utkarsh Sengar
 
Begin With Linux Basics
Begin With Linux BasicsBegin With Linux Basics
Begin With Linux Basics
Utkarsh Sengar
 
Linux User Group @ SJSU Meeting#1
Linux User Group @ SJSU Meeting#1Linux User Group @ SJSU Meeting#1
Linux User Group @ SJSU Meeting#1
Utkarsh Sengar
 
Hackers The Anarchists Of Our Time
Hackers The Anarchists Of Our TimeHackers The Anarchists Of Our Time
Hackers The Anarchists Of Our Time
Utkarsh Sengar
 
SharePoint in Enterprise Collaboration (Education)
SharePoint in Enterprise Collaboration (Education)SharePoint in Enterprise Collaboration (Education)
SharePoint in Enterprise Collaboration (Education)
Utkarsh Sengar
 
Ad

Recently uploaded (20)

Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 

Python Workshop - Learn Python the Hard Way

  • 1. Learn Python The Hard Way Utkarsh Sengar Contents taken from © Copyright 2010, Zed A. Shaw.
  • 2. Resources • Learn Python The Hard Way, 2nd Edition – http://bit.ly/python-lug (Free online) – Paperback book costs $15.99 – http://learncodethehardway.org • Google python class: – http://code.google.com/edu/languages/google- python-class/ • MIT Open courseware: – http://academicearth.org/courses/introduction-to- computer-science-and-programming
  • 3. It’s Easy.  5 most important things: – Do Not Copy-Paste – Code – Practice – Practice – Practice
  • 4. Prerequisites  Python v2.5 +  python  Any text editor.  gEdit (Linux)  TextMate (OSX)  Settings  Tabs Width: 4  Insert spaces instead of tabs  Your Mind.
  • 5. TODO: today  Total of 52 chapters  We will cover: 1-22, 28-35, 39-42  Basic constructs, data structures, OOP  Solve two simple python problems.  Homework: Another problem. What did you think?
  • 6. Lets code….. etherPad http://ip-address:9001
  • 7. But first……..Pip, pep8, iPython • pip install simplejson – For python packages in Python package index • pep8 script.py – Python style guide. Your best friend • Python Easter egg – import this • Ipython • Open pydocs : docs.python.org/library/index.html
  • 8. comments  Single line comments only  '#' (an octothorpe) notifies beginning  Ends with a newline
  • 9. Printing statements  print is builtin function  Usage: print ”Hello, world!”  Appends a newline automatically  To avoid new line, use a comma (,)  Usage: print ”Hello”, print ”roopesh”
  • 10. Basic math  * / % + - < > <= >=  Same as C operator precedence  / does a integer division  Example:  print "Hens", 25 + 30 / 6  print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6  print "What is 5 - 7?", 5 – 7  print "Is it greater or equal?", 5 >= -2
  • 11. More operators • Basic ones: + - * / % • Try: – x // y – abs(x) – int(x), long(x), float(x) – complex(re, im) – c.conjugate() – pow(x, y) or x ** y
  • 12. variables  No need of types  Duck typing  cars = 100  space_in_car = 4.0  result = cars + space_in_car  cars_not_driven = cars  Can assign one var to another  Tip: type(cars)
  • 13. Variables and printing  Can use placeholders in print statements  print ”let's talk about %s” % my_name  print "There are %d types of people." % 10  print "Those who know %s and those who %s." % (binary, do_not)  Also can use names for placeholders  print ”my name is %(name)s” % {'name': my_name}
  • 14. Text (String)  There are 3 types of notation  Single quotes, double quotes, multiline text  Multiline text stores the text, whitespaces and escape characters as well  val = ’hello world’  val = ”hello again!”  val = ”Hello n World !!”  val = ”””no need to ’escape’ anything – ”ok?” ”””  Interesting functions: upper(), lower(), title(), swapcase(),strip()
  • 15. Booleans  True and False  Can use in print with placeholders as well  Anything that has a value is true, anything like 0, zero length string, zero length list or dictionary is false  val = ’Hi my friend’ if val: print ”yo!”  If ’Hi’ in val: print ’this keeps getting better!’
  • 16. Input  There are two functions: input(), raw_input()  raw_input() contains string and input() could contain object  first = raw_input("Please enter your age ") second = input("Please enter your age again")  print "You said you are", first print "Then you said you are", second  Try again, pass 40+2 in second
  • 17. Working with python prog files  Any arguments passed to python prog files is stored in argv  Zero based arguments, first one is always script name  import sys print sys.argv[0] print sys.argv[1]  Run: python file.py 4
  • 18. Working with files  open(filename, mode) : returns file handle  read() : to read the whole file  readline() and readlines(): to read each line  write(data) : writes to file  close() : to close the file handle  from sys import argv script, filename = argv txt = open(filename, 'r+') #r or w print "Here's your script %r:" % script print "Here's your file %r:" % filename print txt.read() txt.write('42') txt.close()
  • 19. functions  def keyword to declare a function  Arguments don't need function type  Can skip return value  No return implies it returns a None value  Always do: x is None and not, x == None  None is similar to null  To take unlimited number of arguments: use *arg as argument, it is packing method for arguments
  • 20. functions cont…  def print_none():pass  def print_one(arg1): print ”got one arg: %s” % arg1  def print_two(arg1, arg2): print ”got two args: %s, %s” %(arg1, arg2)  def print_two_2(*args): print args return args
  • 21. Logics  and, or, not, ==, !=, >, >=, <, <=  and returns last value which makes the statement true  or returns first value which makes the statement false  Both are short-circuit operator  test = True result = test and 'Test is True' or 'Test is False'
  • 22. Data Structures  List: [1, 2, 3, 2]  Tuples: (1, 2, 3, 2)  Set: {1,2,3}  Dictionary: {’name’ : ’utkarsh’, ’age’ : 42}
  • 23. Lists and loops  Lists: [1, 2, 3]  append(elem), extend(list), insert(idx, elem), rem ove(x), pop(i), count(i), sort(), reverse(),len(l)  Tuples: (1, 2, 3)  Difference:  lists are mutable,  tuples are immutable  Ideally lists should have same data types
  • 24. Lists and loops  for element in list: print element  for i in range(i): print i  for i, val in enumerate(list): print i, val  sorted_list = sorted(list)  sort(list)  List comprehensions for ease of use (later..)
  • 25. Lists and loops  Lists from strings:  a = ”A B C D E F”.split() #['A', 'B', 'C', 'D', 'E', 'F’] a.pop() ' '.join(a) #joins lists to form a string  List slicing: list[start:end]  a[0:len(a)]  a[:4]  a[3:]  a[-1]
  • 26. Dictionaries  {'name': 'Roopesh’, ’age’ : 42}  Key-value pairs / lookup table  Can be accessed with a['name']  Can add new values with same syntax a['city'] = 'San Jose'  Can remove an item with 'del' del a['city']  Add a bunch using: dict.update(another_dict)
  • 27. Classes and Objects  Class keyword, inherits from object  Constructor: def __init__  All methods take first arg as the instance of class  Denoted with word 'self'  Any number of args have to follow self def func(self, val)
  • 28. Classes and Objects  Instantiating classes with ClassName() syntax  There is no 'new' keyword  Some examples in code given.  To override operators, override functions like __eq__, __lt__, __gt__, __lte__ etc
  • 29. Class example class MyClass: answer = 42 def a_method(self): print “I am a method” instance = MyClass () instance.a_method() hasattr(MyClass, “answer”)
  • 30. List comprehensions (bonus)  [each for each in range(100) if each % 2 == 0]  [some_func(each) for each in range(100)]  iter(list) produces a list iterator  Gives ability to get next item with iterator.next()  When iterator gets exhausted, it produces StopIteration exception
  • 31. Handling Exceptions Try: … do some handling except Error as e: print e finally: … do some final clean up
  • 32. Problem 1 Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab”)
  • 33. Problem 2 In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary: key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':' a', 'o':'b', 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k', 'y':'l', 'z':'m', 'A':'N', ' B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A' , 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'} Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you will be able to read the following secret message: Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
  • 34. Homework Integer to Roman numerals converter
  • 35. Want more? • Go here: – 15 Exercises to Know A Programming Language: Part 1 – http://www.knowing.net/index.php/2006/06/16/ 15-exercises-to-know-a-programming-language- part-1
  • 36. A lot more… List comprehensions, decorators, lambda functions, effective unit tests, network and web programming, Some popular modules like urlib, simplejson, ElementTree and lxml for xml parsing, SQLAlchemy, sciPy, NumPy, mechanize
  • 37. At the end…… “I'll say that learning to create software changes you and makes you different. Not better or worse, just different.” “The world needs more weird people who know how things work and who love to figure it all out.” ~ Zed Shaw Source: http://learnpythonthehardway.org/book/advice.html

Editor's Notes

  • #8: http://guide.python-distribute.org/installation.html
  • #35: Chart: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm