Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learn Python by Building Data Science Applications

You're reading from  Learn Python by Building Data Science Applications

Product type Book
Published in Aug 2019
Publisher Packt
ISBN-13 9781789535365
Pages 482 pages
Edition 1st Edition
Languages
Authors (2):
Philipp Kats Philipp Kats
Profile icon Philipp Kats
David Katz David Katz
Profile icon David Katz
View More author details

Table of Contents (26) Chapters

Preface Section 1: Getting Started with Python
Preparing the Workspace First Steps in Coding - Variables and Data Types Functions Data Structures Loops and Other Compound Statements First Script – Geocoding with Web APIs Scraping Data from the Web with Beautiful Soup 4 Simulation with Classes and Inheritance Shell, Git, Conda, and More – at Your Command Section 2: Hands-On with Data
Python for Data Applications Data Cleaning and Manipulation Data Exploration and Visualization Training a Machine Learning Model Improving Your Model – Pipelines and Experiments Section 3: Moving to Production
Packaging and Testing with Poetry and PyTest Data Pipelines with Luigi Let's Build a Dashboard Serving Models with a RESTful API Serverless API Using Chalice Best Practices and Python Performance Assessments Other Books You May Enjoy

First Steps in Coding - Variables and Data Types

Having set up all the tools, you're now ready to dive into development. Fire up Jupyter—in this chapter, we will get our hands dirty with code! We'll start with the concept of variables, and learn how to assign and use them in Python. We will discuss best practices on naming them, covering both strict requirements and general conventions. Next, we will cover Python's basic data types and the operators they support, including integers, decimal numbers (floats), strings, and Boolean values. Each data type has a corresponding behavior, typing rules, built-in methods, and works with certain operators.

At the end of this chapter, we will put everything we learned into practice by writing our own vacation budgeting calculator.

The topics covered in this chapter are as follows:

  • Assigning variables
  • Naming the variables...

Technical requirements

You can follow the code for this chapter in the Chapter02/first_code.ipynb notebook. No additional packages are required, just Python.

You can find the code via the following link, which is in the GitHub repository in the Chapter02 folder (https://github.com/PacktPublishing/Learn-Python-by-Building-Data-Science-Applications).

Important note: In this and many other chapters, we'll include both snippets of code and interactive shells, similar to what your code will look like in Jupyter. In order to distinguish the code we ran from the output, in every code block that has an interaction, the running code will start after a triple greater than sign (>>>), similar to how it is present in Python consoles. By the way, you still can copy and paste the code—Jupyter will simply ignore this symbol and will run correctly.
...

Assigning variables

At the end of the previous chapter, we ran a simple Python function for the sake of testing:

print('Hello world!')

Here, "Hello world" is an argument, that is, a data point used as an input for the function. In this particular case, we used a raw data value. However, this approach won't get us far—what if we need to change this value, or use it in some other code? This can be done by using variables!

Variables are one of the most basic and powerful concepts in programming. You can think of them as aliases, similar to variables in math equations. Variables are representations of the actual underlying data in the code, which allow us to write operations and describe relations without knowing the exact values the code will operate on. This allows us to write generalized code, which can be used multiple times and in different situations...

Naming the variable

Naming variables may seem to be a minor topic, but trust us, adopting a good habit of proper naming will save you a lot of time and nerves down the road. Do your best to name variables wisely and consistently. Ambiguous names will make code extremely hard to read, understand, and debug, for no good reason.

Now, technically there are just three requirements for variable names:

  • You cannot use reserved words: False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, or raise. You also cannot use operators or special symbols (+, -, /, *, %, =, <, >, @, &) or brackets and parentheses as part of variable names.
  • Variable names can't start with digits.
  • Variable names can't contain whitespace. Use the...

Understanding data types

Every data point in programming has a type. This type defines how much memory is allocated, how the value behaves, what operations Python will allow you to do with it, and more. Understanding the properties of different data types is vital for effective programming in Python.

You can always check the value's type with another built-in function, type():

>>> type(pi)
float

>>> type(name)
str

>>> type(age)
int

>>> type(sky_is_blue)
bool

As we can see, pi is a float, name is a string, age is an integer, and sky_is_blue is a Boolean value. These four types represent the most popular data types that are built into Python. The fifth one is None (of the NoneType type): the data type of one value that represents, well, nothing (a non-existent value). There are a few more data types, such as complex numbers, but we won't use...

Converting the data types

Quite often, there is a need to convert one data type to another, such as a float to an integer, or a string into a number and back. No worries! It is easy to achieve using built-in functions. However, there are some conversion rules to be learned. A string to a float is as follows:

>>> float(“2.5”)
2.5

A string to an integer is as follows:

>>> int(“45”)
45

A float to an integer and vice versa are as follows:

>>> int(4.521)
4

>>> float(5)
5.0

Booleans to integers, floats, and strings are as follows:

>>> int(True)
1

>>> float(False)
0.0

>>> str(True)
'True'

If Python cannot convert values, then it will raise an error:

>>> int(“2.5”)
File "<ipython-input-11-cf753495344d>", line 1
int(“2.5”)
^
SyntaxError...

Exercise

As a practical exercise, let's solve a simple, yet annoying, problem: converting the temperature from Celsius to Fahrenheit and back. Indeed, the formula is easy, but every time we need to do it in our head, it takes some time. The formulas are as follows:

T(°F) = T(°C) × 9/5 + 32

T(°C) = (T(°F) - 32) × 5/9

Let's calculate the Celsius equivalent of 100°F!

First, let's store the constants and our input as variables:

CONST = 32
RATIO = 5/9

T_f = 100

Now, let's do the conversion:

>>> T_c = (T_f - CONST) * RATIO
>>> T_c
37.77777777777778

Now, let's convert it back:

>>> T_f2 = (T_c / RATIO) + CONST
>>> T_f2
100.0

What is the simplest way to compute the following code for a different temperature? It seems that the easiest way is to change the initial value of the variables, and everything...

Summary

In this chapter, we learned about the concept of variables. We now know how to assign and update variables, and use them as function arguments. Next, we learned about Python's basic data types, which represent text, numerical, and logical values. Each data type behaves differently and works with different operators. We had to review each of them on their own and execute snippets of code. That included numerical operations, the order of computation, string methods, and logical operations. As a result, in the last section of this chapter, we were able to compute the answer to a specific problem and generate a simple textual report as a result.

In the next chapter, we'll start by reviewing our solution and discuss how we can make it better by introducing functions.

Questions

  1. Why do we need to use variables in code?
  2. What is the recommended way to name variables? Why does it matter?
  3. What do data types mean and why do they matter for computation?
  4. What are the four most popular data types in Python?
  5. What does the @ operator stand for? Why doesn't it work?
  6. What are the two operators that will work with strings?
  7. How would you combine the results of two tests if we need to return a True value, but only when both of them return True? What about when at least one returns True? What about if only one (but not both) returns True?

Further reading

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learn Python by Building Data Science Applications
Published in: Aug 2019 Publisher: Packt ISBN-13: 9781789535365
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}