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. 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. 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.
Author(s): Fabrizio Romano
Edition: 2
Year: 2018
Title Page
Copyright and Credits
Learn Python Programming Second Edition
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Foreword
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
A Gentle Introduction to Python
A proper introduction
Enter the Python
About Python
Portability
Coherence
Developer productivity
An extensive library
Software quality
Software integration
Satisfaction and enjoyment
What are the drawbacks?
Who is using Python today?
Setting up the environment
Python 2 versus Python 3
Installing Python
Setting up the Python interpreter
About virtualenv
Your first virtual environment
Your friend, the console
How you can run a Python program
Running Python scripts
Running the Python interactive shell
Running Python as a service
Running Python as a GUI application
How is Python code organized?
How do we use modules and packages?
Python's execution model
Names and namespaces
Scopes
Objects and classes
Guidelines on how to write good code
The Python culture
A note on IDEs
Summary
Built-in Data Types
Everything is an object
Mutable or immutable? That is the question
Numbers
Integers
Booleans
Real numbers
Complex numbers
Fractions and decimals
Immutable sequences
Strings and bytes
Encoding and decoding strings
Indexing and slicing strings
String formatting
Tuples
Mutable sequences
Lists
Byte arrays
Set types
Mapping types – dictionaries
The collections module
namedtuple
defaultdict
ChainMap
Enums
Final considerations
Small values caching
How to choose data structures
About indexing and slicing
About the names
Summary
Iterating and Making Decisions
Conditional programming
A specialized else – elif
The ternary operator
Looping
The for loop
Iterating over a range
Iterating over a sequence
Iterators and iterables
Iterating over multiple sequences
The while loop
The break and continue statements
A special else clause
Putting all this together
A prime generator
Applying discounts
A quick peek at the itertools module
Infinite iterators
Iterators terminating on the shortest input sequence
Combinatoric generators
Summary
Functions, the Building Blocks of Code
Why use functions?
Reducing code duplication
Splitting a complex task
Hiding implementation details
Improving readability
Improving traceability
Scopes and name resolution
The global and nonlocal statements
Input parameters
Argument-passing
Assignment to argument names doesn't affect the caller
Changing a mutable affects the caller
How to specify input parameters
Positional arguments
Keyword arguments and default values
Variable positional arguments
Variable keyword arguments
Keyword-only arguments
Combining input parameters
Additional unpacking generalizations
Avoid the trap! Mutable defaults
Return values
Returning multiple values
A few useful tips
Recursive functions
Anonymous functions
Function attributes
Built-in functions
One final example
Documenting your code
Importing objects
Relative imports
Summary
Saving Time and Memory
The map, zip, and filter functions
map
zip
filter
Comprehensions
Nested comprehensions
Filtering a comprehension
dict comprehensions
set comprehensions
Generators
Generator functions
Going beyond next
The yield from expression
Generator expressions
Some performance considerations
Don't overdo comprehensions and generators
Name localization
Generation behavior in built-ins
One last example
Summary
OOP, Decorators, and Iterators
Decorators
A decorator factory
Object-oriented programming (OOP)
The simplest Python class
Class and object namespaces
Attribute shadowing
Me, myself, and I – using the self variable
Initializing an instance
OOP is about code reuse
Inheritance and composition
Accessing a base class
Multiple inheritance
Method resolution order
Class and static methods
Static methods
Class methods
Private methods and name mangling
The property decorator
Operator overloading
Polymorphism – a brief overview
Data classes
Writing a custom iterator
Summary
Files and Data Persistence
Working with files and directories
Opening files
Using a context manager to open a file
Reading and writing to a file
Reading and writing in binary mode
Protecting against overriding an existing file
Checking for file and directory existence
Manipulating files and directories
Manipulating pathnames
Temporary files and directories
Directory content
File and directory compression
Data interchange formats
Working with JSON
Custom encoding/decoding with JSON
IO, streams, and requests
Using an in-memory stream
Making HTTP requests
Persisting data on disk
Serializing data with pickle
Saving data with shelve
Saving data to a database
Summary
Testing, Profiling, and Dealing with Exceptions
Testing your application
The anatomy of a test
Testing guidelines
Unit testing
Writing a unit test
Mock objects and patching
Assertions
Testing a CSV generator
Boundaries and granularity
Testing the export function
Final considerations
Test-driven development
Exceptions
Profiling Python
When to profile?
Summary
Cryptography and Tokens
The need for cryptography
Useful guidelines
Hashlib
Secrets
Random numbers
Token generation
Digest comparison
HMAC
JSON Web Tokens
Registered claims
Time-related claims
Auth-related claims
Using asymmetric (public-key) algorithms
Useful references
Summary
Concurrent Execution
Concurrency versus parallelism
Threads and processes – an overview
Quick anatomy of a thread
Killing threads
Context-switching
The Global Interpreter Lock
Race conditions and deadlocks
Race conditions
Scenario A – race condition not happening
Scenario B – race condition happening
Locks to the rescue
Scenario C – using a lock
Deadlocks
Quick anatomy of a process
Properties of a process
Multithreading or multiprocessing?
Concurrent execution in Python
Starting a thread
Starting a process
Stopping threads and processes
Stopping a process
Spawning multiple threads
Dealing with race conditions
A thread's local data
Thread and process communication
Thread communication
Sending events
Inter-process communication with queues
Thread and process pools
Using a process to add a timeout to a function
Case examples
Example one – concurrent mergesort
Single-thread mergesort
Single-thread multipart mergesort
Multithreaded mergesort
Multiprocess mergesort
Example two – batch sudoku-solver
What is Sudoku?
Implementing a sudoku-solver in Python
Solving sudoku with multiprocessing
Example three – downloading random pictures
Downloading random pictures with asyncio
Summary
Debugging and Troubleshooting
Debugging techniques
Debugging with print
Debugging with a custom function
Inspecting the traceback
Using the Python debugger
Inspecting log files
Other techniques
Profiling
Assertions
Where to find information
Troubleshooting guidelines
Using console editors
Where to inspect
Using tests to debug
Monitoring
Summary
GUIs and Scripts
First approach – scripting
The imports
Parsing arguments
The business logic
Second approach – a GUI application
The imports
The layout logic
The business logic
Fetching the web page
Saving the images
Alerting the user
How can we improve the application?
Where do we go from here?
The turtle module
wxPython, PyQt, and PyGTK
The principle of least astonishment
Threading considerations
Summary
Data Science
IPython and Jupyter Notebook
Installing the required libraries
Using Anaconda
Starting a Notebook
Dealing with data
Setting up the Notebook
Preparing the data
Cleaning the data
Creating the DataFrame
Unpacking the campaign name
Unpacking the user data
Cleaning everything up
Saving the DataFrame to a file
Visualizing the results
Where do we go from here?
Summary
Web Development
What is the web?
How does the web work?
The Django web framework
Django design philosophy
The model layer
The view layer
The template layer
The Django URL dispatcher
Regular expressions
A regex website
Setting up Django
Starting the project
Creating users
Adding the Entry model
Customizing the admin panel
Creating the form
Writing the views
The home view
The entry list view
The form view
Tying up URLs and views
Writing the templates
The future of web development
Writing a Flask view
Building a JSON quote server in Falcon
Summary
A farewell
Other Books You May Enjoy
Leave a review - let other readers know what you think