Overview
By the end of this chapter, you will be able to simplify mathematical expressions with the order of operations using integers and floats; assign variables and change Python types to display and retrieve user information; apply global functions including len()
, print()
, and input()
; manipulate strings using indexing, slicing, string concatenation, and string methods; apply Booleans and nested conditionals to solve problems with multiple pathways; utilize for
loops and while
loops to iterate over strings and repeat mathematical operations, and create new programs by combining math, strings, conditionals, and loops.
Note
This chapter covers the fundamentals of the Python language.
Introduction
In this chapter, we will present vital Python concepts; that is, the core elements that everyone needs to know when starting to code. We will cover a breadth of topics while focusing on math, strings, conditionals, and loops. By the end of this chapter, you will have a strong foundation in Python, and you will be able to write significant Python programs as you continue with the rest of this book.
You will start with a very famous developer example, Python as a calculator. In addition to the standard operations of addition, subtraction, multiplication, division, and exponentiation, you will learn integer division and the modulus operator. By using only basic Python, you can outperform most calculators on the market.
Next, you’ll learn about variables. Python is dynamically typed, meaning that variable types are unknown before the code runs. Python variables do not require special initialization. The first variables we will look at will be integers
, floats
...
Technical requirements
The code files for this chapter are available on GitHub at https://github.com/PacktPublishing/The-Python-Workshop-Second-Edition/tree/main/Chapter01.
In the Preface, we learned how to install Anaconda, which comes with the most updated version of Python and Jupyter Notebook. We are using Jupyter Notebook as the default integrated development environment (IDE) for this book because it is sufficient for your entire Python Workshop journey, including the later chapters on data science.
It’s time to open a Jupyter Notebook and begin our Pythonic journey.
Note
The Python code in most of the chapters of this book will work on almost any IDE that supports Python. Feel free to use Colab notebooks, terminals, Sublime Text, PyCharm, or any other IDE that suits your purposes.
Opening a Jupyter Notebook
To get started with this book, you need to make sure that you have a Jupyter Notebook open. Here are the steps:
- Locate and open Anaconda...
Python as a calculator
Python is an incredibly powerful calculator. By leveraging the math
library, numpy
, and scipy
, Python typically outperforms pre-programmed calculators. In later chapters, you will learn how to use the numpy
and scipy
libraries. For now, we’ll introduce the calculator tools that most people use daily.
Addition, subtraction, multiplication, division, and exponentiation are core operations. In computer science, the modulus operator and integer division are essential as well, so we’ll cover them here.
The modulus
operator is the remainder in mathematical division. Modular arithmetic is also called clock arithmetic. For instance, in mod5, which is a modulus of 5, we count 0,1,2,3,4,0,1,2,3,4,0,1... This goes in a circle, like the hands on a clock, which uses mod12.
The difference between division and integer division depends on the language. When dividing the integer 9 by the integer 4, some languages return 2; others return 2.25. In your case...
Strings – concatenation, methods, and input()
So far, you have learned how to express numbers, operations, and variables. But what about words? In Python, anything that goes between single ('
) or double ("
) quotes is considered a string. Strings are commonly used to express words, but they have many other uses, including displaying information to the user and retrieving information from a user.
Examples include 'hello'
, "hello"
, 'HELLoo00'
, '12345'
, and 'fun_characters: !@ #$%^&*('
.
In this section, you will gain proficiency with strings by examining string methods, string concatenation, and useful built-in functions, including print()
and len()
, by covering a wide range of examples.
String syntax
Although strings may use single or double quotes, a given string must be internally consistent. That is, if a string starts with a single quote, it must end with a single quote. The same is true of double quotes...
String interpolation
When writing strings, you may want to include variables in the output. String interpolation includes the variable names as placeholders within the string. There are two standard methods for achieving string interpolation: comma separators and format.
Comma separators
Variables may be interpolated into strings using commas to separate clauses. It’s similar to the +
operator, except it adds spacing for you.
Look at the following example, where we add Ciao
within a print
statement:
italian_greeting = 'Ciao'
print('Should we greet people with', italian_greeting,
'in North Beach?')
Should we greet people with Ciao in North Beach?
f-strings
Perhaps the most effective way to combine variables with strings is with f-strings. Introduced in Python 3.6, f-strings are activated whenever the f
character is followed by quotations. The advantage is that any variable inside curly...
String indexing and slicing
Indexing and slicing are crucial parts of programming. Indexing and slicing are regularly used in lists, a topic that we will cover in Chapter 2, Python Data Structures. In data analysis, indexing and slicing DataFrames is essential to keep track of rows and columns, something you will practice in Chapter 10, Data Analytics with pandas and NumPy.
Indexing
The characters in strings exist in specific locations. In other words, their order counts. The index is a numerical representation of where each character is located. The first character is at index 0, the second character is at index 1, the third character is at index 2, and so on.
Note
We always start at 0 when indexing in computer programming!
Consider the following string:
destination = 'San Francisco'
'S'
is in the 0th index, 'a'
is in the 1st index, 'n'
is in the 2nd index, and so on, as shown in the following table:
Slicing
A slice is a subset of a string or other element. A slice could be the whole element or one character, but it’s more commonly a group of adjoining characters.
Let’s say you want to access the fifth through eleventh letters of a string. So, you start at index 4 and end at index 10, as was explained in the Indexing section. When slicing, the colon symbol (:
) is inserted between indices, like so: [4:10]
.
There is one caveat: the lower bound of a slice is always included, but the upper bound is not. So, in the preceding example, if you want to include the 10th index, you must use [4:11]
.
Now, let’s have a look at the following example for slicing.
Retrieve the fifth through eleventh letters of the destination
variable, which you used in the Indexing section:
destination[4:11]
The output is as follows:
’Francis’
Retrieve the first three letters of destination
:
destination[0:3]
The output is as follows:
’San...
Booleans and conditionals
Booleans, named after George Boole, take the values of True or False. Although the idea behind Booleans is rather simple, they make programming much more powerful.
When writing programs, it’s useful to consider multiple cases. If you prompt the user for information, you may want to respond differently, depending on the user’s answer.
For instance, if the user gives a rating of 0 or 1, you may give a different response than a rating of 9 or 10. The keyword here is if
.
Programming based on multiple cases is often referred to as branching. Each branch is represented by a different conditional. Conditionals often start with an if
clause, followed by else
clauses. The choice of a branch is determined by Booleans, depending on whether the given conditions are True
or False
.
Booleans
In Python, a Boolean class object is represented by the bool
keyword and has a value of True
or False
.
Note
Boolean values must be capitalized in Python...
Loops
“Write the first 100 numbers.”
There are several assumptions implicit in this seemingly simple command. The first is that the student knows where to start, namely at number 1. The second assumption is that the student knows where to end, at number 100. And the third is that the student understands that they should count by 1.
In programming, this set of instructions may be executed with a loop.
There are three key components to most loops:
Python distinguishes between two fundamental kinds of loops: while
loops and for
loops.
while loops
In a while
loop, a designated segment of code repeats, provided that a particular condition is true. When the condition evaluates to false, the while
loop stops running. A while
loop may print out the first 10 numbers.
You could print the first 10 numbers by implementing the print
function 10 times, but using...
Summary
You have gone over a lot of material in this introductory chapter. You have covered math operations, string concatenation and methods, general Python types, variables, conditionals, and loops. Combining these elements allows us to write programs of real value.
Additionally, you have been learning Python syntax. You now understand some of the most common errors, and you’re becoming accustomed to the importance that indentation plays. You’re also learning how to leverage important keywords such as range
, in
, if
, and True
and False
.
Going forward, you now have the key fundamental skills to tackle more advanced introductory concepts. Although there is much to learn, you have a vital foundation in place to build upon the types and techniques discussed here.
In the next chapter, you will learn about some of the most important Python types, including lists, dictionaries, tuples, and sets.