Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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
Learning Python
Learning Python

Learning Python

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

AU$50.99
By Fabrizio Romano
Full star icon Full star icon Full star icon Full star icon Half star icon
4.1 (21 Ratings)
Pages 442
Published in Dec 2015
Product Type eBook
Edition 1st Edition
ISBN 9781785284571
Learning Python

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ 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
$149.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ 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 AU$5 each
Feature tick icon Exclusive print discounts
$209.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ 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 AU$5 each
Feature tick icon Exclusive print discounts

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learning Python

Chapter 2. Built-in Data Types

 

"Data! Data! Data!" he cried impatiently. "I can't make bricks without clay."

 
 --Sherlock Holmes - The Adventure of the Copper Beeches

Everything you do with a computer is managing data. Data comes in many different shapes and flavors. It's the music you listen, the movie you stream, the PDFs you open. Even the chapter you're reading at this very moment is just a file, which is data.

Data can be simple, an integer number to represent an age, or complex, like an order placed on a website. It can be about a single object or about a collection of them.

Data can even be about data, that is, metadata. Data that describes the design of other data structures or data that describes application data or its context.

In Python, objects are abstraction for data, and Python has an amazing variety of data structures that you can use to represent data, or combine them to create your own custom data. Before we delve into the specifics, I want you to be very clear about objects...

Everything is an object


As we already said, everything in Python is an object. But what really happens when you type an instruction like age = 42 in a Python module?

Tip

If you go to http://pythontutor.com/, you can type that instruction into a text box and get its visual representation. Keep this website in mind, it's very useful to consolidate your understanding of what goes on behind the scenes.

So, what happens is that an object is created. It gets an id, the type is set to int (integer number), and the value to 42. A name age is placed in the global namespace, pointing to that object. Therefore, whenever we are in the global namespace, after the execution of that line, we can retrieve that object by simply accessing it through its name: age.

If you were to move house, you would put all the knives, forks, and spoons in a box and label it cutlery. Can you see it's exactly the same concept? Here's a screenshot of how it may look like (you may have to tweak the settings to get to the same view...

Mutable or immutable? That is the question


A first fundamental distinction that Python makes on data is about whether or not the value of an object changes. If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.

It is very important that you understand the distinction between mutable and immutable because it affects the code you write, so here's a question:

>>> age = 42
>>> age
42
>>> age = 43  #A
>>> age
43

In the preceding code, on the line #A, have I changed the value of age? Well, no. But now it's 43 (I hear you say...). Yes, it's 43, but 42 was an integer number, of the type int, which is immutable. So, what happened is really that on the first line, age is a name that is set to point to an int object, whose value is 42. When we type age = 43, what happens is that another object is created, of the type int and value 43 (also, the id will be different), and the name age is set to point...

Numbers


Let's start by exploring Python's built-in data types for numbers. Python was designed by a man with a master's degree in mathematics and computer science, so it's only logical that it has amazing support for numbers.

Numbers are immutable objects.

Integers

Python integers have unlimited range, subject only to the available virtual memory. This means that it doesn't really matter how big a number you want to store: as long as it can fit in your computer's memory, Python will take care of it. Integer numbers can be positive, negative, and 0 (zero). They support all the basic mathematical operations, as shown in the following example:

>>> a = 12
>>> b = 3
>>> a + b  # addition
15
>>> b - a  # subtraction
-9
>>> a // b  # integer division
4
>>> a / b  # true division
4.0
>>> a * b  # multiplication
36
>>> b ** a  # power operator
531441
>>> 2 ** 1024  # a very big number, Python handles it gracefully
17976931348623159077293051907890247336179769789423065727343008115...

Immutable sequences


Let's start with immutable sequences: strings, tuples, and bytes.

Strings and bytes

Textual data in Python is handled with str objects, more commonly known as strings. They are immutable sequences of unicode code points. Unicode code points can represent a character, but can also have other meanings, such as formatting data for example. Python, unlike other languages, doesn't have a char type, so a single character is rendered simply by a string of length 1. Unicode is an excellent way to handle data, and should be used for the internals of any application. When it comes to store textual data though, or send it on the network, you may want to encode it, using an appropriate encoding for the medium you're using. String literals are written in Python using single, double or triple quotes (both single or double). If built with triple quotes, a string can span on multiple lines. An example will clarify the picture:

>>> # 4 ways to make a string
>>> str1 =...

Mutable sequences


Mutable sequences differ from their immutable sisters in that they can be changed after creation. There are two mutable sequence types in Python: lists and byte arrays. I said before that the dictionary is the king of data structures in Python. I guess this makes the list its rightful queen.

Lists

Python lists are mutable sequences. They are very similar to tuples, but they don't have the restrictions due to immutability. Lists are commonly used to store collections of homogeneous objects, but there is nothing preventing you to store heterogeneous collections as well. Lists can be created in many different ways, let's see an example:

>>> []  # empty list
[]
>>> list()  # same as []
[]
>>> [1, 2, 3]  # as with tuples, items are comma separated
[1, 2, 3]
>>> [x + 5 for x in [2, 3, 4]]  # Python is magic
[7, 8, 9]
>>> list((1, 3, 5, 7, 9))  # list from a tuple
[1, 3, 5, 7, 9]
>>> list('hello')  # list from a string
['h',...

Set types


Python also provides two set types, set and frozenset. The set type is mutable, while frozenset is immutable. They are unordered collections of immutable objects.

Hashability is a characteristic that allows an object to be used as a set member as well as a key for a dictionary, as we'll see very soon.

Note

An object is hashable if it has a hash value which never changes during its lifetime.

Objects that compare equally must have the same hash value. Sets are very commonly used to test for membership, so let's introduce the in operator in the following example:

>>> small_primes = set()  # empty set
>>> small_primes.add(2)  # adding one element at a time
>>> small_primes.add(3)
>>> small_primes.add(5)
>>> small_primes
{2, 3, 5}
>>> small_primes.add(1)  # Look what I've done, 1 is not a prime!
>>> small_primes
{1, 2, 3, 5}
>>> small_primes.remove(1)  # so let's remove it
>>> 3 in small_primes  # membership...

Mapping types – dictionaries


Of all the built-in Python data types, the dictionary is probably the most interesting one. It's the only standard mapping type, and it is the backbone of every Python object.

A dictionary maps keys to values. Keys need to be hashable objects, while values can be of any arbitrary type. Dictionaries are mutable objects.

There are quite a few different ways to create a dictionary, so let me give you a simple example of how to create a dictionary equal to {'A': 1, 'Z': -1} in five different ways:

>>> a = dict(A=1, Z=-1)
>>> b = {'A': 1, 'Z': -1}
>>> c = dict(zip(['A', 'Z'], [1, -1]))
>>> d = dict([('A', 1), ('Z', -1)])
>>> e = dict({'Z': -1, 'A': 1})
>>> a == b == c == d == e  # are they all the same?
True  # indeed!

Have you noticed those double equals? Assignment is done with one equal, while to check whether an object is the same as another one (or 5 in one go, in this case), we use double equals. There is also...

The collections module


When Python general purpose built-in containers (tuple, list, set, and dict) aren't enough, we can find specialized container data types in the collections module. They are:

Data type

Description

namedtuple()

A factory function for creating tuple subclasses with named fields

deque

A list-like container with fast appends and pops on either end

ChainMap

A dict-like class for creating a single view of multiple mappings

Counter

A dict subclass for counting hashable objects

OrderedDict

A dict subclass that remembers the order entries were added

defaultdict

A dict subclass that calls a factory function to supply missing values

UserDict

A wrapper around dictionary objects for easier dict subclassing

UserList

A wrapper around list objects for easier list subclassing

UserString

A wrapper around string objects for easier string subclassing

We don't have the room to cover all of them, but you can find plenty of examples in the official documentation...

Final considerations


That's it. Now you have seen a very good portion of the data structures that you will use in Python. I encourage you to take a dive into the Python documentation and experiment further with each and every data type we've seen in this chapter. It's worth it, believe me. Everything you'll write will be about handling data, so make sure your knowledge about it is rock solid.

Before we leap into the next chapter, I'd like to make some final considerations about different aspects that to my mind are important and not to be neglected.

Small values caching

When we discussed objects at the beginning of this chapter, we saw that when we assigned a name to an object, Python creates the object, sets its value, and then points the name to it. We can assign different names to the same value and we expect different objects to be created, like this:

>>> a = 1000000
>>> b = 1000000
>>> id(a) == id(b)
False

In the preceding example, a and b are assigned to two...

Summary


In this chapter, we've explored the built-in data types of Python. We've seen how many they are and how much can be achieved by just using them in different combinations.

We've seen number types, sequences, sets, mappings, collections, we've seen that everything is an object, we've learned the difference between mutable and immutable, and we've also learned about slicing and indexing (and, proudly, negative indexing as well).

We've presented simple examples, but there's much more that you can learn about this subject, so stick your nose into the official documentation and explore.

Most of all, I encourage you to try out all the exercises by yourself, get your fingers using that code, build some muscle memory, and experiment, experiment, experiment. Learn what happens when you divide by zero, when you combine different number types into a single expression, when you manage strings. Play with all data types. Exercise them, break them, discover all their methods, enjoy them and learn them...

Left arrow icon Right arrow icon
Download code icon Download Code

Key Benefits

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

What You Will Learn

Who Is This Book 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.

Book Description

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.
Category:
Languages:
Concepts:

Frequently bought together


Stars icon
Total AU$ 219.97
Object-Oriented JavaScript
AU$79.99
Learning Python
AU$63.99
R for Data Science
AU$75.99
Total AU$ 219.97 Stars icon

Table of Contents

(12 Chapters)
Introduction and First Steps – Take a Deep Breath Chevron down icon Chevron up icon
Built-in Data Types Chevron down icon Chevron up icon
Iterating and Making Decisions Chevron down icon Chevron up icon
Functions, the Building Blocks of Code Chevron down icon Chevron up icon
Saving Time and Memory Chevron down icon Chevron up icon
Advanced Concepts – OOP, Decorators, and Iterators Chevron down icon Chevron up icon
Testing, Profiling, and Dealing with Exceptions Chevron down icon Chevron up icon
The Edges – GUIs and Scripts Chevron down icon Chevron up icon
Data Science Chevron down icon Chevron up icon
Web Development Done Right Chevron down icon Chevron up icon
Debugging and Troubleshooting Chevron down icon Chevron up icon
Summing Up – A Complete Example Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon
4.1
(21 Ratings)
5 star 52.4%
4 star 28.6%
3 star 4.8%
2 star 9.5%
1 star 4.8%
Filter icon Filter
Top Reviews

Filter reviews by




Miklos Vincze Feb 14, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon
5
I have recently started working with Python after working many years with PHP. I have found this book very useful to get familiar with the language and helped me a lot to learn how to do things "the Python way". It covers lots of interesting topics, such as testing, web development, debugging, code performance, all of them are accompanied by nice examples. After reading this book, now I understand how consistent and nice Python is and I have an idea how it is different to the other OOP languages I have worked with before.However I am not new to software development, I believe this book would be really useful for those too who have recently started learning it (perhaps for those as well who are completely new to it). This book doesn't only teach you how to write code. It teaches you how to do it well. It tells you about good practices that help you avoid mistakes that beginners tend to make. It helps you to make the first steps for becoming a professional developer and prepares for the difficulties you are going to face.
Amazon Verified review Amazon
Jakub Borys Feb 09, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon
5
As a new Python developer myself I was super excited to find out that Fabrizio will be publishing a book on the subject.Coming from a statically typed languages background, I found dynamic languages quite refreshing. I had done medium size project in Ruby and now found myself in a Python shop. Python is one of these languages that you can hit the ground running with very quickly, but to appreciate it in full and to understand its philosophy you need to dig dipper. This book is for everyone who wants to do so.There are many conventions when writing Python which are considered "Pythonic". You'll be able to learn about them by following simple examples and straightforward explanations provided by the author. There are many hidden features and gotchas in Python that this book will point you to so you can maximize efficiency and elegance of your work. Some of more fun that I found are: negative indexing, using else with 'for' and 'while' loops, LEGB rule and so on....On top of this, not much prior programming knowledge is expected from the reader (although some would be preferable since samples getting complicated quickly)Overall I enjoyed reading this book and would highly recommend it to anyone.
Amazon Verified review Amazon
Chris Smith May 14, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon
5
A excellent text for those who have some experience in programming. The author really opened my eyes to the power and ease of use of Python. I would not recommend this book to someone who is just starting out with programming. Come back to this one after you have gone through a few beginners tutorials, and you will build on the fundamentals you have learned.
Amazon Verified review Amazon
macieksobczak Feb 15, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon
5
I'm very passionate about the educational aspects of programming and because of that I got interested in Learning Python by Fabrizio Romano. For a long time I was looking for a single book which could fulfil the following requirements:- introduce programming concepts in a very clear but not too simple way so that the reader would feel that his time spent with the material is highly optimized and there are no over-explained ideas- focus on the practical aspects therefore showing how really a given language is used (by really of course I mean professionally) and not merely being a reference to the whole richness of modern programming languages. The reference type of books are in my opinion very harmful since way too often they are leaving the reader with enormous set of possible permutations of language constructs that ultimately make the user more lost than before reading the book.- showing that programming is highly creative and collaborative activity.Fulfilling all above conditions requires from the author an incredible sense of balance and deep understanding of readers mind, skills and motivation and in my opinion the author of Learning Python achieved that.I'm quite an advanced Python developer with few years of professional experience and initially I was only planning to read few chapters (advance ones) of Learning Python but because of some intuition I started to read from the first chapter and after few minutes I was hooked! I loved it! Here are some of things I've noted down while reading the book:- the author used very light conversational style which makes the text very easy to read and follow- the idea of using inline comments in the code snippets making them a natural almost organic continuation of the main text is ingenious!- incredible amount of side threads that introduce certain concepts which will be fully outlined later in book but enable one to start becoming comfortable with way earlier.- chapters are organized in a brilliant fashion not using some artificial and highly theoretical categorisation but rather the practicality and intuition.- projects (especially the one in last chapter) are highly practical and could be easily used in real world products.I think that the best way to describe Learning Python is to compare it to a very good book for studying one of the foreign languages, a book which does not focus on every single aspect of a language by overflowing the reader with tables of grammar rules, declinations and super boring and useless examples but rather showing beauty, richness, smartness and adaptivity of certain ideas and concepts making the language alive and such a powerful tool to communicate, create poetry and literally construct any yet unthinkable thoughts.Quite accidentally while reading Learning Python I've found a quote by Antoine de Saint-Exupéry which in a prefect way describes what I really tried to convey above:```If you want to build a ship, don't drum up people to collect wood and don't assign them tasks and work, but rather teach them to long for the endless immensity of the sea```And without any doubts Fabrizio Romano and his Learning Python taught me how to long for the endless immensity and richness of the world of Python.
Amazon Verified review Amazon
mizar Mar 25, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon
5
This is a very impressive work. Bought the book and read it very quickly, it gave me a very bright idea of what python can do and cleared me out of some subtle doubts about this language. I was used to do some python projects, with Django framework, but I never had the opportunity to really know this astounding language, and, I must say, in this warming way.Yes, that’s what I felt the most important in this book. The writer seems to feel tied to the reader in a mission to catch always his attention, with good examples and funny analogies when forced toexplain things. I felt reading this book something like you’re in a classroom with a teacher that tries to make you think but at the same time he must avoid you to get asleep or watch out of the window.Maybe I read a very overly complicated Groovy book before this, but I appreciated so much the effort to explain in the simplest way possible a lot of concepts, and made me feel at ease with every single page. Furthermore most of chapters aim to giving you a good knowledge about best practices both in design phase and implementation phase, alerting from every possible mistake you should avoid from the very beginning of your learning.In the end I think it’s a very solid base to learn the language or to understand better some aspects of django or even other frameworks. Chapters from 9 to 11 are my favorites because they inspect every kind of things you can do with Python and Django about Web and Data Analysis, and they revealed to be really helpful for almost every project I got involved.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon

Loading shipping options...

Unable to load shipping costs. Please try again later.

Estimated Shipping Cost

Deliver to -
Modal Close icon
Modal Close icon