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
Free Learning
Arrow right icon
Learning Python
Learning Python

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

eBook
$24.99 $36.99
Paperback
$45.99
Subscription
Free Trial
Renews at $19.99p/m

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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...

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...

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...

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...

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
>...

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...

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',...
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

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.

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.

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

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 24, 2015
Length: 442 pages
Edition : 1st
Language : English
ISBN-13 : 9781785284571
Category :
Languages :

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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 24, 2015
Length: 442 pages
Edition : 1st
Language : English
ISBN-13 : 9781785284571
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 155.97
Object-Oriented JavaScript - Second Edition
$54.99
R for Data Science
$54.99
Learning Python
$45.99
Total $ 155.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Introduction and First Steps – Take a Deep Breath Chevron down icon Chevron up icon
2. Built-in Data Types Chevron down icon Chevron up icon
3. Iterating and Making Decisions Chevron down icon Chevron up icon
4. Functions, the Building Blocks of Code Chevron down icon Chevron up icon
5. Saving Time and Memory Chevron down icon Chevron up icon
6. Advanced Concepts – OOP, Decorators, and Iterators Chevron down icon Chevron up icon
7. Testing, Profiling, and Dealing with Exceptions Chevron down icon Chevron up icon
8. The Edges – GUIs and Scripts Chevron down icon Chevron up icon
9. Data Science Chevron down icon Chevron up icon
10. Web Development Done Right Chevron down icon Chevron up icon
11. Debugging and Troubleshooting Chevron down icon Chevron up icon
12. Summing Up – A Complete Example Chevron down icon Chevron up icon
Index 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
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
Vincent Jun 06, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book! This is a well written introduction to Python and good software development in general. I have used R for 7 years intensively for data analyses but wanted to broaden my programming skills.
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.