Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python Essentials
Python Essentials

Python Essentials: Modernize existing Python code and plan code migrations to Python using this definitive guide

eBook
€23.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Python Essentials

Chapter 2. Simple Data Types

Now we'll look at a number of data types that are built-in as well as some that are part of Python's standard library. We'll start with Python's numeric types. These include three built-in types: int, float, and complex, plus the standard library types Fraction and Decimal.

We'll also look at strings, str, and simple collections, tuple. These are more complex than numbers because they contain multiple items. Since their behavior is less complex than the kinds of objects we'll see in later chapters, they serve as a good introduction to the general concept of sequences in Python.

Note the capitalization of the names of Fraction and Decimal. The built-in type names start with a lowercase letter. Types that we must import have a module name that starts with a lowercase letter, but the type name starts with a capital letter. This convention is widespread, but not universal.

All of the types we'll look at in this chapter have...

Introducing the built-in operators

Before looking at the various kinds of numbers available, we'll introduce the Python operators. The operators fall into three broad groups:

Group

Operators

Arithmetic

+, -, *, **, /, //, %

Bit-oriented

<<, >>, &, |, ^, ~

Comparison

<, >, <=, >=, ==, !=

The differences between these groups are partly subjective. There's only a small technical difference in the way the comparison operators work. Most of the operators are binary, only one (~) is unary, and a few (+, -, *, **) can be used in either context.

The +, -, *, /, and % operators have meanings similar to those used other programming languages. There is an arithmetic meaning for and +. Python adds the ** operator when raising a number to a power. The ** operator takes higher precedence than the unary form -; this means that -2**4 is -16.

Bit-oriented operators apply only to integers. They also apply to sets. These are emphatically not logical...

The numeric tower

We've seen Python's three built-in numeric types: int, float, complex, plus two more types—Fraction and Decimal—imported from the standard library. The numbers module in the standard library provides four base class definitions for the numeric types. We rarely need to use this module explicitly; it's a convention that we need when we have to implement our own numeric types.

The numeric types form a kind of "tower" that parallels the various kinds of numbers seen in conventional mathematics. The foundation of the tower is integers. Rational numbers are above integers. Floating-point values are still further up, and complex numbers are at the top of the tower.

A common expectation is that a language will automatically coerce numeric values to permit expressions such as 2*2.718 to work properly and produce a useful result. When multiplying an integer by a float value, we expect integers to be coerced to a floating-point value.

In order...

The math libraries

The Python library has six modules relevant to mathematical work. These are described in Chapter 9, Numeric and Mathematical Modules, of the Python Standard Library document. Beyond this, we have external libraries such as NumPy (http://www.numpy.org) and SciPy (http://www.scipy.org). These libraries include vast collections of sophisticated algorithms. For an even more sophisticated toolset, the Anaconda project (https://store.continuum.io/cshop/anaconda/) combines NumPy, SciPy, and 18 more packages.

These are the relevant built-in numeric packages:

  • numbers: This module defines the essential numeric abstractions. We rarely need this unless we're going to invent an entirely new kind of number.
  • math: This module has a large collection of functions. It includes basic sqrt(), the various trigonometric functions (sine, cosine, and so on) and the various log-related functions. It has functions for working with the internals of floating-point numbers. It also has the gamma...

Using bits and Boolean values

As noted earlier, the bit-oriented operators &, |, ^, and ~ have nothing to do with Python's actual Boolean operators and, or, not, and if-else. We'll look at Boolean values, logic operators, and related programming in Chapter 5, Logic, Comparisons, and Conditions.

If we misuse the bit-oriented operators & or | in place of a logical and or or, things may appear very peculiar:

>>> 5 > 6 & 3 > 1
True
>>> (5 > 6) & (3 > 1)
False

The first example is clearly wrong. Why? This is because the & operator has relatively high priority. It's not a logical connective, it's more like an arithmetic operator. The & operator is performed first: 6&3 evaluates to 2. Given this, the resulting expression, 5 > 2 > 1, is True.

When we group the comparisons to perform them first, we'll get a False for 5>6, and a True for 3>1. When we apply the & operator the result will be False, which...

Working with sequences

In this chapter, we'll introduce Python sequence collections. We'll look at strings and tuples as the first two examples of this class. Python offers a number of other sequence collections; we'll look at them in Chapter 6, More Complex Data Types. All of these sequences have common features.

Python sequences identify the individual elements by position. Position numbers start with zero. Here's a tuple collection with five elements:

>>> t=("hello", 3.14, 23, None, True)
>>> t[0]
'hello'
>>> t[4]
True

In addition to the expected ascending numbers, Python also offers reverse numbering. Position -1 is the end of the sequence:

>>> t[-1]
True
>>> t[-2]
>>> t[-5]
'hello'

Note that position 3 (or -2) has a value of None. The REPL doesn't display the None object, so the value of t[-2] appears to be missing. For more visible evidence that this value is None, use this:

&gt...

Introducing the built-in operators


Before looking at the various kinds of numbers available, we'll introduce the Python operators. The operators fall into three broad groups:

Group

Operators

Arithmetic

+, -, *, **, /, //, %

Bit-oriented

<<, >>, &, |, ^, ~

Comparison

<, >, <=, >=, ==, !=

The differences between these groups are partly subjective. There's only a small technical difference in the way the comparison operators work. Most of the operators are binary, only one (~) is unary, and a few (+, -, *, **) can be used in either context.

The +, -, *, /, and % operators have meanings similar to those used other programming languages. There is an arithmetic meaning for and +. Python adds the ** operator when raising a number to a power. The ** operator takes higher precedence than the unary form -; this means that -2**4 is -16.

Bit-oriented operators apply only to integers. They also apply to sets. These are emphatically not logical operators. The actual...

The numeric tower


We've seen Python's three built-in numeric types: int, float, complex, plus two more types—Fraction and Decimal—imported from the standard library. The numbers module in the standard library provides four base class definitions for the numeric types. We rarely need to use this module explicitly; it's a convention that we need when we have to implement our own numeric types.

The numeric types form a kind of "tower" that parallels the various kinds of numbers seen in conventional mathematics. The foundation of the tower is integers. Rational numbers are above integers. Floating-point values are still further up, and complex numbers are at the top of the tower.

A common expectation is that a language will automatically coerce numeric values to permit expressions such as 2*2.718 to work properly and produce a useful result. When multiplying an integer by a float value, we expect integers to be coerced to a floating-point value.

In order for this to work, there are two general...

The math libraries


The Python library has six modules relevant to mathematical work. These are described in Chapter 9, Numeric and Mathematical Modules, of the Python Standard Library document. Beyond this, we have external libraries such as NumPy (http://www.numpy.org) and SciPy (http://www.scipy.org). These libraries include vast collections of sophisticated algorithms. For an even more sophisticated toolset, the Anaconda project (https://store.continuum.io/cshop/anaconda/) combines NumPy, SciPy, and 18 more packages.

These are the relevant built-in numeric packages:

  • numbers: This module defines the essential numeric abstractions. We rarely need this unless we're going to invent an entirely new kind of number.

  • math: This module has a large collection of functions. It includes basic sqrt(), the various trigonometric functions (sine, cosine, and so on) and the various log-related functions. It has functions for working with the internals of floating-point numbers. It also has the gamma function...

Using bits and Boolean values


As noted earlier, the bit-oriented operators &, |, ^, and ~ have nothing to do with Python's actual Boolean operators and, or, not, and if-else. We'll look at Boolean values, logic operators, and related programming in Chapter 5, Logic, Comparisons, and Conditions.

If we misuse the bit-oriented operators & or | in place of a logical and or or, things may appear very peculiar:

>>> 5 > 6 & 3 > 1
True
>>> (5 > 6) & (3 > 1)
False

The first example is clearly wrong. Why? This is because the & operator has relatively high priority. It's not a logical connective, it's more like an arithmetic operator. The & operator is performed first: 6&3 evaluates to 2. Given this, the resulting expression, 5 > 2 > 1, is True.

When we group the comparisons to perform them first, we'll get a False for 5>6, and a True for 3>1. When we apply the & operator the result will be False, which is what we expected. Using...

Working with sequences


In this chapter, we'll introduce Python sequence collections. We'll look at strings and tuples as the first two examples of this class. Python offers a number of other sequence collections; we'll look at them in Chapter 6, More Complex Data Types. All of these sequences have common features.

Python sequences identify the individual elements by position. Position numbers start with zero. Here's a tuple collection with five elements:

>>> t=("hello", 3.14, 23, None, True)
>>> t[0]
'hello'
>>> t[4]
True

In addition to the expected ascending numbers, Python also offers reverse numbering. Position -1 is the end of the sequence:

>>> t[-1]
True
>>> t[-2]
>>> t[-5]
'hello'

Note that position 3 (or -2) has a value of None. The REPL doesn't display the None object, so the value of t[-2] appears to be missing. For more visible evidence that this value is None, use this:

>>> t[3] is None
True

The sequences use an extra comparison...

Using string and bytes values


Python string values are similar—in some respects—to simple numeric types. There are a few arithmetic-like operators available and all of the comparisons are defined. Strings are immutable: we cannot change a string. We can, however, easily build new strings from existing strings, making the mutability question as irrelevant for string objects as it is for number objects. Python has two kinds of string values:

  • Unicode: These strings use the entire Unicode character set. These are the default strings Python uses. The input-output libraries are all capable of a wide variety of Unicode encoding and decoding. The name for this type is str. It's a built-in type, so it starts with a lowercase letter.

  • Bytes: Many file formats and network protocols are defined over bytes, not Unicode characters. Python uses ASCII encoding for bytes. Special arrangements must be made to process bytes. The internal type name is bytes.

We can easily encode Unicode into a sequence of bytes...

Left arrow icon Right arrow icon
Download code icon Download Code

Description

This book is designed for Python 2 developers who want to get to grips with Python 3 in a short period of time. It covers the key features of Python, assuming you are familiar with the fundamentals of Python 2.

What you will learn

  • Use Python interactively and master the art of writing efficient Python scripts
  • Learn techniques for working with string data, including how to use regular expressions to parse strings
  • Get to know how the shortcircuit and ifelse logic operators work
  • Explore mutable data structures including list, set, and dict
  • Define functions with positional and optional parameters, and learn to use keyword argument values when calling a function
  • Write generator functions, generator expressions, and comprehensions
  • Master the use of exceptions for handling errors and other unexpected conditions
  • Understand the importance of working with files, context manager, and the with statement

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 30, 2015
Length: 298 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390341
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 30, 2015
Length: 298 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390341
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 116.97
Python Essentials
€32.99
Functional Python Programming
€41.99
Python 3 Object-Oriented Programming - Second Edition
€41.99
Total 116.97 Stars icon

Table of Contents

16 Chapters
1. Getting Started Chevron down icon Chevron up icon
2. Simple Data Types Chevron down icon Chevron up icon
3. Expressions and Output Chevron down icon Chevron up icon
4. Variables, Assignment and Scoping Rules Chevron down icon Chevron up icon
5. Logic, Comparisons, and Conditions Chevron down icon Chevron up icon
6. More Complex Data Types Chevron down icon Chevron up icon
7. Basic Function Definitions Chevron down icon Chevron up icon
8. More Advanced Functions Chevron down icon Chevron up icon
9. Exceptions Chevron down icon Chevron up icon
10. Files, Databases, Networks, and Contexts Chevron down icon Chevron up icon
11. Class Definitions Chevron down icon Chevron up icon
12. Scripts, Modules, Packages, Libraries, and Applications Chevron down icon Chevron up icon
13. Metaprogramming and Decorators Chevron down icon Chevron up icon
14. Fit and Finish – Unit Testing, Packaging, and Documentation Chevron down icon Chevron up icon
15. Next Steps Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(2 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
ruben Aug 26, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has develop the skills on how to program in a very structured way so that it covers all the necessary to be ready to use Python3 in order to be updated to the next version.It covers the main idea of how to use the tools of programming, functions, libraries, structures and the codes to develop your own programming.You will learn how to used the main structure in a programit covers the main topics to be ready and program your own codesThe main topics1: getting started2: simple data types3: expressions and output4: variables, assignment and scoping rules5: logic, comparisons, and conditions6: more complex data types7: basic function definitions8: more advanced functions9: exceptions10: files, databases, networks, and contexts11: class definitions12: scripts, modules, packages, libraries, and applications13: metaprogramming and decorators14: fit and finish – unit testing, packaging, and documentation15: next stepsI really recomend this title has the necessary to learn the basics of this important language and tool to jump to the next generation
Amazon Verified review Amazon
Tim Crothers Aug 21, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I found Python Essentials to be a very solid book depending on your background and intent. This book is best suited if you are an experienced programmer looking to learn Python to add it to your toolkit. To that end the chapters are all matter of fact and straight to the point. Coverage of Python is quite broad despite being just over 250 pages. On the other hand if you're new to programming then this book is unlikely to get you coding in Python successfully. There is very little discussion of "why and when" to use things, just how. The book also lacks any examples of how to tie the pieces all together. All of the Python code is done discretely in snippets illustrating just the necessary information.I gave the book four stars instead of five for a few reasons. Mostly it boils down to the book sending some confusing messages. For instance, the Amazon description "a rapid guide to the fundamental features of Python" is spot on whereas the cover of the book displays "Modernize existing Python code and plan code migrations to Python using this definitive guide". The latter from the cover is definitely not accomplished in my opinion. There is no discussion of code migration or modernization beyond the initial chapters reasons for focusing on Python 3 rather than 2.x. There are a fair number of similar inconsistencies which lead me confused a bit. Ultimately they were mostly just distracting rather than serious flaws.All in all an excellent book for this with solid programming experience looking to learn Python quickly.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.