You are previewing Learning Python.
O'Reilly logo
Learning Python

Book Description

Learn to code like a professional with Python – an open source, versatile, and powerful programming language

About This Book

  • Learn the fundamentals of programming with Python – one of the best languages ever created

  • Develop a strong set of programming skills that you will be able to express in any situation, on every platform, thanks to Python’s portability

  • Create outstanding applications of all kind, from websites to scripting, and from GUIs to data science

  • Who This Book Is For

    Python is the most popular introductory teaching language in U.S. top computer science universities, so if you are new to software development, or maybe you have little experience, and would like to start off on the right foot, then this language and this book are what you need. Its amazing design and portability will help you become productive regardless of the environment you choose to work with.

    What You Will Learn

  • Get Python up and running on Windows, Mac, and Linux in no time

  • Grasp the fundamental concepts of coding, along with the basics of data structures and control flow.

  • Write elegant, reusable, and efficient code in any situation

  • Understand when to use the functional or the object oriented programming approach

  • Create bulletproof, reliable software by writing tests to support your code

  • Explore examples of GUIs, scripting, data science and web applications

  • Learn to be independent, capable of fetching any resource you need, as well as dig deeper

  • In Detail

    Learning Python has a dynamic and varied nature. It reads easily and lays a good foundation for those who are interested in digging deeper. It has a practical and example-oriented approach through which both the introductory and the advanced topics are explained. Starting with the fundamentals of programming and Python, it ends by exploring very different topics, like GUIs, web apps and data science. The book takes you all the way to creating a fully fledged application.

    The book begins by exploring the essentials of programming, data structures and teaches you how to manipulate them. It then moves on to controlling the flow of a program and writing reusable and error proof code. You will then explore different programming paradigms that will allow you to find the best approach to any situation, and also learn how to perform performance optimization as well as effective debugging. Throughout, the book steers you through the various types of applications, and it concludes with a complete mini website built upon all the concepts that you learned.

    Style and approach

    This book is an easy-to-follow guide that will take you from a novice to the proficient level at a comfortable pace, using a lot of simple but effective examples. Each topic is explained thoroughly, and pointers are left for the more inquisitive readers to dig deeper and expand their knowledge.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

    Table of Contents

    1. Learning Python
      1. Table of Contents
      2. Learning Python
      3. Credits
      4. About the Author
      5. Acknowledgements
      6. About the Reviewers
      7. www.PacktPub.com
        1. Support files, eBooks, discount offers, and more
          1. Why subscribe?
          2. Free access for Packt account holders
      8. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      9. 1. Introduction and First Steps – Take a Deep Breath
        1. A proper introduction
        2. Enter the Python
        3. About Python
          1. Portability
          2. Coherence
          3. Developer productivity
          4. An extensive library
          5. Software quality
          6. Software integration
          7. Satisfaction and enjoyment
        4. What are the drawbacks?
        5. Who is using Python today?
        6. Setting up the environment
          1. Python 2 versus Python 3 – the great debate
        7. Installing Python
          1. Setting up the Python interpreter
          2. About virtualenv
          3. Your first virtual environment
          4. Your friend, the console
        8. How you can run a Python program
          1. Running Python scripts
          2. Running the Python interactive shell
          3. Running Python as a service
          4. Running Python as a GUI application
        9. How is Python code organized
          1. How do we use modules and packages
        10. Python's execution model
          1. Names and namespaces
          2. Scopes
          3. Object and classes
        11. Guidelines on how to write good code
        12. The Python culture
        13. A note on the IDEs
        14. Summary
      10. 2. Built-in Data Types
        1. Everything is an object
        2. Mutable or immutable? That is the question
        3. Numbers
          1. Integers
          2. Booleans
          3. Reals
          4. Complex numbers
          5. Fractions and decimals
        4. Immutable sequences
          1. Strings and bytes
            1. Encoding and decoding strings
            2. Indexing and slicing strings
          2. Tuples
        5. Mutable sequences
          1. Lists
          2. Byte arrays
        6. Set types
        7. Mapping types – dictionaries
        8. The collections module
          1. Named tuples
          2. Defaultdict
          3. ChainMap
        9. Final considerations
          1. Small values caching
          2. How to choose data structures
          3. About indexing and slicing
          4. About the names
        10. Summary
      11. 3. Iterating and Making Decisions
        1. Conditional programming
          1. A specialized else: elif
          2. The ternary operator
        2. Looping
          1. The for loop
            1. Iterating over a range
            2. Iterating over a sequence
          2. Iterators and iterables
          3. Iterating over multiple sequences
          4. The while loop
          5. The break and continue statements
          6. A special else clause
        3. Putting this all together
          1. Example 1 – a prime generator
          2. Example 2 – applying discounts
        4. A quick peek at the itertools module
          1. Infinite iterators
          2. Iterators terminating on the shortest input sequence
          3. Combinatoric generators
        5. Summary
      12. 4. Functions, the Building Blocks of Code
        1. Why use functions?
          1. Reduce code duplication
          2. Splitting a complex task
          3. Hide implementation details
          4. Improve readability
          5. Improve traceability
        2. Scopes and name resolution
          1. The global and nonlocal statements
        3. Input parameters
          1. Argument passing
          2. Assignment to argument names don't affect the caller
          3. Changing a mutable affects the caller
          4. How to specify input parameters
            1. Positional arguments
            2. Keyword arguments and default values
            3. Variable positional arguments
            4. Variable keyword arguments
            5. Keyword-only arguments
            6. Combining input parameters
            7. Avoid the trap! Mutable defaults
        4. Return values
          1. Returning multiple values
        5. A few useful tips
        6. Recursive functions
        7. Anonymous functions
        8. Function attributes
        9. Built-in functions
        10. One final example
        11. Documenting your code
        12. Importing objects
          1. Relative imports
        13. Summary
      13. 5. Saving Time and Memory
        1. map, zip, and filter
          1. map
          2. zip
          3. filter
        2. Comprehensions
          1. Nested comprehensions
          2. Filtering a comprehension
          3. dict comprehensions
          4. set comprehensions
        3. Generators
          1. Generator functions
          2. Going beyond next
          3. The yield from expression
          4. Generator expressions
        4. Some performance considerations
        5. Don't overdo comprehensions and generators
        6. Name localization
        7. Generation behavior in built-ins
        8. One last example
        9. Summary
      14. 6. Advanced Concepts – OOP, Decorators, and Iterators
        1. Decorators
          1. A decorator factory
        2. Object-oriented programming
          1. The simplest Python class
          2. Class and object namespaces
          3. Attribute shadowing
          4. I, me, and myself – using the self variable
          5. Initializing an instance
          6. OOP is about code reuse
            1. Inheritance and composition
          7. Accessing a base class
          8. Multiple inheritance
            1. Method resolution order
          9. Static and class methods
            1. Static methods
            2. Class methods
          10. Private methods and name mangling
          11. The property decorator
          12. Operator overloading
          13. Polymorphism – a brief overview
        3. Writing a custom iterator
        4. Summary
      15. 7. Testing, Profiling, and Dealing with Exceptions
        1. Testing your application
          1. The anatomy of a test
          2. Testing guidelines
          3. Unit testing
            1. Writing a unit test
            2. Mock objects and patching
            3. Assertions
            4. A classic unit test example
            5. Making a test fail
            6. Interface testing
            7. Comparing tests with and without mocks
            8. Boundaries and granularity
            9. A more interesting example
        2. Test-driven development
        3. Exceptions
        4. Profiling Python
          1. When to profile?
        5. Summary
      16. 8. The Edges – GUIs and Scripts
        1. First approach – scripting
          1. The imports
          2. Parsing arguments
          3. The business logic
        2. Second approach – a GUI application
          1. The imports
          2. The layout logic
          3. The business logic
            1. Fetching the web page
            2. Saving the images
            3. Alerting the user
          4. How to improve the application?
        3. Where do we go from here?
          1. The tkinter.tix module
          2. The turtle module
          3. wxPython, PyQt, and PyGTK
          4. The principle of least astonishment
          5. Threading considerations
        4. Summary
      17. 9. Data Science
        1. IPython and Jupyter notebook
        2. Dealing with data
          1. Setting up the notebook
          2. Preparing the data
          3. Cleaning the data
          4. Creating the DataFrame
            1. Unpacking the campaign name
            2. Unpacking the user data
            3. Cleaning everything up
          5. Saving the DataFrame to a file
          6. Visualizing the results
        3. Where do we go from here?
        4. Summary
      18. 10. Web Development Done Right
        1. What is the Web?
        2. How does the Web work?
        3. The Django web framework
          1. Django design philosophy
            1. The model layer
            2. The view layer
            3. The template layer
          2. The Django URL dispatcher
            1. Regular expressions
        4. A regex website
          1. Setting up Django
            1. Starting the project
            2. Creating users
          2. Adding the Entry model
          3. Customizing the admin panel
          4. Creating the form
          5. Writing the views
            1. The home view
            2. The entry list view
            3. The form view
          6. Tying up URLs and views
          7. Writing the templates
        5. The future of web development
          1. Writing a Flask view
          2. Building a JSON quote server in Falcon
        6. Summary
      19. 11. Debugging and Troubleshooting
        1. Debugging techniques
          1. Debugging with print
          2. Debugging with a custom function
          3. Inspecting the traceback
          4. Using the Python debugger
          5. Inspecting log files
          6. Other techniques
            1. Profiling
            2. Assertions
          7. Where to find information
        2. Troubleshooting guidelines
          1. Using console editors
          2. Where to inspect
          3. Using tests to debug
          4. Monitoring
        3. Summary
      20. 12. Summing Up – A Complete Example
        1. The challenge
        2. Our implementation
        3. Implementing the Django interface
          1. The setup
          2. The model layer
          3. A simple form
          4. The view layer
            1. Imports and home view
            2. Listing all records
            3. Creating records
            4. Updating records
            5. Deleting records
          5. Setting up the URLs
          6. The template layer
            1. Home and footer templates
            2. Listing all records
            3. Creating and editing records
            4. Talking to the API
            5. Deleting records
        4. Implementing the Falcon API
          1. The main application
          2. Writing the helpers
            1. Coding the password validator
            2. Coding the password generator
          3. Writing the handlers
            1. Coding the password validator handler
            2. Coding the password generator handler
          4. Running the API
          5. Testing the API
            1. Testing the helpers
            2. Testing the handlers
        5. Where do you go from here?
        6. Summary
        7. A word of farewell
      21. Index