O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Learn Python Programming

Book Description

Learn the fundamentals of Python (3.7) and how to apply it to data science, programming, and web development. Fully updated to include hands-on tutorials and projects.

Key Features

  • Learn the fundamentals of Python programming with interactive projects
  • Apply Python to data science with tools such as IPython and Jupyter
  • Utilize Python for web development and build a real-world app using Django

Book Description

Learn Python Programming is a quick, thorough, and practical introduction to Python - an extremely flexible and powerful programming language that can be applied to many disciplines.

Unlike other books, it doesn't bore you with elaborate explanations of the basics but gets you up-and-running, using the language. You will begin by learning the fundamentals of Python so that you have a rock-solid foundation to build upon.

You will explore the foundations of Python programming and learn how Python can be manipulated to achieve results. Explore different programming paradigms and find the best approach to a situation; understand how to carry out performance optimization and effective debugging; control the flow of a program; and utilize an interchange format to exchange data. You'll also walk through cryptographic services in Python and understand secure tokens.

Learn Python Programming will give you a thorough understanding of the Python language. You'll learn how to write programs, build websites, and work with data by harnessing Python's renowned data science libraries. Filled with real-world examples and projects, the book covers various types of applications, and concludes by building real-world projects based on the concepts you have learned.

What you will learn

  • Get Python up and running on Windows, Mac, and Linux
  • Explore fundamental concepts of coding using data structures and control flow
  • Write elegant, reusable, and efficient code in any situation
  • Understand when to use the functional or OOP approach
  • Cover the basics of security and concurrent/asynchronous programming
  • Create bulletproof, reliable software by writing tests
  • Build a simple website in Django
  • Fetch, clean, and manipulate data

Who this book is for

Learn Python Programming is for individuals with relatively little experience in coding or Python. It's also ideal for aspiring programmers who need to write scripts or programs to accomplish tasks. The book shows you how to create a full-fledged application.

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 files e-mailed directly to you.

Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Learn Python Programming Second Edition
  3. Dedication
  4. Packt Upsell
    1. Why subscribe?
    2. PacktPub.com
  5. Foreword
  6. Contributors
    1. About the author
    2. About the reviewers
    3. Packt is searching for authors like you
  7. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Conventions used
    4. Get in touch
      1. Reviews
  8. A Gentle Introduction to Python
    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
    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. Objects and classes
    11. Guidelines on how to write good code
    12. The Python culture
    13. A note on IDEs
    14. Summary
  9. Built-in Data Types
    1. Everything is an object
    2. Mutable or immutable? That is the question
    3. Numbers
      1. Integers
      2. Booleans
      3. Real numbers
      4. Complex numbers
      5. Fractions and decimals
    4. Immutable sequences
      1. Strings and bytes
        1. Encoding and decoding strings
        2. Indexing and slicing strings
        3. String formatting
      2. Tuples
    5. Mutable sequences
      1. Lists
      2. Byte arrays
    6. Set types
    7. Mapping types – dictionaries
    8. The collections module
      1. namedtuple
      2. defaultdict
      3. ChainMap
    9. Enums
    10. Final considerations
      1. Small values caching
      2. How to choose data structures
      3. About indexing and slicing
      4. About the names
    11. Summary
  10. 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 all this together
      1. A prime generator
      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
  11. Functions, the Building Blocks of Code
    1. Why use functions?
      1. Reducing code duplication
      2. Splitting a complex task
      3. Hiding implementation details
      4. Improving readability
      5. Improving traceability
    2. Scopes and name resolution
      1. The global and nonlocal statements
    3. Input parameters
      1. Argument-passing
      2. Assignment to argument names doesn'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. Additional unpacking generalizations
        8. 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
  12. Saving Time and Memory
    1. The map, zip, and filter functions
      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
  13. OOP, Decorators, and Iterators
    1. Decorators
      1. A decorator factory
    2. Object-oriented programming (OOP)
      1. The simplest Python class
      2. Class and object namespaces
      3. Attribute shadowing
      4. Me, myself, and I – 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. Class and static 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
      14. Data classes
    3. Writing a custom iterator
    4. Summary
  14. Files and Data Persistence
    1. Working with files and directories
      1. Opening files
        1. Using a context manager to open a file
      2. Reading and writing to a file
        1. Reading and writing in binary mode
        2. Protecting against overriding an existing file
      3. Checking for file and directory existence
      4. Manipulating files and directories
        1. Manipulating pathnames
      5. Temporary files and directories
      6. Directory content
      7. File and directory compression
    2. Data interchange formats
      1. Working with JSON
        1. Custom encoding/decoding with JSON
    3. IO, streams, and requests
      1. Using an in-memory stream
      2. Making HTTP requests
    4. Persisting data on disk
      1. Serializing data with pickle
      2. Saving data with shelve
      3. Saving data to a database
    5. Summary
  15. 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. Testing a CSV generator
        1. Boundaries and granularity
        2. Testing the export function
        3. Final considerations
    2. Test-driven development
    3. Exceptions
    4. Profiling Python
      1. When to profile?
    5. Summary
  16. Cryptography and Tokens
    1. The need for cryptography
      1. Useful guidelines
    2. Hashlib
    3. Secrets
      1. Random numbers
      2. Token generation
      3. Digest comparison
    4. HMAC
    5. JSON Web Tokens
      1. Registered claims
        1. Time-related claims
        2. Auth-related claims
      2. Using asymmetric (public-key) algorithms
    6. Useful references
    7. Summary
  17. Concurrent Execution
    1. Concurrency versus parallelism
    2. Threads and processes – an overview
      1. Quick anatomy of a thread
        1. Killing threads
        2. Context-switching
      2. The Global Interpreter Lock
      3. Race conditions and deadlocks
        1. Race conditions
          1. Scenario A – race condition not happening
          2. Scenario B – race condition happening
        2. Locks to the rescue
          1. Scenario C – using a lock
        3. Deadlocks
      4. Quick anatomy of a process
        1. Properties of a process
      5. Multithreading or multiprocessing?
    3. Concurrent execution in Python
      1. Starting a thread
      2. Starting a process
      3. Stopping threads and processes
        1. Stopping a process
      4. Spawning multiple threads
      5. Dealing with race conditions
      6. A thread's local data
      7. Thread and process communication
        1. Thread communication
        2. Sending events
        3. Inter-process communication with queues
      8. Thread and process pools
      9. Using a process to add a timeout to a function
    4. Case examples
      1. Example one – concurrent mergesort
        1. Single-thread mergesort
        2. Single-thread multipart mergesort
        3. Multithreaded mergesort
        4. Multiprocess mergesort
      2. Example two – batch sudoku-solver
        1. What is Sudoku?
        2. Implementing a sudoku-solver in Python
        3. Solving sudoku with multiprocessing
      3. Example three – downloading random pictures
        1. Downloading random pictures with asyncio
    5. Summary
  18. 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
  19. 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 can we improve the application?
    3. Where do we go from here?
      1. The turtle module
      2. wxPython, PyQt, and PyGTK
      3. The principle of least astonishment
      4. Threading considerations
    4. Summary
  20. Data Science
    1. IPython and Jupyter Notebook
      1. Installing the required libraries
      2. Using Anaconda
      3. Starting a 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
  21. Web Development
    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
    7. Farewell
  22. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think