0% found this document useful (0 votes)
46 views116 pages

Python For Beginners - Edward Thornton

This document is a beginner's guide to Python programming, detailing its capabilities, syntax, and practical applications. It emphasizes Python's simplicity and versatility, making it an ideal choice for new programmers. The guide includes step-by-step instructions for getting started with Python, as well as insights into its use by major companies like Google.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views116 pages

Python For Beginners - Edward Thornton

This document is a beginner's guide to Python programming, detailing its capabilities, syntax, and practical applications. It emphasizes Python's simplicity and versatility, making it an ideal choice for new programmers. The guide includes step-by-step instructions for getting started with Python, as well as insights into its use by major companies like Google.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON FOR BEGINNERS

A Genius Guide to Python Programming

EDWARD THORNTON
© Copyright 2021 - All rights reserved.

It is not legal to reproduce, duplicate, or transmit any part of this document


in either electronic means or in printed format. Recording of this publication
is strictly prohibited and any storage of this document is not allowed unless
with written permission from the publisher except for the use of brief
quotations in a book review.

Contents
Introduction v

1. What Is Python? 1
2. Python Capabilities 16

3. Getting Started with Python 32

4. The Python Syntax 40


5. Functions and Modules 48
6. Expressions in Python 65
7. Strings, Numeric Data, Booleans, and Variables 73

8. Dictionaries and Lists 85

9. Python Tuples, Sets, and Loops 110

10. Your First Program 131

11. File Management 141

Final Words 153

The following chapters will cover every aspect of learning how to do some
of your coding in Python. There are numerous reasons why you might want
to learn how to work with the Python programming language, and we want
to ensure that you can take a few steps from each section and learn how to
adapt them to your specific needs. There are numerous options for learning
to code and accomplishing tasks with programming, but you will discover
that the Python language is one of the best to work with, as this guidebook
will demonstrate.

Python has been used by developers to create applications of various types


and software programs that function across multiple platforms such as Mac
OS X, iOS, Android, Windows 8/10/8.1/7/7.5 and others.

Python is a high-level, interpreted, object-oriented programming language


that supports modules, classes, exceptions, and dynamic typing. It was
created by Guido van Rossum in 1965 and first released in 1991. It is used
across various industries in the finance sector as well as in scientific
research.

Python takes care of the task of multi-tasking and making the most out of all
core functions and libraries, such as functions and methods from v

Python's built-in standard library. The language is fully dynamic, can be


used for object-oriented applications, and supports various operating
systems. It is compatible with UNIX, Linux/Unix, Mac OS X, and Microsoft
Windows.

The language is extremely versatile and very easily adaptable to different


platforms. It offers software developers the freedom to use it on any
platform or utilize its features. The Python programming language has an
interactive console that allows you to test out your programs as you develop
them so you can catch bugs early in your program design stage.

Therefore, if you're interested in learning how to program in Python and


create the next big app, you've come to the right place. This book is intended
to introduce you to Python programming fundamentals, providing a
foundation upon which you can build your knowledge and expertise.
Additionally, I've included some simple projects to get you started as well as
a few exercises to assess your understanding. By the end of the book, you
should have a solid knowledge of Python and its capabilities.
Numerous reasons exist for why you will enjoy working with Python code.
Python is a programming language frequently recommended for beginners
who want to experiment with coding and fall in love with it. One of the
primary reasons for Python's widespread popularity is its simplicity and
ability to accomplish tasks with less code. Even with the addition of tens of
programming languages over the last decade, Python has retained its allure,
and we are confident that it will continue to do so.

Therefore, before you can begin using Python to handle all of your
programming needs, program and all of Python is a high-level programming
language, meaning it is simple to use and read for even the most
inexperienced programmer. The code is written with readability in mind, and
it uses a syntax that enables the programmer to express their concepts
without including pages of code. Compared to other popular programming
it's critical to educate yourself about the the wonderful benefits that come
with it.

vi
languages, such as Java and C++, Python is significantly easier to complete.

This code language's philosophy is straightforward. It believes that a detailed


design is far superior to a complex one and that readability is critical. This is
an excellent language for beginners to learn because they will read and
comprehend the code they write. With other options, they may have to spend
considerable time fine-tuning the code and adding numerous additional
symbols to make it work. However, Python keeps things much more
straightforward, and you may find it easier to read through the lines and
understand what you're doing.

Among the features that you may enjoy with Python are the following: an
elegant syntax that makes reading the programs a breeze and a simple-to-use
language which ensures that the program runs without errors when
performing ad hoc programming tasks or prototyping, without causing
problems with its maintenance. It has an extensive library that can be used
for other programming tasks such as file manip‐ ulation, text searching, and
connecting to web servers. Python is truly an interactive language. This
simplifies the process of testing small pieces of code to determine if they
work. Additionally, you can bundle it with the IDLE development
environment.

Who is this book aimed at?

This book is intended for the complete beginner, the underdog we are
rooting for, and we are sure our confidence will eventually triumph. We'll go
over everything step by step, in as much detail as possible, so that your first
steps down this ostensibly frightening path feel like a walk in the park.
Additionally, we've included illustrations, images, and codes for your
exploration. Thus, if you lack a programming background, this is quite
advantageous. Python is an excellent language.

In theory, it would take two to three months of coding for a couple of hours a
day to become fluent in a language like Python. If you intend to apply what
you've learned in a career, you'll need to acquire additional advanced
specializations. That should take about a year if you code for two to three
hours per day. Given that you are here and reading this, we

vii

can assume that you have a specific reason for learning this language.
Whatever it is, we assure you that once you begin, your educational journey
will only improve, and you may discover that you can accom‐ plish much
more with the language than you ever imagined.

We appreciate your interest in this universal language and invite you to join
us for some fun!
viii ONE

What Is Python?
Python is a general-purpose, high-level programming language that was
released for the first time in 1991. It is a highly effective language which is
widely used throughout the world today. The original purpose of this
programming language was to enable programmers to convert require‐
ments into code with fewer lines of code. This is a very noticeable differ‐
ence if you are familiar with other programming languages.

Many large companies, including YouTube, Google, and Facebook, use


Python to develop web applications' back-ends. Additionally, it is widely
used in the fields of data science and data analytics. As previously stated,
one of Python's primary selling points is the simplicity of its programs. It is
not necessary to write a large amount of code to get a program to run.

What is programming?

Programming is the process of determining which data the computer should


process to produce the desired result. There are numerous programming
languages, some more complicated than others, but they all share certain
characteristics. They all require us to select a set of instructions that specify
precisely how we want the computer to operate. It sounds straightforward—
and it is!

Consider the following example: You have just purchased an iPod and want
to use it to listen to music stored on your computer via iTunes. You have a
few songs stored on your computer's hard drive, but you want them to be
transferred to the iPod via Bluetooth. How do you instruct iTunes to perform
this action? Simply connect the iPod and select it from the iTunes menu,
correct? That is correct—but perhaps you should consider what is occurring
here. If all we know is that we need iTunes to transfer music to our iPod,
why are we not simply connecting our computer directly via USB?

If we think like a programmer in this case, we can see that we have some
choices to make. To begin, we must decide which songs to transfer. Second,
we must inform iTunes about the specific songs we wish to transfer. Third,
iTunes must determine how we want them transferred —via iPod or
computer.

How do you accomplish this? To be sure, iTunes is a simple program that the
user can easily control with a few mouse clicks. However, beneath this
simple-to-use interface is a slightly more complicated set of instructions that
specify how iTunes should operate. This is what programming languages
enable us to do with computers. They enable us to type those instructions
and then translate them into commands that the computer can understand
and process.

From the start with Python

The Python idea was discovered in 1980 after the ABC language. Python 2.0
was introduced; it had features like garbage collection and list
comprehensions used in reference cycle collection. Since 1990 when Python
was developed, it has undergone tremendous changes, with a series of
versions following suit. In January 1994, Python version 1.0 was released.
The Python 2 series followed, and it has been available in lower version
numbers, for example, 2.7.11. In general, these series are denoted by the
abbreviations 2.x, 3.x. There are currently a large number of programs
written in the Python 2.x series available on the market.

When Python 3.0 was released in 2008, it brought about a complete


language revision. Python is primarily used for developing software and
webs, for mathematics and scripting systems. The latest version of Python is
known as Python 3, while Python 2 is still prevalent. Python was developed
to help in reading and similar aspects of different languages, like English,
and to emphasize mathematics. A new line is used to complete a Python
command instead of other programming languages that usually use
semicolons. Formatting depends on indenta‐ tion, whitespace, and defining
the scope.

Conversely, Python 3 is a more robust, fault-tolerant, and powerful


programming language than Python 2. Python 3 has undergone signifi‐ cant
changes in comparison to Python 2. At this point, you may be wondering
which Python series to study. If you are new to Python, it is natural, to begin
with, Python 3. However, if you will work on a Python project, you will
need to know the version in which the project was developed, as not all
modules used before Python 3 have been imported to Python 3. However,
the conversion will be completed eventually, and Python 3 will supersede
Python 2.

What is Python programming?


This is a programming language that is object-oriented, high level, and uses
semantics. It is a high level in data structures and a combination of dynamic
typing and binding. This is what makes it attractive to be used for Rapid
Application Development and for connecting different elements.

Python is open-source; this means you can use every version freely for any
commercial application. Python is programmed to work on UNIX, Windows,
and Mac, and can be transferred to Java. Python is a language that helps in
scripting and helps in web applications for different content. It is like Perl
and Ruby. Several imaging programs aid Python; users can create
customized extensions. Other web applications support Python, such as API
like Blender and GIMP.

Python is a joy for the majority of programmers

The majority of programmers adore Python programs due to their high


productivity. Python makes use of an edit-test-debug cycle, which is a quick
cycle that does not require any compilation. As a result, debug‐ ging Python
programs is easier, and they do not generate segmentation faults. When the
interpreter detects an error, an exception is thrown. The interpreter prints a
trace if the program does not know about the exception. On the sourcing
level, the debugger will allow inspecting of any variable. Breakpoints,
arbitrary expressions, and stepping on the code at any point will be settled.
Python creates the debugger, which is more accessible and provides a quick
debugging method, as well as programs for adding prints to the source code
and statements.

Interestingly, because Python is so simple and easy to learn, it aids in


reading the programming language, lowering the cost of maintaining the
program. Python promotes program modularity and code reuse using
packages and modules. Binary distributions of the standard library and the
Python interpreter are available. It is unnecessary to charge for all available
platforms; they can be freely distributed.

The information provided on Python programming is beneficial to both


newcomers and seasoned programmers. The majority of professional
programmers are capable of quickly learning and using Python. There is a
more straightforward way to install Python. The majority of UNIX and
Linux distributions include the most recent Python. That is why the majority
of computers come pre-installed with Python. Before you begin using
Python, you should familiarize yourself with the best inte‐ grated
development environments (IDEs) and text editors for Python. To obtain
additional assistance and information, you can peruse intro‐ ductory books
and code samples.

How to use Python on your PC

Before using Python, you first need to install and run it on your computer,
and once you do that, you will be able to write your first program. Python is
known as a programming platform that cuts across multiple platforms. You
can use it on Linux, macOS, Windows, Java, and .NET machines freely and
as an open source. Most of the Linux and Mac machines come pre-installed
even though on an outdated version. That is the main reason why you will
need to install the latest and current version. An easier way to run Python is
by using Thonny IDE because it is bundled with the newest version of
Python. This is an advantage since you will not need to install it separately.

To achieve all that, you can follow the simple steps below:

1. First, you will need to download Thonny IDE.


2. Then run the installer to install it on your computer.
3. Click on the File option, then new. Save the file on .py extension, for
instance, [Link] or [Link]. You are allowed to use any name for the file,
as long as it ends with .py. Write the Python code on the file before saving it.
4. To run the file, click on RUN, then run current script. Alternatively, click
on F5 to run it.

There is also an alternative to install Python separately; it does not involve


installing and running Python on the computer. You will need to follow the
listed steps below:

1. Look for the latest version of Python and download it. 2. The next step is
to run the installer file to install Python.

When installing, look for Add Python to environment variables. This will
ensure that Python is added to the environment variables, enabling you to
run Python from any computer destination and part. You have the advantage
of choosing the path to install Python. When you complete the process of
installing, you can now run Python.

There is also an alternative and immediate mode to run Python. When


Python is installed, you will type Python on the command line; the
interpreter will be in an immediate mode. You can type Python code, and
when you press enter, you will get the output. For instance, when you type 1
+ 1 and then press enter, you will get the output as 2. You can use it as a
calculator, and to quit the process, type quit, and then press enter.

The second way to do it is by running Python on the Integrated Devel‐


opment Environment. You can use any editing software to write the Python
script file. All you need to do is save the extension .py, and it is considered a
lot easier when you use an IDE. The IDE has distinctive and useful features
like file explorers, code hinting, and syntax checking and highlighting that a
programmer can use for application development.

It would help if you remembered that there is an IDE labelled IDLE when
you install Python that will also be installed. You will use it to run Python on
the computer, and it is considered the best IDE for begin‐ ners. You will have
an interactive shell when IDLE is opened. This is where you can have a new
file and ensure that you save it as a .py extension.

Tech and other organizations using Python

Google

Since the beginning of Python, Google has been its supporter. They chose
Python because it was easy to maintain and deploy, and faster in delivery.
The first web-crawling spider used for Google was in Java 1.0. It was
challenging to use and support, and they had to do it again in Python. Python
is one of the main programming languages that Google uses; the others
include Java, C++, and Go that are used for produc‐ tion. Python is an
integral part of Google. They have been using it for many years, and remain
a system that evolves and grows. Many engi‐ neers that work for Google
prefer using Python. They keep seeking engineers with Python skills.
Facebook

Production engineers that work for Facebook have positive comments about
Python. This has made Python among the top three program‐ ming
languages after C++ and Hack. Facebook adopted Python because it is easy
to use. With over 5000 services on Facebook, this is the best programming
language. The engineers do not need to maintain or write much coding,
allowing them to focus on live improvements, which is one of the reasons
why Facebook infrastructure scales efficiently. Python is used for
infrastructure management, network switch setup, and imaging.

Instagram

From 2016, engineers working for Instagram declared that they were
running the most extensive Django web framework written in Python. The
engineers stated that they like Python because of the simple way to use and
practice. That is why the engineers have invested their resources and time in
using Python in all their trades. In recent times, Instagram has moved its
codes from Python 2.7 to Python 3.

Spotify

Spotify is a music-streaming platform that uses Python as its program‐ ming


language for back-end services and data analysis. Spotify decided to use
Python because they like the way it works in writing and coding. Spotify
will use its analytics to offer its users recommendations and suggestions. For
the interpretation, Spotify uses Luigi that collaborates with Hadoop. The
source will handle the libraries that work together. It will consolidate all the
error logs and help in troubleshooting and rede‐ ployment.

Quora

Before implementing their idea, Quora decided to use Python program‐ ming
for their question and answer platform. The Quora founders decided to go
for Python because it was easy to read and write. For outstanding
performance, they implemented C++. Python is still considered because of
the frameworks it has, like Pylons and Django.

Netflix
Netflix uses Python programming language to help in data analysis from
their servers. They also use that in coding and other Python applications. It
uses Python in the Central Alert Gateway and tracking any security history
and changes.

Dropbox

The cloud storage system Dropbox uses Python for its desktop client. The
programs are coded in Python, and they use different libraries for Windows
and Mac. It is not preinstalled on any Mac or Windows and the Python
version differs.

Reddit

Python programming language was used to implement Reddit. They chose


Python because it has different versions of code libraries, and it was flexible
in developing it.

Histories, origins, and evolution

Python originated from a project Guido van Rossum worked on at the Dutch
CWI research institute—the ABC language—that was eventually abandoned,
and the Amoeba operating system. The new language's primary strength was
its extensibility and ability to run on multiple plat‐ forms. This was critical in
the early days of personal computers, and Python quickly gained popularity
due to its ability to communicate with various libraries and file formats.

Python grew in popularity throughout the 1990s, and years later, more
programming tools were added. It was also instrumental in the develop‐
ment of van Rossum's new initiative, Computer Programming for Everyone.
The goal of CP4E was to make programming accessible to all, not just a
select few, and to promote primary computer and coding literacy as
necessary skills alongside English and math. Python has become the
language of choice for beginners due to its simple syntax and ease of reading
and access.

Python's development began in the 1980s, and Guido van Rossum started
implementing it in 1989. Van Rossum chose the name Monty Python for the
programming language after a British comedy group. Van Rossum released
Python 2.0 in 2000. Simultaneously, he made the development process
transparent and included the community. In 2008, he released Python 3.0.
This version of Python introduced significant changes that broke backward
compatibility (i.e., caused programs written in previous Python releases to
fail to run correctly).

Due to Python 3.0's incompatibility with older source codes, most busi‐
nesses, and developers continued to use Python 2.x. Python 3.x includes a
Python 2.x code conversion tool, which enables migration to the latest
releases. However, some found it more convenient to retain and main‐ tain
their legacy code.

Fundamental philosophy and unusualness

Python's fundamental philosophies can be summarized as simplicity,


transparency, and readability. Van Rossum and the Python community
ensured that all Python programs were comprehensible to anyone after
reading the code just once.

The following are some ways Python programming differs from the
conventions of some of the most popular programming languages:

1. Rather than enclosing code blocks with brackets, you can create them
through indentation alone.
2. A statement does not have to end with a semicolon (;) or any other
symbol.
3. Python allows for seamless integration of other programs and can be used
for a variety of purposes
4. You can write programs with fewer lines of code.
5. There is no requirement to declare variables or define their types.

The popularity and advantages of Python

Python is used in a wide variety of fields, from engineering to finance. It has


been widely used in scientific and computational studies since the 2000s.
Both hardware and software advancements have influenced it.
In terms of hardware, processing power and memory (storage) capacity are
readily available to all. In many cases, interpreted languages such as Python
have become relatively slow in specific processes, and the use of high-level
data structures can be neglected in many cases.

Scientists take the approach to collaborate with the efficient tools devel‐
oped on the Internet in terms of software, the widespread use of the Internet,
and the subsequent flow of open source or free software.

Simple to learn and use

Python is designed to be simple to learn and use. This simple-to-learn


feature is, of course, a significant advantage for any application. If
necessary, it is possible to begin teaching the language to learners in
scientific computation classes and devote time to the subjects being stud‐
ied. Learners who complete programming courses before beginning their
first course in scientific calculation will have the opportunity to explore
additional subjects in greater depth.

Appropriate for smaller programs

When Python is compared to another popular programming language, such


as Java, the number of lines of code required to create an equiva‐ lent
program is approximately 3 to 5 times smaller. When examining the above
code sample, one of the primary reasons for this is the absence of the need to
define the data type for variables.

If we need to define a variable in Java, we must ensure that the variable is


declared with an associated data type, as illustrated below. The keyword
“int” here declares the variable to be an integer.

I int; i=5;

Thus, in Java and the majority of other programming languages, we must


first declare that the variable will be of a particular data type before
assigning it a value. However, in Python, we simply give the vari‐ able's
chosen value, as illustrated below.
i=5
That is all. We saved time on the variable declaration by utilizing Python's
built-in high-level data types and dynamic typing feature. Adaptability

Python includes an interactive shell that enables you to begin quickly writing
code. Below is an illustration of a screenshot. Thus, after installing Python,
you can immediately start issuing statements without requiring additional
installations.

Object-Oriented Design

Most programming languages support object-oriented programming. This


paradigm is predicated on the idea of using objects to represent everyday
occurrences. For example, we could have an employee class with attributes
for a name and ID.

Example: The following illustrates how to define a class in Python

class Employee: def displayCount(self): print(“This is an employee class”)


empl =Employee() [Link] ()

Abundant and diverse library

One of Python's most significant advantages is its extensive collection of


plugin libraries. These libraries provide a wealth of standard functional‐ ity,
eliminating the need for developers to write them manually. Simply connect
a library, and you are ready to go. The various types of libraries available are
listed below:

User interfaces that are graphical in nature Frameworks for the web
Multimedia
Databases
Networking
Frameworks for testing
Automation
Documentation
Administration of the system
Processing of text
Image manipulation

English is the primary language used

Since this program is written in English, it is effortless to read. There aren't


many words that you won't understand, and you won't have to spend time
attempting to decipher what it's saying. The program is entirely in English,
and you will be amazed at how straightforward it can make things.

Python is already installed on a few computers

Python may already be installed on your computer in some cases. Python is


preinstalled on Mac OS X and Ubuntu systems. To get started, you will
simply need to download a text interpreter. Python is compatible with all of
these programs, even if it is not initially installed.

Python is used in conjunction with other programming languages

At first, you are likely to use Python exclusively. It is an excellent program


for learning and growth. However, you may decide over time that you want
to try something new that Python is incapable of doing on its own.
Fortunately, Python is compatible with various programming languages,
including C++ and JavaScript, so you can experiment, learn more, and
ultimately obtain the code you need, even if Python is unable to perform all
of the work.

Python conducts experiments with the interpreter

When you download Python, you will also need a text interpreter. This
makes it easier for Python to read your data. You can use simple prod‐ ucts
that are frequently already installed on your computer, such as Notepad from
Windows, or you can search for a more user-friendly interpreter.

Once you have chosen an interpreter, it is time to get to work writing the
code. Some individuals who are new to coding may feel anxious about
attempting to make the code work. Python can take the words you are typing
and spit them back out in a matter of seconds, aided by the interpreter. You
can test your work as you go!
Therefore, there are numerous advantages to using the Python programming
language. Beginners will appreciate how accessible this program is and how
quickly they can enact some basic commands. Even those with some
experience in programming will be impressed by how this all works!

Utilizations of Python

Python is utilized by around 1.5 million engineers as per the insights. A lot
of sites, APIs, and programming are created utilizing Python as an essential
language. This achievement of Python is additionally a direct result of its
open-source nature that lets software engineers utilize the language as they
like. This is why Python is additionally utilized as a scripting language by
numerous programmers.

Notwithstanding, it isn't apparent to call Python a scripting language in this


comment. We consider Python as a multi-use language that can be valuable
for some fields and clients.
Here are some global organizations that utilize Python for their items:

Google broadly utilizes Python to construct and update its web index
crawlers.
YouTube was at first composed in Python. A great deal of YouTube
combination benefits despite everything uses Python. A ton of Netflix
proposal calculations uses Python to asset them viably.
Dropbox, an acclaimed stockpiling administration, utilizes Python to
scramble the records.
Aside from these couple of models, Python is likewise utilized in iRobot to
create robots.

In addition, there are some specialized fields where Python is widely


utilized.
Systems Programming

This is part of software engineering where we can create a framework for the
board devices; for example, compilers, translators, and shell instruments can
associate with the framework at the portion level. Python is entirely versatile
to this part of software engineering as it has a few extensible libraries that
can assist with making successful projects.
Internet

Python is a simple language to make little web contents. A great deal of


content that kids use are programs created utilizing Python to split record
passwords. A ton of savage compelling devices uses Python to robotize word
reference assaults on a validated server. Python is likewise popular for
creating web applications that can store touchy data. Tons of WebCrawler
and web examination administrations use Python to administer the data.

Integration frameworks

A great deal of equipment segments; for example, Arduino works


successfully only when it is modified to do so. Normally, installed frame‐
works function admirably with conventional auxiliary languages, for
example, C and C++. Python has many libraries that can assist with
coordinating formerly composed python code to installed frameworks.

Database programming

Databases are a basic element to store and control data. There are many
database question languages to store and query information. In any case,
Python is utilized by numerous database heads to screen the interruption
discovery framework that is accessible continually. Many Python libraries
can push designers to naturally check for infections and store reinforcement
in the remote server.

Machine Learning

AI is a blasting software engineering field where we can examine the data


and information that is available. Python has various libraries, for example,
SciPy and Pandas, to keep up the information in a huge manner.
TWO

Python Capabilities
Python has essential elements that will be expounded in detail in the
subsequent chapters of the book. Everybody has to start somewhere, and this
section covers the fundamental concepts that any programmer must
understand to write code. Expect to make mistakes; this is a natural part of
the learning process. If the IDE generates an error message, simply navigate
your preferred search engine and paste the message there. By utilizing
predefined Python expressions, the computer will interpret the action you are
attempting to create and present a result. To write a program, one must first
break down important goals into smaller ones. The majority of programming
begins with sequential programming.

Python-to-Python interaction

As mentioned in the first chapter, the Python programming language is


popular due to the degree of flexibility and dynamic programming that a
developer can use to accomplish various tasks. For instance, you can use
Python interactively to test a statement line by line or to learn new
properties. Additionally, you can use it in script mode if you have a large file
of statements to interpret.
Python includes the Command Line Window or the IDLE, which enables
interactive programming. The command line interface is the most
straightforward way to work with Python. This tool allows the user to
visualize how Python works as it responds to each completed typed
command. While it is not the optimal tool for interacting with Python, it is
the simplest way to learn how Python works.

How to begin with Python

There exist several ways to access Python's command line, depending on the
operating system that is installed on your computer:

Windows users can access the Python command line by clicking on the Start
menu's Python menu item. Additionally, Windows users can navigate to the
shortcut folder and click on the Python command line.
Those running Linux or Mac OS X must launch the Terminal Tool and enter
the Python command to initiate a session.

Computer commands are used to communicate with the machine and instruct
it what to do. As a result, if you want Python to perform a task, you must
enter commands for it to interpret. Following that, Python will convert the
commands to machine-readable instructions and execute them.

To demonstrate how Python works, you will print the following message
using the print command: Greetings and welcome to Python.

1. First, open your Python command line tool


2. Then type the following code at the >>> prompt
3. Print (“Welcome to Python!”)
4. Now press enter to instruct Python that you are done writing the command
5. Next, you will see the message Welcome to Python! on the command line
window
Python responded correctly in the preceding example because you typed the
correct command in the correct format. If you typed the command
incorrectly, Python will display the following message: Invalid syntax.

When a syntax error message appears, it indicates that you have entered an
incomplete statement into your code. Typing the keyword print in capital
letters, for example, will result in a syntax error.

When programming in Python, you can completely omit the print command
by enclosing your statements in quotes. Consider the follow‐ ing: "Welcome
to Python!"

How to exit from Python


Once you are done using Python, you can exit by typing the following
commands:

Quit () Exit () Control-Z then press Enter

Language and the programs

This is the phase where the programming language is presented to make the
user understand the type of language employed and how to use it. This
means that the code you write will run sequentially. In Python, the most
fundamental type of programming instruction is called an expres‐ sion. This
is accomplished by using values and operators to reduce it to a single value,
similar to how a calculator works. For instance, if we enter the code 40 + 2,
we anticipate Python returning the value 42.

The majority of people believe that programmers are adept at mathemat‐ ics.
In reality, programmers are primarily concerned with writing logical
instructions. Inevitably, a programmer is assumed to use mathematics.

Interpretations and modules drafting

Python can be used as an active translator or transcriber by interaction


through the web. It can also be employed to formulate lessons. In exchange,
though, there is one serious concern: that is, it is impossible to keep a copy
of what transpired. On the other hand, using lessons allows you to keep a
record of the work done. In the interactive translator, you can open only one
display page, while in lessons, you can open as many as you need.

Variables

Python uses information that is not constant; these are used to keep the data.
When using these, be sure to put descriptions. These data could be names,
age, addresses, gender, and other similar material.

Outputs and inputs

Any computer program requires interfacing between itself and the person
using it. The user encodes, that is input, and the output is printing what has
been encoded.

Mathematics

Numbers are the common language in computer programs, including


Python. Python also uses mathematical operations, as you will learn later on.
Most of its languages are represented by mathematical equa‐ tions and
symbols.

Loop

You need to understand the term loop in Python. It is a symbol used to


represent repeated word/s or sentence/s in python programming. Anything
that is being repeatedly used can employ a loop.

Python categories

It is essential to be acquainted with the types of python product cate‐ gories


for easy reference and understanding. Python categories are symbolized as
A, B, C that signifies the shifts in language. Examples are 3.3.1 to 3.3.2.
This means there are minor changes, but when it employs something like
[Link] to [Link], there are significant changes.

Cutting

This critical component of Python is used to copy the desired part of data. It
is a method of making programs simple by concentrating on items from a
gamut of data. When you do that, you are removing components that are not
relevant to the program.

Modules

Modules are files of descriptions and declarations of Python. On the other


hand, a module in Python is a list of all the terminologies used by Python
with corresponding explanations of each. Python adopts a method of
consolidating definitions into one folder called a module. These modules can
be introduced into different modules depending on the needs of the
programmer or user.

This is created to allow users to have a better understanding and easy access
to Python's standard library. A programmer or even a beginner can do
modules for his use. Modules can be on indexing and searching, Audio and
Music, Web development, Console, and Database. Python provides an array
of modules that you can use. You can also make your own.

Source codes

Generating Python source codes can be tedious if you do not know how to
derive your codes. Program developers now have an application that
converts your Python 2 codes to Python version 3 codes from AST.
You can create your code as discussed in the chapters, and it is easy to
append strings to a list to create a code, but it won't hurt you if you know
how to generate Python source codes. One way of doing this is to use
context managers.

These are the essential elements in Python. There are more, but with the
ones presented, one can already start using Python and learn the others as
you go on in your programming.

Objects and their reliability

Python will check whether the data type is empty or not, so you will not
have to do so before including it in your program. For instance, if your tuple
has a length of zero or is equal to having inserted an empty tuple, you have
triggered Python's checker to go in and verify that the object you have
entered is valid.

In essence, any number you enter into Python will return true, but if you
enter zero, you will receive a false. In the examples that follow, a string will
be your string as it checks out Python truthfulness. Conversely, when you
want Python to validate the integrity of the objects contained in strings,
tuples, lists, or dicts, you can use them.

For instance, consider the following:


Exhibit 1:
A string = project #this is an accurate illustration, as the string is not empty.
Exhibit 2:
A string =" #this one is false because no data has been entered into the
string, rendering it empty.
Exhibit 3:
If len (a string) is greater than zero: Print “a_string is not truly empty”

Because Python considers zero to be an empty type, you will receive an


incorrect evaluation of your type when Python verifies the truthfulness of its
objects. This will occur even if you believe it should not because zero is a
number, but Python will disregard this because it is not how the program
was written.
Lambda functions in Python

There will be times in your code when you need to pass a function as an
argument. Alternatively, you may discover that you are required to perform a
brief but complex operation several times in a row and do not wish to type it
out as many times as necessary.

You can either define your function normally or create a lambda func‐ tion
that will take the expression and return the appropriate result for the number
of times it needs to be repeated. Whichever plan you choose, you will define
your function precisely the same way.

Exhibit 1
Subtract (c, z): c – z Add 3 = lambda c, z: c-z, c-z

One of the wonderful things about using the lambda function is that you will
be using it as an expression, which means that you will have the knowledge
to use it in a different statement.
With this example, you will see the map function calling on functions for
each element in the list, which results in a list of results.

Exhibit 2
Map (lambda c: c*c, [ 8, 9, 10, 3, 1]) = square Your outcome will be as
follows: [64, 81, 100, 9, 1].

Without the lambda function, you would be forced to define each func‐ tion
individually. With lambda, you will be able to save both lines of code and
variable names for the function you are using.

Lambda functions have the following syntax: variable(s) Lambda :


expression

Your expression will be written in Python. The scope will always include
both the local and global scopes. The expression will be the result of your
function.

The variables will be a list of variables separated by commas that the


function will receive. You will be unable to use keywords or parentheses. If
you use parentheses, your lambda function will fail to function correctly.

Benefits of Python

When it comes time to begin working with a coding language, you will
discover that there is none better than the Python coding language to choose
from. When it comes to working with Python, there are so many advantages
that you will be able to take advantage of that it will not take long for you to
realize why it is the programming language of choice for the majority of
programmers. Let's take a look at some of the advan‐ tages that you will be
able to reap when you work with this type of coding language in more detail.
The first advantage is that this language is intended to be simple to read and
write, which is a major plus. Python, in contrast to some of the other options
that have been around for a long time and are more tradi‐ tional coding
languages, was designed to be simple enough for even complete beginners to
learn. Whatever your previous coding experience has been, whether you
have some knowledge of how to make this all work, or this is the first time
that you have ever done anything with coding, you will find that the Python
programming language is the best choice to use in this situation.

Even though there is a significant learning curve when it comes to working


with the Python programming language, you will discover that this does not
detract from any of the functionality or capabilities that you will be able to
enjoy while using this language. Python is a powerful programming
language, and it frequently has more power than those who are just getting
started with it realize. In addition to allowing you to do some basic coding,
which we will go over in greater detail later in this guidebook, Python comes
with extensions and other features that will assist you in data analysis, data
science, machine learning, and other areas of programming.

Another advantage of Python is the large and active community that it


attracts, which you are likely to appreciate as well. This is a worldwide
community of programmers of all stripes who can be found in different
locations from around the world. You will be able to work with people from
all levels of experience, from complete beginners to professionals who have
been coding for a long time. You will be able to work with people from all
levels of experience, from complete beginners to profes‐ sionals who have
been coding for a long time.
Especially beneficial for those who are just getting started with Python for
the first time is this. This allows you to connect with a large number of other
programmers, many of whom have some coding experience, who can help
you with your questions, show you how to try something new with the
coding that you want to do, and much more besides. This community will be
able to assist you at any point in time if you are having difficulties or want to
learn something new about Python. Python is also referred to as an OOP
(object-oriented programming) programming language. This is good news
for someone who is just getting started because it has a nice logical way of
organizing your code that you are able to use to organize your work. You
will find that doing so will make it much easier for you to store all of your
objects, or parts of code, into the appropriate class, and then everything will
be exactly where you left it when you are finished with the project in
question. This will make more sense when we go over it in greater depth
later, but it is essentially going to make things easier when it comes time to
write the actual program code.

This type of language is also going to be a pleasure to work with because of


all of the libraries that are included with it. The traditional or standard library
that comes with Python is capable of performing a wide range of tasks and
can assist you with some of the more funda‐ mental coding tasks that you
may wish to complete. It is possible, however, that you will need to add
something to Python in order to accomplish something a little more
complicated, such as data analysis or machine learning.

Fortunately, Python already includes the capabilities and extensions that


you'll need to make all of this possible. There is a plethora of data science
and machine learning libraries available, all of which are perfectly
compatible with the Python programming language. Creating the types of
codes that you require with Python, no matter how simple or complex they
may be, becomes easier as a result of this.

As we can see, the Python programming language contains a large number


of different components, and understanding what these compo‐ nents are and
how they work together will be critical when it comes time to begin working
on some of your code. With this in mind, let's take some of the fundamentals
and use them to explore some of the inter‐ esting things that you can do with
the Python programming language.
Utilizing Python programming

There is a big challenge in choosing a programming language that you can


use for your coding businesses. The bigger question is, which language are
you supposed to learn? Python is a program that is easy to use, and there are
known companies that use it. This is one of the reasons why you should
adapt to its uses. This is also the reason why worldwide developers have
taken advantage of its easy availability.

Development of the software

There are numerous applications for Python programming, like machine


learning, data science, and web development. In addition, other several
projects can use Python skills:

With Python programming, you can automate boring stuff; this is the best
approach for beginners. It helps with spreadsheet updates and renaming files.
When you get to master Python basics, then this is the best point to start
with. With the information, you will create dictionar‐ ies, web scraping,
creating objects, and working on files.

Python will help you stay on top of the prices that are set on Bitcoin. Bitcoin
and cryptocurrency have become popular investments; this is because of its
price fluctuation. To know the right move concerning Bitcoin, you will need
to be alert on their prices. With Python, it is possible to create a price
notification for Bitcoin. This is the best way to start on crypto and Python.

When your intention and plan are to create a calculator, Python is the best
programming language. You will be able to build back-end and front-end
services, which are the best for deployment. It is essential to create
applications that users can easily use. If your interest is in UX and UI design,
then Python has a graphical user interface that is easy to work with.

Data analytics is an important concept. It involves peoples’ behavioral


patterns. In this case, Twitter is the best place to start when your interest is in
data analysis to get all the answers. As such, there is a data-mining project
on Twitter, and that is when your Python skills will come in handy. With the
influx of technology and the Internet, it is easy to get data and information
easily, and in this case, Python is the best programming language to use
when mining data from social media programs, such as Twitter.

You will have the ability to create a microblog with Flask. In recent times,
most people have a blog. Again, it is not a bad idea to have your personal
hub online. With Instagram and Twitter, microblogging has become a
popular concept. With Python skills, you will be able to create your
microblog. When you are into web development, you do not need to be
worried about knowing Flask. You can learn about it online and then move
to Django, which helps in web applications on a large scale.

With Python skills, it is possible to build a blockchain. The main reason for
blockchain development was financial technology, even though it is
spreading to other industries. As of now, blockchains can be used for any
type of transaction, like medical records or real estate. When you get to build
one for yourself, you will understand it better. You need to remember that
blockchain is not just for the individuals who are inter‐ ested in crypto.
When you build one, you will have a creative way for technology
implementation to your interest.

You can bottle your Twitter feed with your Python skills, and this will help
in web applications. You can create a simple web app that can help in
navigation on your Twitter feed. You will not be using Flask, but rather
Bottle, a low-dependency approach that is easy and quick to implement.

Some PyGames are easy to play with Python skills. You can use the skills to
code several games and puzzles. With the Pygame library, it is easier to
create your games and develop them. It is an open and free source with
computer graphics and sound libraries, and it helps add up interac‐ tive
functions to the application. Different games can be used for library creation.

Python helps with multiple paradigms that help programmers know what is
relevant in the work environment and requirements. Since Python supports
different paradigms in programming, it is capable of featuring other concepts
that relate to functional programming. With Python, it is possible to develop
a software application that is complicated and large. Python helps in
integrating with different operating systems and inter‐ preting other codes.
There is also a possibility to redevelop this applica‐ tion without
recompiling.

Python can also provide better results than other programming languages
because of its robust and big library. It is possible to select the best from the
library as per the requirements and add more functional‐ ity. The feature will
prevent having any other code writing.

Python helps in simplifying any complicated software. This program‐ ming


language helps in data analytics and visualization in any program that is
developing. When you are familiar with Python, you get to complete
complex solutions without putting in much time.

Implication of Python in Economics

Most people ask if it is important for economists to learn any program‐ ming
language. It is essential since they will use the skills to test and crush data
sets. Most economists use Python as their primary program‐ ming language
to help with efficiency to run complex models. Other professionals, not only
data scientists, use the idea of data analysis. Economists learn how to code to
enjoy the ability to handle bigger data software. Large data deposits can now
be held in spreadsheets when you use the new systems, and all that can be
done in a shorter time. That is the main reason why economists are adapting
to the Python program‐ ming language.

Different people use different sets of big data. It helps in coding for market
and business intelligence. Tech individuals create more spec‐ trums of
solutions, and they are not just for data scientists. For this reason,
economists are using and learning programming languages. Economists have
been adapting to Python at a slower rate since they did not mostly depend on
the data compared to data scientists. They have adapted to the programming
languages because of their flexibility, the breadth of functionalities,
development, speed in computing, and the ability to operate between
different systems.
Economists deal with data that is on both low and high frequencies. This is
because of the increase in digitization and computing. The modern economy
brings about significant power in computing and data sources. Years back,
coding was used for only back office work, unlike recent times when used
for front functions, which is why the use of Python has increased.

Significance of Python at the workplace

Several benefits come with learning Python if you have not learned the
language. There is no need to panic because Python is a program that is easy
to learn and can be used to learn other programming languages. You will
understand the importance of Python since different compa‐ nies adopt it
like Instagram, Disney, Nokia, IBM, Pinterest, and Google. When you learn
about Python, you will have the skills needed to succeed and make good
money.

Python programming language helps develop prototypes, and the reason is


that it is quick to learn and work with. Significantly, most data mining and
automation rely on Python, because it is better for general tasks.

With Python, you will get a better and more productive environment for
coding, unlike what most programming languages like Java and C++ will do.
Most coders claim that they are better organized and more productive with
Python when it comes to their work.

Since Python is not complicated and any beginner can easily read, learn, and
understand, anyone can work with the programming language. All that you
will need is patience and practice to excel with the language. Python helps
most programmers to develop in large-scale dimensions.

How to earn through Python programming

Blogging

Python programming helps in creating a blog, and the blog is used in making
money. There are different types of blogging. You can specialize in
programming as your niche in blogging. There are numerous ways to use
your blog as a programmer. This includes online coding, charging your
premium content, and affiliate links. Ensure all your content is search engine
friendly with the relevant keywords used in ranking your page. In addition,
search engine optimization should be both on and off the page. You will be
guaranteed traffic to the site.

App development

Your programming skills will be beneficial when you develop an app and
monetize it. This programming helps in attaining that. Ensure that you
market your app and use the automatic coding apps that will help in creating
the app in a few minutes. With a great marketing technique, you will be able
to make money out of app development. To sell it, you need to launch it on
the app store.

Freelancing

This is a situation whereby you offer your services online. You should ensure
that you look for the available online platforms and what works for you. You
will be able to work within your own work schedule and make money while
doing that. Some of the genuine and known plat‐ forms include Guru,
Freelancer, and Upwork. You can also pitch directly to clients and offer your
programming services.

Make a plugin with Python

Another alternative is a theme on WordPress. The best way to do it is by


developing many apps and smaller modules like themes and WordPress
plugins. This is a great way to make money coding online. Most websites
use WordPress, so if you can create WordPress plugins, you are assured of
making much money.

Become an online educator

All this is possible when you use your Python skills and do coding. Most
people are adopting online courses where people who cannot attend classes
can still learn. When you have a personal website, you can offer free courses
and tutorials and have traffic. You can teach many students in economics and
finance how to code and use Python skills.

Join coding competitions with Python


You can do development, data science, and design. When you are a winner,
you are paid and get access to big companies on the lookout for competent
coders.

Website creation with Python

You can share your programming tips and then display what you have.
Ensure that your website shows all your skills, your bans, and your port‐
folio as a coder. When you have your brand established, you will get more
clients willing to get your services and consultation, and you can charge for
that. A website can bring your earnings through Google Adsense, affiliate
marketing, and sponsored ads.
THREE

Getting Started with Python


Installing Python

Since we have learned a little more about Python, it's time to look at some of
the steps involved in installing Python on your computer. You want to ensure
that you are able to properly navigate and install this program, as well as that
the correct version is installed on your computer at the appropriate time.
This will make it easier to write some of the necessary code without
encountering too many roadblocks.

Install the interpreter

Before we can begin writing our first Python program, we must first
download the Python interpreter appropriate for our computers. Python 3
will be used in this book because, as stated on the official Python website,
"Python 2.x is legacy; Python 3.x is the language's present and future."
Additionally, "Python 3 eliminates numerous quirks that can unnecessarily
confuse inexperienced programmers."

However, it is worth noting that Python 2 is still quite popular. Python 2


and 3 are approximately 90% identical. Thus, if you learn Python 3, you will
almost certainly have no difficulty understanding Python 2
code.
To download the Python 3 interpreter, navigate to
[Link] At the top of the webpage, the correct
version should be indicated. See the figure below:

Figure 1:

Before any programmer can proceed through the remainder of this book and
begin writing their own Python code, it is necessary to go through various
steps for running Python, which completes installation. Python installation
will vary according to the operating system installed on your computer and
the installation source you choose.

There are a few places where you can obtain information about this
programming language, but we're going to focus on [Link] to
make things easier. We're going to spend some time in this chapter going
over the various steps required to install the Python interpreter and more on
all of the major operating systems.

First, locate the one that is compatible with the operating system on your
computer, and then follow these steps to obtain the desired results and to
install the Python programming language and all of its associ‐ ated software
on your computer..

Utilizing Mac OS X
If you're installing Python on a Mac, you'll notice that the Python 2 version
is already installed, without you having to do anything else. The exact
version of Python 2 installed on your computer will vary depending on the
age of the computer and the operating system version. To determine which
version of Python is currently installed on your computer, open a command
prompt and type "python – V". This will display the Python version that is
currently installed on your Mac operating system.

Additionally, you can now select the Python version that you wish to use.
Many people prefer to work with Python's newest version, Python 3, which
means that you'll need to follow a few steps to get everything set up. This
does not require you to uninstall the Python 2 version that you currently
have. To determine whether your system contains a Python 3 installation,
open the terminal app that we previously used and type "python3 – V".

As mentioned previously, the default behavior of this type of system is that


Python 3 is not installed on the computer at all. If you want to use Python 3
on this type of computer, you must visit the previously mentioned
[Link] and download the installers. This is a good place to start
because it ensures that all of the components necessary for coding are
installed concurrently. This includes the Python shell and interpreter, as well
as any necessary tools and the IDLE.

Notably, to run the IDLE and shell with this language depends on the version
you choose to work with and some of your personal preferences for writing
code. The two commands that will assist you in starting the IDLE and shells
applications, depending on the version of Python that you wish to work with
are as follows:

For Python 2.X, simply type “Idle” For Python 3.X, simply type “idle3”

As mentioned previously, when you download and install Python 3 on the


Mac operating system, you will also need to install the IDLE, which you can
do as a standard application inside of your Applications folder. To begin
using this program from your desktop, simply navigate to the folder, double
click on the IDLE application, and then wait for it to download.
Installing on Windows Operating System
Figure 2:

After finishing our work with the Mac operating system, we'll move on to
the Windows operating system. You might want to try installing Python on
your computer as a test. Because Windows ships with its own programming
language pre-installed, you must manually add Python to use it. This will not
be difficult for you to work with, but you must take it slowly and avoid
rushing through tasks in order to complete them.

Python runs without a hitch on a Windows computer. All that is required is


that you install it on your Windows operating system. However, once
configured, the Python language will be straightforward to use on this type
of operating system, so you won't have to worry about that.

When you're ready to work with Python on Windows, you'll need to go


through and create the environment variables necessary to run Python scripts
from the command prompt. To work with Python on a Windows system,
several steps are required, including the following:

1. To begin, navigate to the Python distribution's official download page and


download the Windows installer. You can either use Python 3's most recent
version or select another option. The installer installs Python in 32-bit mode
by default, but you can switch to 64-bit mode if you wish. While 32-bit is
frequently preferred to ensure compatibility with older packages, you are
free to experiment.

2. Select "Run as Administrator" from the context menu of the installer.


There will be two choices. From the drop-down menu, select "Customize
Installation."

3. On the following screen, check all of the boxes under "Optional Features"
and then click "Continue."
4. Select the directory in which you want Python to be installed under
"Advanced Options." Choose Install. Allow some time for the installer to
complete and then close it.

Next, modify the system's PATH variable to include directories containing


packages and other required components. To do so, follow the steps below:

1. Open the Control Panel. This is done by right-clicking the taskbar and
typing Control Panel. Choose the icon.
2. In the Control Panel, navigate to the Environment tab. Click Edit System
Environment Variables after that. Select the Environment Variables button
from here.
3. Navigate to the section User Variables. You can modify an existing PATH
variable or create a new one.
4. If the system does not already contain a variable named PATH, click on
New to create one. Give the PATH variable a meaningful name and populate
it with the directories you desire. Proceed by closing all Control Panel dialog
boxes.
5. Now, you can open the command prompt. This is accomplished by
selecting the Start Menu, followed by Windows System and finally
Command Prompt. Enter the word "python." This will start the Python
interpreter automatically.

Once you've completed these steps (which are actually quite simple), you'll
be able to open and use the Python programming language on your Windows
system in any way you wish. You can configure the inter‐ preter and other
components to your specifications and then write the code and create the
programs you desire.

Fundamentals of Python interpreter

The Python interpreter is the next item that requires attention. Python's
standard installation, which you can download from [Link], comes
with everything you need to get started. It will include documen‐ tation,
licensing information, and the files necessary to run any Python script. These
three files will contain the shell, the interpreter, and the IDLE.
To begin, let us take a look at the Python interpreter. This is critical because
it is the section that executes the code you specify. The inter‐ preter is
capable of converting the instructions you write into codes. It will then
process these to generate the desired content for display on the screen.

Interpreters and compilers

Python is basically an interpreter language but also offers compiler options


for large programs. It highlights the versatility of the language once again. In
all high-level languages, the programs are either inter‐ preted or compiled
for the computer to understand what needs to be done. In interpreters, each
line of code is translated to machine language and executed as soon as it’s
entered. Interpreter languages are useful for testing and learning. An
example of such language is Ruby.

In compilers, the entire program is converted to machine language called


object code and saved for future executions. If the original program isn’t
changed, the compiler ignores the conversion step and executes the object
code, which makes the process faster. This technique is good for large
software that strains available resources. An example of this language is C.

Utilization of a text editor

Python programming can be accomplished using virtually any plain text


editor. You can use programs such as Notepad, Notepad++, and gedit. Bear
in mind that several of these text editors include a variety of useful features
for programmers. For instance, some of them, such as Notepad++, include
syntax highlighting, which highlights any errors you make instantly.

If you type code in a simple editor such as plain Notepad, the program will
not notify you if you omit a semicolon or if you add extra space. There are
numerous programs available; therefore, select an editor with which you are
comfortable. Avoid using word processors such as Microsoft Word or
OpenOffice in light of this. They are unsuitable for use in programming.

Installing a text editor

Sublime Text is a basic text editor: easy to install on OS X, allowing you to


execute nearly all of your programs directly from the editor rather than from
a terminal, use syntax highlights to paint your file, and running your file in a
terminal session inserted in the Sublime Text window to make the display
easy to see. Appendix B contains informa‐ tion about the other text editors,
but unless you have a good reason to use a different editor, I recommend
using Sublime Text A. Sublime Text app is available for free from
http:/[Link]/3. Click on the download link and look for an OS X
installer. Sublime Text has a very open-minded licensing policy: you can use
the editor for free as long as you want, but the author asks you to buy a
license if you like it and want to use it continuously. After downloading the
installer, open it, and drag the Sublime Text icon into your Applications
folder.

Python IDLE

After that, we'll work on the Python IDLE. IDLE stands for Interdisciplinary
Development and Learning Environment. It is in charge of storing all of the
various tools required to create programs in Python. Within this IDLE, you'll
find all of the tools necessary to debug the code, the text editor, and even the
shell. Depending on which Python version you choose, you can work with a
simple IDLE or a more comprehensive one.

There is a version of the IDLE that comes with the downloaded Python, but
you can also use some third-party ones. You can find a new text editor and
IDLE that better suit your needs, but the basic one that comes with your
Python download will suffice if you're not in the mood to switch.

Using an IDE

Numerous IDEs even include suggestions for resolving an error. There are
numerous IDEs available, but one of the most popular is IDLE. It is included
in the same package as Python, so no additional steps are required. Bear in
mind that it has two modes of operation: interactive and scripted. If you want
Python to respond immediately to whatever commands you type, use
interactive.

They can be used to write code; however, when they are saved, the program
automatically inserts some additional lines of code. This code is processor-
specific, and it may slow down or, in the worst-case scenario, prevent your
program from running entirely.

Finally, we should familiarize ourselves with the Python Shell. This is an


interactive command line driving interface that will be available within the
interpreter. This one will be in charge of retaining the commands that you go
through and write out. It will then go through and execute all of the code that
you intend to write. If you discover that the code is unintelligible, you will
receive an error message and will need to go through and resolve the issue.

Each of these three components of the code will be critical when it comes to
writing the codes you wish to use. When you work with the [Link]
installation, all three of these points will be installed automatically; you will
not need to do anything else. If you downloaded Python from a source other
than that website, you must double-check the files and determine whether
you need to download those three components separately to get the code to
work.
FOUR

The Python Syntax


Syntax is the set of rules that governs how to write code in a program‐ ming
language. Just like real-life languages, it’s essential to follow the specific
syntax to avoid unexpected results. On the other hand, syntax is a collection
of rules that define the proper structure and order of words and symbols in a
programming language. The syntax and conventions used in Python 3 are
listed below.

Python keywords

Python has 33 built-in functions and processes. You must be aware of these
keywords and refrain from using them as program identifiers.
Identifier naming conventions

An identifier is a unique name assigned to a variable, string, dictionary, list,


class, module, or function in Python. Each object type has its own unique
naming convention.

An identifier may be composed of a single letter or a combination of


uppercase and lowercase letters, underscores, or the digits 0 to 9.
Examples of identifiers

X
x
my_dict
my_list9
UPPERCASE
lowercase
UPPERCASE_WITH_UNDERSCORES lowercase_with_underscores
CamelCase or CapWords
mixedCase

While you should avoid using keywords as identifiers, if you absolutely


must, you can distinguish them from keywords by using a trailing
underscore.

This is preferable to abbreviation or corrupted words.


For example : global_, class_

Identifiers should not contain symbols or special characters such as #, $, %,


and @.
Identifiers may end in a number but should never start with a number. For
example, var_1 is valid but 1var is not.
A multiple-word identifier is acceptable but separating each unit with an
underscore will make it more readable.
For example, my_main_function is more preferred over mymain‐ function.

You can use the following style guide when naming specific identifiers.
Global variables
Names of global variables are written in lowercase. If there are two or more
words in an identifier, they are preferably separated by an under‐ score for
clarity and readability.

Classes

The UpperCaseCamelCase convention is used when naming a class. That is,


the identifier should start with an uppercase letter. If there are two or more
words in a class identifier, they all start in a capital letter and are joined
together. For example: Employees, MyCamelCase, TheFamousList, Cars,
MyCar.

Variables by instance

When naming instance variables that contain two or more words, an


underscore should be used to separate them. They should be capitalized.

Examples: student_one, member_status, employee.


Functions

A function name should be written in lowercase. Multiple-word function


names should be separated by an underscore for better readability.

Examples: multiplier, adder, sub_function


Arguments

Arguments must consist of letters in lowercase. The word “self ” is always


the first argument in instance methods while “cls” is the first argument in
class methods.

Modules and packages

Module identifiers should be in lowercase and are usually written as a short


single-word name. Using multiple words is discouraged but you may do so
to facilitate clarity and readability. A single underscore should separate each
unit in a module and package identifier consisting of two or more words.

Constants
Constants are written in uppercase letters and separated by an under‐ score if
the name consists of multiple words.
Examples: TOTAL, MAX_OVERFLOW
Quotation Marks

Quotation marks are used to indicate strings. You may use single (‘), double
(“), or triple (‘“) quotes but you must use the same mark to start and end
string literals.

Examples:
‘status’, “Johnny”, ‘“age limit:”’, ‘Enter a vowel:’
Indentation

Python structures programs or blocks of code using indentation or white


spaces. Curly braces {} will not be used to denote a group of related
statements. Instead, you'll use equal indentation to denote a block of code.
As a result, Python programs appear tidy, uncluttered, organized, and
readable. By indenting a block further to the right, a nested block is created.

While tabs can be used to indent code, Python programmers frequently use
four white spaces to indicate the beginning of a block of code. This is a
language convention worth considering for consistency's sake. It is not
mandatory, however, and you may substitute tabs. Simply ensure that all
lines within a code block are consistently indented if you want your program
to run correctly. When using the built-in text editor, you'll notice that it
automatically inserts four white spaces whenever the most recently typed
statement requires it.

Here is a snippet of a program that will give you an idea of how Python
programs are structured:

def Vehicle_Rental(days): rate = 15 * days if days >= 15: rate -= 20 elif days
>= 7: rate -= 5 return fees

Statements

Statements are a type of expression that can be entered at the Python prompt
or written within a program and are read and executed by the interpreter.
Python supports the following statements: if, for, while, break, and
assignment statements.
Multiple-Line Statements

Certain statements may span multiple lines of code. By enclosing the


statements in parentheses (), curly braces {}, or square brackets [), you can
implicitly indicate to Python that the lines are related and form a single
statement.

For instance, the assignment statement below creates a list and requires three
lines of code. The items are enclosed in square brackets, indi‐ cating that
they are part of a list and are contained within a single statement.

>>> my_collection = ['stamps', 'stationery', 'pens', 'compact discs', 'boxes',


'watches', 'metallic toy cars', 'numismatic coins', 'paintings', 'newspaper
clippings', 'books']

You may also indicate continuation explicitly by using a backslash \ at the


end of each line of related statements. For example:

my_alphabet = 'a', 'b', 'c', 'd','e', 'f', 'g', 'h', 'i' \ 'j', 'k', 'l' 'm', 'n', 'o', 'p', 'q', 'r' \ 's',
't', 'u','v', 'w', 'x', 'y', 'z'

Documentation string

A docstring, short for documentation string, is used to provide informa‐ tion


on what a class or a function does. Docstrings are typically found at the top
of a code block that defines a class, function, method, or module.

By convention, a docstring starts with a one-line imperative phrase that


begins in a capital letter and ends with a period. It may stretch over multiple
lines and is enclosed in triple-double quotes ("""). Here are examples of a
docstring:

def adder(x, y): """Function to get the sum of two numbers.""" return x + y
class Doc(obj): """ Explain function docstring.

A function name is introduced by the keyword def. Function definition


statements end in a colon and are followed immediately by a docstring in
triple double-quotes. The function body is distinguished by the white spaces
right after the definition statement and docstring.
Comments

Comments are notes written inside programs. They are intended to provide
documentation about the programming steps, processes, and other
information that a programmer may consider important. Comments are
useful when evaluating a program. They facilitate a smooth evaluation and
transition between programmers. A hash # symbol is used to introduce a
comment. It tells Python to ignore the line and proceed to the execution of
the next statement.
For example:

#print a birthday greeting print('Happy Birthday, Member!')


Comments may stretch over multiple lines. You may use a hash # symbol at
the start of each line to wrap the lines together.
Example:

#This step is important # because it is the basis # of succeeding processes.

Another way to wrap long multiple-line comments is by using triple quotes


at the beginning and end of the comment.
For example:

"""This is another way to write comments that span several lines."""

In summary, the Python syntax is a list of rules that explicitly define how
Python code should be written. The syntax is a little different from other
programming languages because it allows the programmer to use whitespace
to add structure and clarity.
FIVE

Functions and Modules


Functions are critical in any programming language because they help divide
a large program into manageable sections. Functions are still necessary if
throughout keyword def followed by the function's name and parentheses.
Within these parentheses, any input arguments or parameters should be
enclosed. However, you can define parameters within these parentheses. you
find yourself writing the same code multiple times
your program. Python function blocks begin with the

Why are functions required?

In computer programs, functions control the inputs and outputs. The purpose
of programming languages is to work with data, and functions are the best
way to convert this type of data.

A function, in particular, is the program's main code. Each function is


logically related to the main code. However, if a function has not been
defined previously, you must define it before using it. Thus, functions can be
thought of as tasks that a user wishes to perform. Defining a function once
with a name enables the functionality to be reused without making the main
program appear frightening. This rapidly eliminates lines of code and
simplifies debugging.
This will become clearer later, but for now, keep in mind that the reason you
use a function is for its reusability. The fact that complex operations can be
compiled into single tasks that can be executed with a single call explains
why computer codes are more readable.

Each programming language enables you to create and use functions to


perform multiple tasks with a single call. In this view, you can make
numerous calls without having to worry about logically structuring the code
into the main code.

Functions in Python

Python functions are an excellent demonstration of reusability. This enables


the server to support a broad range of applications, from web development to
testing. The Python interpreter includes a variety of functions. Additionally,
you can always incorporate additional libraries into your program that
include predefined functions.

All you need to do is download the necessary packages and import them into
your code to provide the necessary functionality. As a result, once defined, a
function can be used multiple times throughout the code. Python adheres to
the DRY principle of software engineering. This principle emphasizes the
importance of abstracting any repetition of software patterns in order to
avoid redundancy and ensure that they can be used freely without revealing
their implementation details.

DRY stands for Don't Repeat Yourself, and this feature of re-usable blocks of
code is critical for Python's abstraction to work. Thus, to apply a function, all
that is required is its name, its arguments, and its purpose if it accepts any, as
well as the type of results if it returns any.

It's similar to operating an automobile or a telephone, where you don't need


to understand how their components work to operate them. It is pre-built to
provide common purposes that you can immediately use to accomplish your
objectives while devoting your time to implementing all of your application
program's innovative features. And no one cares about the inner workings of
a function as long as it performs its function.
Thus, unless you want to create a new function or modify an existing one,
you don't need to understand anything about how Python works on the inside
if it works the way you need it to. It's similar to driving a car; you'll need to
understand how it works before you can build or repair one. Alternatively,
once you've created a working function, you can reuse it indefinitely without
ever having to inspect its contents. You can invoke a function as part of a
program that is written once and can be executed whenever the program
requires it. This enables the code to be reused.

A function is a subprogram that performs operations on data and outputs


results. To define a Python function, precede its name with the "def"
keyword and append parentheses to its end, followed by a colon (:). Python
uses indentation to indicate blocks rather than brackets, which improves
code readability.

In Python, a function may have a variable number of parameters or none at


all. As a result, when your function is required to work with variables from
other blocks of code or your main program, it may require a different
number of parameters and generate different results.

A Python function may or may not return a value. The value can be derived
from the execution of the function or it can be an expression or value that
you emphasize following the keyword "return." And when a return statement
is executed, the program's flow returns to the state immediately preceding
the function call and continues execution from there. Thus, to invoke a
Python function at any point in your code, all you need to do is specify its
name and any arguments in parentheses.

Defining a function follows the same rules as naming a variable. It begins


with a letter from A to Z, a-z in both lower and upper case, or a period (.).
The remainder of the name contains underscores (_), digits (0-9), and
lowercase or uppercase letters.

1. It is possible that a reserved keyword will not be chosen as an identifier.


2. Appropriate grammar usage to increase the readability of the code.
It is proper to name a Python function after the task it performs. Add a
docstring to the function declaration's first line. It is a documentation string
that describes the functionality of the function.

Fundamentals of functions

The def statement is used to define functions in Python. This statement is


terminated by a colon, and the code within the function is indented
immediately below the def statement.

Example:

Consider this program in greater detail. The following program's final


section of code contains a function call. Functions are critical because they
enable you to avoid writing the same code repeatedly.
If you want to draw a box of stars in your program, you can use a Python
function. Instead of typing multiple lines of redundant code whenever you
want a box, you simply insert the function to draw the box. The function is
as:

The advantage this brings is if you want to alter the size of the box, you only
need to alter the code inside the function. On the other hand, if you try to
copy and paste the box code everywhere, then you will be required to change
every place you paste it.

Arguments
In most programming languages, one can pass values to functions. For
example:

When the print_hello function is invoked with the value 3, the value of the
variable n is retained in the result. From within the function's code, you can
reference this variable as needed. Therefore, if you are programming in
Python, you can pass a different value to the same function at different
times.

Obtaining and returning values

Programming is a fascinating subject to learn, particularly when it comes to


writing functions. It is possible to write functions that return a result after the
computation is completed, in addition to functions that accept values as
input.

The following is an example of how to convert a temperature from Celsius


to Fahrenheit.
The return statement in this program is used to send the result of a function
computation back to the caller of the function. Keep in mind that the
function does not produce any output at all. The printing takes place outside
of the function's scope.

As a result, you can compute the math and come up with the following
result:

Python's math module includes trig functions, but the functions only work in
radians, rather than degrees. Here is an example of a sine func‐ tion that can
be used in degrees.

In a
nutshell, a function can still return a list of values if it returns more than one
value.
Categories of Python functions

There are many categories of Python functions, and each of the func‐ tions is
unique. Different categories of Python functions include (I) Inbuilt, (II)
Lambda, (III), User-defined, and (IV) Recursion Functions.

In-built Python functions

The Python interpreter has different functions available to use. These


functions are referred to as built-in functions. For instance, the print ()
function will display the object to the standard output device or the text
stream file.

Python 3.6 has 68 built-in functions. For purposes of simplicity, let us look
at the main functions used, and we can start on from there. Python abs ()
function
This function will return the absolute value of any number entered.
Therefore, if the number is complex, abs () displays a magnitude. Syntax
The general syntax of the abs () function is:
Abs (num)

Parameters
The abs () function accepts a single argument:

Num-This is a number whose complete value should be returned. This


number can be:

Integer
Complex number Floating number
Example:

Python all () function


The all () function will output True if all elements in a specific iterable are
true. If not, it will display False.
Syntax
The syntax of all () method is:
all (iterable)

Parameters
The all () method accepts a single parameter:

Iterable- Any iterable (tuple, list, dictionary, etc.) which has the
elements.

Python () ascii function


This is a function that displays characters in ascending order.

When this method is invoked, it will return a string containing a print‐ able
representation of the object. It uses the u, x, and U escapes to skip over the
non-ASCII characters contained within the string.

Syntax
The asci () method has the following syntax:
ascii (object)
Parameters
The asci method accepts a variety of objects, including lists and strings,
among others.
Bin () Python function
The bin function converts an integer to a binary string and returns the binary
string of that integer. In the event that the parameter is not an integer, the
_index_ () method must be called in order to run an integer.

The bin () method has the following syntax: bin (num)

The bin () method only accepts one parameter, a numeral. This is an integer
number for which the binary equivalent must be determined. If the value is
not an integer, the _index_ () method must be called in order to produce an
integer.

The bool () function in Python

The bool () method will change the value of an integer and return the binary
string that represents that integer. If the parameter is not an inte‐ ger, the
__index__ () function must be executed in order to display an integer.

The following is the syntax for the bool () method:


Bool([value])
Parameters

It is not required to pass a value to the bool function (). In the absence of a
value, the bool () function returns the value False. In general, the bool ()
function only accepts a single parameter value.

Python recursive functions

In Python programming, a function can reference another function. Also,


functions don’t have to be called by other functions, but instead it can call
itself.

An example of a recursive function is one to find the factorial of numbers. 6


factorial means 1*2*3*4*5*6= 720.
Example:
In this example, calc_factorial () is a recursive function. Recursion Merits

A recursive function improves the appearance of code. The code looks


elegant and clean.
A difficult problem is divided into small parts using recursion.

Drawbacks of recursion
Recursive calls consume a lot of time and memory. Sometimes the logic of
recursion is difficult to follow.
Python lambda functions

Lambda Functions are a type of function in Python. An anonymous function


is a function that does not have a name assigned to it. Anony‐ mous is
denoted by the keyword lambda.

The following is the syntax for the Python lambda function: Lambda
arguments: expression
Syntax
Python modules

Modules consist of definitions as well as program statements. An illus‐


tration is a file name [Link] that is considered as a module. The module
name would be config. Modules are used to help break large programs into
smaller manageable and organized files as well as promoting reusability of
code.

Example
Creating the First module
Def add(x, y): “””This is a program to add two numbers and return the
outcome"""

outcome=x+y
return outcome
Module Import

The keyword import is used to import.

Example
Import first

The dot operator can help us access a function as long as we know the name
of the module.

Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:

[Link](6,8)
Import Statement in Python
The import statement can be used to access the definitions within a module
via the dot operator.

Start IDLE.
Navigate to the File menu and click New Window.
Type the following:

import math print("The PI value is", [Link]) Import with renaming

Example Start IDLE. Navigate to the File menu and click New Window.
Type the following:

import math as h print(“The PI value is-“,[Link])


Explanation

In this case, h is our renamed math module with a view helping save typing
time in some instances. When we rename, the new name becomes a valid
and recognized one and not the original one.

From…import statement Python.


It is possible to import particular names from a module rather than importing
the entire module.

Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:

from math import pi print("The PI value is-", pi)

Importing All Names


Example
Start IDLE.
Navigate to the File menu and click New Window. Type the following:

from math import* print("The PI value is-", pi)


Explanation
In this context, we are importing all definitions from a particular module, but
it is an encouraged norm as it can lead to unseen duplicates.

Module Search Path in Python


Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:

import sys [Link]


Python searches everywhere, including the sys file.
Reloading a Module
Python will only import a module once, increasing efficiency in execution.
print(“This program was executed”) import mine Reloading Code

Example
Start IDLE.
Navigate to the File menu and click New Window. Type the following:

import mine import mine import mine [Link](mine) Dir() built-in


Python function

For discovering names contained in a module, we use the dir() inbuilt


function.
Syntax
dir(module_name)
Python package

Files in Python hold modules and directories are stored in packages. A single
package in Python holds similar modules. Therefore, different modules
should be placed in different Python packages.

In summary, the concepts explored in this chapter should help you develop
your own Python functions by adding operability and function‐ ality to the
same. This will be useful when you try to build an applica‐ tion by
simplifying the process and making it suitable for your personal needs. Now,
you need to be able to use Python functions to create applications easily.
SIX
Expressions in Python
Expressions

Expressions are the most basic building blocks of computer program‐ ming.
They describe a change to a value or set of values in a program. For
example, the expression + 5 represents placing 5 after the + sign; this would
yield 10. Expressions also include mathematical operations and conditional
statements in python. Mathematical operations include addition, subtraction,
multiplication, and division. Conditional state‐ ments pass the value of a
given expression to a function or another expression depending on the
outcome of a comparison.

Python also includes expressions that are more complex: functions, tuples,
lists, dictionaries, and sets. They all describe configurations in the Python
programming language. They are used to demonstrate the flexi‐ bility and
power of Python.

Expressions are used to define values and then to store, manipulate, or


transform these values in a program. Expressions can be grouped into
arithmetic expressions and logical expressions. Arithmetic expression is used
to calculate a sum, product, or difference of two values. Logical expressions
are used to check whether values are true or false (True/False) and if it is
true then do something else, while if it is false do something else.

Python has many built-in functions and mathematical operations that can be
used to express expressions. Functions are used to perform math‐ ematical
operations on numbers, strings, or other values. For example, the function
"sqrt" (square root) calculates the value of a given number by finding the
square root of that number.

Similarly, operators are distinct symbols that compute or combine values


from various computations. The values that an operator manipulates are
referred to as operands. An expression is a collection of operands and
operators, such as 20 + 5 – 5. Python includes a large number of operators
for concentrating data objects into expressions.
Operators are arithmetic, logical, and relational symbols that are primarily
used to estimate an expression that is a number, but becomes a joint value or
a complex number when it is a letter, as discussed previ‐ ously. Operators are
functional expressions denoted by symbols like (+,
-, /, and others). Operators require some data to work with, referred to as
operands. For instance, 2 + 6 (the plus sign is an operator, while the 2 and 3
are operands, and the summation of all is called an expression).

Expressions carry out specific operations and are a representation of value


that utilize an operator and one or two operands. An operand can be a
constant, a variable, or the result of a function.

Operators and their application

Apart from the operators mentioned previously, I will briefly discuss


additional operators and their applications. You can analyze and comprehend
various operators; for example, to evaluate the expression 15 + 5, use the
interactive Python interpreter prompt or the "Visual Studio Code text editor."

A symbol that acts on one or more operands is known as an operator. The


operand is a value or vector on which the operation is performed. Consider
the example 6+9. The operands are 6 and 9, and the operator is +. Python has
a number of operators, which are listed below:

Arithmetic Operators Assignment Operators Comparison Operators Logical


Operators
Membership Operators Bitwise Operators
Identity Operators

Arithmetic operator

Basic mathematical operations are performed using the Python Arith‐ metic
operators. The following is a list of arithmetic operators. Assume x and y are
two variables with values of 30 and 10, respectively, and the following is the
product of the operation:
Assignment
operators

When the assignment operator is used, the value of the right operand is
assigned to the value of the left operand. There are several different
assignments listed below. In the case of x = 20 and y = 10, the following
results are:
Comparison
operators

Python has a number of comparison operators that are frequently used to


compare the values of two operands. The following are some exam‐ ples.
This comparison produces a Boolean value of true or false when the two
values are compared. The following table contains a list of the operators.
The coordinates x=10 and y=15 have been assigned.
In the conditional statement, three logical operators are used: and, or, and
not. These three operators are, in fact, essential to our ability to think
critically about how we reason using the Python language of logic.
Membership
operators

Using membership operators, you can find out whether or not a given
element belongs to an ordered collection of elements such as a string, list, or
tuple. There are two membership operators listed in the following table:

Bitwise operators

Bitwise operators are used to perform binary operations on operands that are
carried out bit by bit. Pretend you're in the following situation: a and b are
both assigned numerical values of 5, and a and b are both assigned numerical
values of 6.a = 5.

b = 6 binary (a) = 0101 binary (b) = 0110 Hence a&b = 0100 is equivalent to
4 a|b=0111

For example: SEVEN

Strings, Numeric Data, Booleans, and Variables


In Python, a string is a collection of characters stored in a list. In contrast to
other languages such as C, Python does not support a char data object that is
a character singleton. A character singleton is essen‐ tially a string of a single
character in Python. In Python, strings are immutable. In other words, once a
string variable is defined, its size cannot be changed. As previously stated, a
string is a list of characters that are saved in an orderly fashion from left to
right. Because each character in a string is stored in a list, it can be accessed
by position.

For the purposes of Python and other programming languages, any text value
that we may use is referred to as a string. For example, names, places, and
sentences are all considered strings. In contrast to words or letters, a string is
a collection of characters that is denoted by the use of single or double
quotation marks to denote their separation. To display a string, use the print
command, followed by a parenthesis, a quotation mark, and whatever you
want to write in the text box.

When we're finished, we'll usually close the brackets and end the quota‐ tion
marks. The IntelliSense feature in PyCharm detects what we are about to do
and delivers the rest of what we need to complete the task right away. When
you only type in the opening bracket, you may have noticed that it
automatically jumps to the rescue.

It will automatically provide you with a way to close the window for you. In
the same way, if you use one or two quotation marks, it will automati‐ cally
provide the closing one for you. See why we are using PyCharm?

There is a reason we use these; let me explain by using the example below:
print(‘I’m afraid I won’t be able to make it’) print(“He said “Why do you
care?”)
Try and run this through PyCharm.
Remember, to run, simply click on the green play-like button on the top right
side of the interface.

right side of the interface. 32\[Link]"


"C:/Users/Programmer/PycharmProjects/PFB/[Link]"

File "C:/Users/Programmer/PycharmProjects/PFB/[Link]", line 1


print('I'm sorry I won't make it today') SyntaxError: invalid syntax
Process finished with exit code 1 Here’s a hint: That’s an error!
So what happened here? Try and revisit the inputs. See how we started the
first print statement with a single quote? Immediately, we ended the quote
using another quotation mark.
The program only accepted the letter ‘I’ as a string.

The color of each character from ‘m' to ‘won' may have changed slightly,
and the program may have detected yet another quotation mark and accepted
the rest of the string as another string after that. To be completely honest, it's
a bit confusing.

Additionally, the same thing occurred in the second statement. The program
recognized double quotation marks and interpreted it as a string, up until the
point where the second instance of double quotation marks appeared in the
string.

In that case, the program didn't even bother to check whether it was a
sentence or whether the conversation was still going on. However,
computers do not comprehend the language of English and instead
understand binary communications. When we press the run button, the
compiler is the program that begins to run. It compiles and interprets our
code, converting it into a series of ones and zeros that the computer can
understand and perform the task we have asked it to perform.

This is precisely why, the second it detects the first quotation mark, it treats
it as the beginning of a string, and it terminates the string imme‐ diately
when it detects the second quotation mark, even if the sentence was
continuing.

To get around this problem, we use a combination of single and double


quotes when we know we will need to use one of these types of quota‐ tion
marks within the sentence. Replace the opening and closing quota‐ tion
marks in the first state with double quotation marks on both ends to see if
you can get away with it. Similarly, for the second statement, replace the
double quotation marks with single quotation marks as shown here:

print("I'm sorry I won't make it today") print('He said "Why do mind?"')


Now the output should look like this:
I'm sorry I won't make it today He said "Why do mind?"
Finally, when it comes to strings, the naming convention does not apply to
the text contained within the string. Regular English writing methods and
conventions are acceptable as long as they are contained within the quotation
marks; otherwise, there is no problem. In the first place, anything outside of
the box will not be a string, and it will or may not work if you change the
case.

Numeric data type

Python has a good understanding of numerical representations. The numbers


are divided into two groups of two each: Individual whole numbers that are
represented without the use of decimal points are referred to as integers. On
the other hand, Real numbers with decimal point representation are
represented as floating point numbers (floats). This means that if you were to
use the numbers 100 and 100.00, one would be considered an integer and the
other would be considered a float, respectively. So what is the point of using
two different number representations?

Assuming you are designing a small game in which the character has a life
of 10, you might want to keep the program in such a way that whenever the
character takes a hit, his or her life is reduced by one or two points. Float
numbers, on the other hand, may be required in order to make things a little
more precise. Now, the damage dealt by each hit may differ and may deduct
1.5, 2.1, or 1.8 points from the player's total life. When we use floats, we can
achieve higher levels of precision, which is especially useful when
performing calculations. When it comes to accuracy, integers are fine if you
aren't too concerned about it or if your programming involves only whole
numbers.

Booleans in Python

Bool is a data type that can only operate on and return two values: true or
false. It is also known as the Boolean data type. Booleans are an essential
part of any program, with the exception of those in which they may never be
required, such as our first program. These are the ones that allow programs
to take different paths depending on whether the result is true or false.
Here's an illustration of what I mean. Consider the following scenario: you
are traveling to a country you have never visited before. There are two
options that you are most likely to be presented with. If it's going to be cold,
you'll be packing your winter clothes as well. Depending on how hot it is
going to be, you will be packing clothes that are appro‐ priate for the heat.
Isn't it straightforward? That is precisely how the Booleans function. We'll
also look into the coding aspect of it as a result of this. For the time being,
just keep in mind that when it comes to true and false, you are dealing with a
bool value.

Variables

A variable is typically a reserved memory to a saved value on your machine.


According to the data type to be stored in a variable, a Python interpreter
will allocate memory to save the variable. In Python, vari‐ ables do not have
to be explicitly declared before they are used. In other words, you don’t need
to define the type or size of any variable before it is used in Python.

Basically, Python does not allocate any memory for variables prior to their
use. Variables are defined and memory is allocated instantaneously when the
variable is used. In Python, variables are objects that can be a number, string,
list, dictionary, tuple, or a file. We will explain in detail each data object type
in the next chapter. For the sake of simplicity and to explain variables and
how to declare and manipulate them in this chapter, we will consider the
basic data object number and strings. A number object type can be, for
instance, an integer or a decimal.

To store data, we require containers. We then need to reserve a certain


amount of memory where we can store this data for processing. Python
offers this container in the form of variables that can be used for storing
data. We can think of a variable as a name given to an object. Using it, we
can refer to that object inside the program environment whenever we want.

The variables can hold data of any type— a number, a string, floating
numbers, Boolean values, or characters. We will be learning about these data
types in the following section.

Assigning values to variables


We use the assignment operator (=) to assign values to variables. As
discussed in Chapter 1, one of Python's distinguishing characteristics is that
it is dynamically typed. Thus, in order to assign values to variables, we do
not need to explicitly declare them with a data type (as is required in other
programming languages such as C, C++, or Java). The inter‐ preter
determines the variable's data type automatically during execution.

You have the passengers, but you do not have a mode of commuting; they
will have nowhere to go. These passengers would just be folks standing
around, waiting for some kind of transportation to pick them up. Similarly,
data types cannot function alone. They need to be stored in these vehicles.
These special vehicles, or as we programmers refer to as containers, are
called ‘variables,’ and they are the elements that perform the magic for us.

Variables are specialized containers that store a specific value in them and
can then be accessed, called, modified, or even removed when the need
arises. Every variable that you may create will hold a specific type of data in
them. You cannot add more than one type of data within a variable. In other
programming languages, you will find that in order to create a variable, you
need to use the keyword ‘var’ followed by an equals mark ‘=’ and then the
value. In Python, it is a lot easier, as shown below:

name = "Mark" age = 34


weight = 133.80 is_married = True

In the above, we have created a variable named ‘name’ and given it a value
of characters. If you recall strings, we have used double quotation marks to
let the program know that this is a string. We then created a variable called
age. Here, we simply wrote 34, which is an integer as there are no decimal
figures following that. You do not need to use quotation marks here at all.

Next, we created a variable ‘weight’ and assigned it a float value. Finally, we


created a variable called ‘is_married’ and assigned it a ‘True’ bool value. If
you were to change the ‘T’ to ‘t’, the system will not recognize it as a bool
and will end up giving an error. Focus on how we used the naming
convention for the last variable. We will be ensuring that our variables
follow the same naming convention.
You can even create blank variables if you feel like you may need these at a
later point in time, or wish to initiate them at no value at the start of the
application. For variables with numeric values, you can create a variable
with a name of your choosing and assign it a value of zero. Alternatively,
you can create an empty string as well by using opening and closing
quotation marks only.

empty_variable1 = 0 empty_variable2 = ""

You do not have to necessarily name them like this; you can come up with
more meaningful names so that you and any other programmer who may
read your code would understand. I have given them these names to ensure
anyone can immediately understand their purpose. Now we have learned
how to create variables, let’s learn how to call them. What’s the point of
having these variables if we are never going to use them, right? Let’s create
a new set of variables.

Have a look here:

name = "Joel" age = 44 height_in_cm = 162 occupation = "Programmer"

I do encourage you to use your own values and play around with vari‐ ables
if you like. In order for us to call the name variable, we simply need to type
the name of the variable. In order to print that to the console, we will do this:

print(name) Jack

The same goes for age, the height variable, and occupation. But what if we
wanted to print them together and not separately? Try running the code
below and see what happens:

print(name age height_in_cm occupation) SyntaxError: invalid syntax

Surprised? Did you end up with this? Here is the reason why that happened.
When you were using a single variable, the program knew what variable that
was. The minute you added a second, a third, and a fourth variable, it tried to
look for something that was written in that manner. Since there wasn’t any, it
returned with an error that otherwise says: “Umm… Are you sure, sir? I tried
looking everywhere, but I couldn’t find this ‘name age height_in_cm
occupation’ element anywhere.” All you need to do is add a comma to act as
a separator like so:

print(name, age, height_in_cm, occupation) Jones 44, 162, Programmer

And now, it knew what we were talking about. The system recalled these
variables and was successfully able to show us what their values were. But
what happens if you try to add two strings together? What if you wish to
merge two separate strings and create a third-string as a result?

first_name = “Joel” last_name = “Luke”

To join these two strings into one, we can use the + sign. The resulting string
will now be called a String Object, and since this is Python we are dealing
with, everything within this language is considered as an object, thus the
Object-Oriented Programming nature.

first_name = "Joel" last_name = "Luke" first_name + last_name

Here, we did not ask the program to print the two strings. If you wish to print
these two instead, simply add the print function and type in the string
variables with a + sign in the middle within parentheses. Sounds good, but
the result will not be quite what you expect:

first_name = "Joel" last_name = "Luke" print(first_name + last_name)


JoelLuke

Why do you think that happened? Certainly, we did use a space between the
two variables. The problem is that the two strings have combined together,
quite literally here, and we did not provide a white space (blank space) after
John or before Wick; it will not include that. Even the white space can be a
part of a string.

To test it out, add one character of space within the first line of code by
tapping on the friendly spacebar after John. Now try running the same
command again, and you should see “John Wick” as your result. The process
of merging two strings is called concatenation. While you can concatenate as
many strings as you like, you cannot concatenate a string and an integer
together.
If you really need to do that, you will need to use another technique to
convert the integer into a string first and then concatenate the same. To
convert an integer, we use the str() function.

text1 = "Zero is equal to” text2 = 0 print(text1 + str(text2)) Zero is equal to 0

Python reads the codes in a line-by-line method. First, it will read the first
line, then the second, then third, and so on. This means we can do a few
things beforehand as well, to save some time for ourselves.

text1 = "Zero is still equal to " text2 = str(0) print(text1 + text2) Zero is still
equal to 0

You may wish to remember this as we will be re-visiting the conversion of


values into strings a lot sooner than you might expect. There is one more
way through which you can print out both string variables and numeric
variables, all at the same time, without the need for + signs or conversion.
This way is called String Formatting. To create a formatted string, we follow
a simple process as shown here:

print(f ”This is where {var 1} will be. Then {var 2}, then {var 3} and so
on”)
Var 1, 2, and 3 are variables.

You can have as many as you like here. Notice the importance of white‐
space. Try not to use the spacebar as much. You might struggle at the start
but will eventually get the hang of it. When we start the string, we place the
character ‘f ’ to let Python know that this is a formatted string. Here, the
curly brackets are performing a part of placeholders. Within these curly
brackets, you can recall your variables. One set of curly brackets will be a
placeholder for each variable that you would like to call upon. To put this in
practical terms, let’s look at an example:

show = "SLY" name1 = "Mazden" name2 = "Joe" name3 = "Helene" seasons


=5

print(f"The show called {show} had characters like {name1}, {name2} and
{name3} in all {seasons} seasons.")
The show called SLY had characters like Mazden, Joe, and Helene in all 5
seasons.
If you get an error please make sure you have the latest version of python
installed.

While there are other variations to convert integers into strings and
concatenate strings together, it is best to learn those which are used
throughout the industry as standard. Now, you have seen how to create a
variable, recall it, and concatenate the same. Everything sounds perfect,
except for one thing; these are predefined values. What if we need input
directly from the end-user? How can we possibly know that? Even if we do,
where do we store them?
EIGHT

Dictionaries and Lists


The dictionary offers programmers a whole lot of options, especially in
storing a limitless volume of information. Here, you will understand what
dictionaries are, how you can use them in a loop, build lists inside them, and
create a dictionary inside another dictionary. If you can understand the
concept of dictionaries in Python, it will equip you in various ways and
allow you to model different live situations.

You can create a simple dictionary, which represents an individual. With this,
you can store huge amounts of information, including the person’s name,
location, age, phone details, and security number, anything you can think of
as it concerns the person. You can do so much with a dictionary in Python,
such as storing people’s names with their best food, words with their
meaning, countries and their presidents, etc.

Let us look at a game with teams having different scores and colors. This
code stores information as it relates to a particular team.

team1 ={‘color’: ‘red’, ‘scores’ : 3} print(team1 [‘color’]) print(team1


[‘scores’])

The dictionary team1 stores the color and scores, whereas the last two lines
access the dictionary before displaying the information as seen below
red 3

New programming concepts require consistent practice to perfect it. Since


you are learning a new language, it is crucial to understand this concept
painstakingly. If you understand it, you can apply it in all realworld
situations.

What is a dictionary?

From the program above, you can have an idea of what dictionaries are. A
dictionary is a group of key-value pairs. Every single key in the dictio‐ nary
has its corresponding value; the key enables you to have access to the value,
and it can be a list, string, number, or dictionary. Dictionaries are usually
enclosed in braces with the keys and values placed inside the braces. For
instance:

team1 ={‘color’: ‘red’, ‘scores’ : 3}

A key to a value pair always has values corresponding to each other. Once
you provide the key in a dictionary, Python returns the value corresponding
with such key. Each key is linked to a value by a colon, whereas individual
key-value pairs are disconnected by a comma.

team1 ={‘color’: ‘red’, ‘scores’ : 3}


The program above has only one pair, with each matching its value,
respectively. The color matches red, whereas scores match the value 0.

How to access values

If you want to access the value of a key, you have to include the dictio‐ nary
name before placing the key in square brackets.
team1 ={‘color’: ‘red’, ‘scores’ : 3} print(team1[‘color’])
The output for this code will return the corresponding key value from the
dictionary “team1,” which in this situation is red.

Python allows us to have an unlimited number of key-value pairs. We can


add more codes to illustrate this. Additionally, we can decide the particular
key-pair to print or display on the screen. In this code, it will display
‘London.’

team1 ={‘color’: ‘red’, ‘scores’ : 3, ‘S/N’ : 1, ‘place’ : ‘London’}


print(team1[‘place’]) London

Adding key-value pairs

Since dictionaries are structurally dynamic, we can add new pairs to them
whenever we want. For instance, we can add additional informa‐ tion to our
original program to include positions, which will display the position score..
Let the home team be on the left position while the away team is on the
right.

team1 ={‘color’: ‘red’, ‘scores’ : 3} print(team1) team1[‘home_team’] = left


team1[‘away_team’] = right print(team1)

We began by defining a dictionary “team1” and included its key and values,
respectively, before printing the dictionary. In the second phase of the code,
we assign the home team to be on the left position while the away team is on
the right. If we print the program, our output will be:

{‘color’: ‘red,’ ‘scores’ : 3} {‘color’: ‘red’, ‘scores’ : 3, ‘home_team’: left,


‘away_team’ : right}
In our final program, we have four key-value pairs, where we added two
positions, whereas the original two specifies only the color and score.

At times, most programmers find it convenient to begin with an empty


dictionary, unlike what we did by adding elements first. To fill an empty
dictionary, you have to define the dictionary without adding any keyvalue
pairs. The dictionary will be empty with a set of braces. For instance, if we
are to define the color and scores dictionary, that will be as follows:

team1 = {} team1[‘color’] = ‘red’ team1[‘score’] = 3 print(team1)

What we did here is to define an empty team1 dictionary before adding color
and score values, respectively. We will get the same results as what we got in
our aforementioned examples.
{‘color’: ‘red,’ ‘scores’ : 3}

How to modify values

Besides adding and creating an empty dictionary list, you can also modify a
value in your dictionary. To do this, you have to specify the dictionary name
before adding the new value. Let us change the color from red to blue.

team1 ={‘color’: ‘red’} print(f “The color of the team is {team1[‘color’]}.”)


team1 = [‘color’] = ‘blue’ print(f “The team’s new color is
{team1[‘color’]}.”)

What we did is first to define the team1 dictionary, which contains only the
team’s color. We then print the team’s color before changing the value of the
corresponding key from red to blue. The output shows that we have changed
the team color from red to blue.

The color of the team is red. The team’s new color is blue.

To make the program more interesting, I will track the position of the team
based on their speed in the opponent’s direction. With the ball speed, we can
determine if the team is on the left or right.

team1 = {‘home_team’ : ‘left’, ‘away_team’: ‘right’, ‘ball’: ‘ neutral’

print(f “Original direction: {team1(‘home_team’)}”)


#The team is on the left position
#Current speed of the team
if team1[‘ball’] == ‘slow’:
home_incre = 1
elif team1[‘ball’] == ‘medium’:
home_incre = 2
else:
#in opposition half
home_incre = 3
team1[‘home_team’] = team[‘home_team’] + home_incre print(f “Position
of team: {team1[‘home_team’]}”)
If you observe, I intentionally avoided the color and its point value in order
to make the program simple. We began by defining a team with the left and
right position; a ball speed set medium.

In the line “if team1[‘ball’] == ‘home’:” we use an if-elif-else condi‐ tional


statement to test the position of the ball. If the ball is slow, then it is on the
home team, if it is medium, then it is positioned in the middle. Run the
program and notice what the output will be.

How to remove key-value pairs

So far, you have learned how to add, modify, and create an empty dictionary
list. What if you decide to remove a piece of information in your dictionary?
You can take advantage of the “del” statement to remove your information.
Let us use our original program to illustrate how you can easily remove a
key-value pair in Python.

team1 = {‘color’: ‘red’, ‘scores’ : 3} print(team1) del team1[‘color’]


print(team1)

The only difference to our original program is the last two lines we added.
We use the del statement to delete the “color” key from our team1
dictionary. This will eventually remove the corresponding value of the key.
Our initial output will display the keys and its corresponding value, but after
the “del” statement, it will print only the scores. Let’s see how that will be:

{‘color’: ‘red,’ ‘scores’ : 3} {‘scores’ : 3}

Dictionary with similar objects

We have only stored different information as it relates to a single object,


which in this case, is our team1. However, you are not limited to a particular
team as you can store information on different objects. For instance, we want
to conduct an election for a community. We can use a dictionary to store the
list of candidates, along with their parties.

election_list = { ‘Elizabeth Wallen : ‘Freedom Party,’ ‘Douglas Smith:


‘Sovereign Nation Party,’ ‘Angelina Rice: ‘ Women Liberation Movement,’
‘Hillary Clinton: ‘Democratic Party,’ ‘Mitt Romney: ‘Republican Party,’ }

If you observe, there is a difference from our earlier list as we broke this list
into several lines, unlike the team1 dictionary, where everything is written
on a single line. Each candidate corresponds to his or her party; additionally,
there is always an opening and closing brace. Don’t forget to add a comma
to signify the end of a pair. With this, you can add another key-value pair.
Let us pick a candidate of our choice.

list = election_list[‘Mitt Romney].title() print(“Our Vote will be for {list}.”)


In this portion, we see that the user picked Mitt Romney as their favorite
candidate.
Our vote will be for Mitt Romney.

Looping through dictionaries

A dictionary can have a single key-value pair and even up to millions of


pairs due to its capability of accommodating large amounts of data. With
this, you can loop through a dictionary. Since we have different ways of
storing information when using dictionaries, it makes it possible to loop
through the dictionary in various ways. Here, we will explore ways of
looping through dictionaries.

However, before we begin to explore the various ways of approaching


looping through dictionaries, let us look at a dictionary that saves the
information about users visiting a website. The dictionary stores the last
name, first name, and username of the person.

user = { ‘last_name’: ‘Romney,’ ‘first_name’: ‘Mitt,’ ‘username’: ‘miromn,’


}

If you remembered what you have learned, you could easily access every
information in our user dictionary. However, what will you do if you want to
see all the information stored in our dictionary? Well, to do that, you have to
use a “for loop” to go through the dictionary. Let's see how you can put that
into action.
user = { ‘last_name’: ‘Romney,’ ‘first_name’: ‘Mitt,’ ‘username’: ‘miromn,’
} for k, v in [Link](): print(f “\nK: {k}”) print(f “V: {v}”)

As you can see, for you to loop through a dictionary, you have to create
names for our two variables, which will hold last and first names in our key-
value pair. You can use any variable name of your choice. In this case, we
use k and v to represent key and value, respectively. Our output will be:

K: last_name V: Romney K: first_name V: Mitt K: username V: miromn

Looping through a dictionary works perfectly for a program like the list of
candidates in an election we wrote precedingly. Remember, it stores the
name and party of candidates approved to participate in the elec‐ tion. If we
were to loop through the list, we will get the names of every candidate and
generate their respective parties. Since the keys represent the person’s name,
whereas the value is the party, we can use variable names such as name and
party in our loop rather than using key and value. This will make it easier for
you to understand fully.

election_list = { ‘Elizabeth Wallen : ‘Freedom Party’, ‘Douglas Smith:


‘Sovereign Nation Party’, ‘Angelina Rice: ‘ Women Liberation Movement’,
‘Hillary Clinton: ‘Democratic Party’, ‘Mitt Romney: ‘Republican Party’, }
for name, party in election_list.item(): print(f “{[Link]()}’s party is the
{[Link]()}.”)

The program loops through every key-value pair in our election_list, and it
goes through every pair of the key assigned to the name variable while the
value is assigned the party variable. With only the last two lines, we can
generate a full list of all candidates in the election. With this, you can display
from a single name to millions of names in a list to the screen.

Elizabeth Wallen’s party is the Freedom Party. Douglas Smith’s party is the
Sovereign Nation Party. Angelina Rice’s party is the Women Liberation
Movement. Hillary Clinton’s party is the Democratic Party. Mitt Romney’s
party is the Republican Party.

team1 = {‘home_team’ : ‘left’, ‘away_team’: ‘right’, ‘ball’: ‘ neutral’


print(f “Original direction: {team1(‘home_team’)}”)
#The team is on the left position
#Current speed of the team
if team1[‘ball’] == ‘slow’:
home_incre = 1
elif team1[‘ball’] == ‘medium’:
home_incre = 2
else:
#in opposition half
home_incre = 3
team1[‘home_team’] = team[‘home_team’] + home_incre print(f “Position
of team: {team1[‘home_team’]}”)

Looping through keys only

We can use the keys() method to display only the key values while omit‐ ting
the values contained in the dictionary. Let us use our election_list to
demonstrate this feat.

election_list = { ‘Elizabeth Wallen’ : ‘Freedom Party,’ ‘Douglas Smith:


‘Sovereign Nation Party,’ ‘Angelina Rice: ‘ Women Liberation Movement,’
‘Hillary Clinton’: ‘Democratic Party,’ ‘Mitt Romney: ‘Republican Party,’ }
for name in election_list.keys(): print([Link]())

The line after the closing brace is the beginning of the “for loop,” which tells
the interpreter to pull only the keys from our election_list. Remem‐ ber, we
assign names as the key. The output will be as follows:

Elizabeth Wallen Douglas Smith Angelina Rice Hillary Clinton Mitt


Romney

Looping through values only

In the same manner that we can easily loop through the keys in a given
dictionary, we can also loop through the value and display the value list. We
can use the values() method to achieve this feat. Remember, in the earlier
example, we use the keys() method.
election_list = { ‘Elizabeth Wallen : ‘Freedom Party,’ ‘Douglas Smith:
‘Sovereign Nation Party,’ ‘Angelina Rice: ‘ Women Liberation Movement,’
‘Hillary Clinton: ‘Democratic Party,’ ‘Mitt Romney: ‘Republican Party,’ }
print(“This is the list of Political Party for the election:”) for party in
election_list.values(): print([Link]())

The “for” statement pulls all the value in our dictionary list and assigns it to
the party. The print statement then prints all the values in the elec‐ tion_list.

This is the list of Political Party for the election: Freedom Party Sovereign
Nation Party Women Liberation Movement Democratic Party Republican
Party

This approach prints all the values available in the dictionary without
verifying any repetition. Although this may work perfectly in a small list,
however, when you have to pull a significant name or item, there may be
room for repetition. To avoid such repetition, it is a way out. We can use a
set, which is a group where every item is unique.

election_list = { ‘Elizabeth Wallen : ‘Freedom Party,’ ‘Douglas Smith:


‘Sovereign Nation Party,’ ‘Angelina Rice: ‘ Women Liberation Movement,’
‘Hillary Clinton: ‘Democratic Party,’ ‘Mitt Romney: ‘Republican Party,’ }

print(“The following Political Parties have been mentioned already:”)


for party in set(election_list.values()):
print([Link]())

We added another name and party to the list – Nicolas Fred. Assuming we
are printing only the value list and don’t want a repetition of the party. Once
you use the set() around the list, you don’t wish to duplicate; python
identifies this as a unique item in the list. In the end, there won’t be any
repeated detail.

The following Political Parties have been mentioned already. Freedom Party
Sovereign Nation Party Women Liberation Movement Democratic Party
Republican Party

Definition of list
A list refers to a data type that contains a collection of items in an orderly
manner. For instance, a list can comprise the alphabets, digits, or names of
the street in a country. Below is the syntax structure for a list:

list = [item1, item2, item3, itemN] Consider the list of items in a kitchen in
this code.

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]

print(kitchen_item)
If you decide to print this code, the output will be as follows:

[“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,” “knife,” “bowls”]

Accessing a list item

Perhaps, you don’t want the users to see certain items in a list; you can
decide to access only the items you want. To have access to a particular
element in a list, you have to write the list name then followed by the index
of the item, which is enclosed in squared brackets. For instance, we can pull
the third item in our list of items in the kitchen.

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]
print(kitchen_item [3])
The output will be as follows: dishwasher

Index positions

The first index position in Python is not 1 but 0. If you observe in the
example above, you will see that when indexed the third item, we started
counting from 0. You can see that pot (0), kettle (1), fridge (2), while
dishwasher (3). If you run a Python program and get a different result; you
have to check if you are making a number error.

Always remember that the second element in any list starts with an index of
1. A simple way of knowing what the particular index number will be is to
subtract one from the item you want to index. Does that sound simple?

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]
print(kitchen_item)

For instance, we want to access only the item “microwave.” To do that, you
have to count the number of items to get to the “microwave” and subtract
one. From the code, if you count first, you will discover that “microwave” is
the 5th element. However, to index it to print only “microwave,” you have to
substrate one from the element. Your code will be like this:

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]
print(kitchen_item [4])
Let us use another example to index the third and sixth items.
kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”
“knife,” “bowls”]
print(kitchen_item [3])
print(kitchen_item [6])
The output will be as follows:
dishwasher bowls

Assuming you only want to access the last element, Python has a unique way
of doing that. You can do this by using an index of -1. With this, Python
returns the last item.

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]
print(kitchen_item [-1])

In this example, the code will return “bowls.” It is easy to remember this
syntax. You do not have to know the particular length of the list. This also
applies to other negative index values. It is like going backward. You can use
the negative index to access the second or third items in a list. For instance,

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]
print(kitchen_item [-2])
print(kitchen_item [-3])
The output will be as follows:
knife microwave

Adding, changing, and removing elements in a list

The lists you will mostly create in Python are dynamic in nature. This means
you have to build the list, add elements to it, and remove it in the course of
running your program. For instance, you may decide to create a game where
the player must shoot birds flying. You may record the first set of birds in a
particular list before removing each bird that is shot down. Once a new bird
appears, it is added to the screen. Your bird lists will increase, whereas the
length will decrease throughout the game.

Modifying elements

You can modify elements in an element similar to how you can access it.
Furthermore, the same syntax applies to when you want to access an
element. To modify an element, you will use the list name, followed by the
index element that you want to modify, and then provide the new value that
you want to change. Well, this may sound foreign; however, let me use a
simple example to illustrate how you can do this. For instance, we want to
change dishwasher to spoon in the example below:

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]

print(kitchen_item)
kitchen_item[3] = “spoon”
print(kitchen_item)

The first two lines of code define our original list, which contains the word
“dishwasher.” The third line changes the element from dishwasher to spoon.
If you do it correctly, you will get the output as:

[“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,” “knife,” “bowls”]


[“pot,” “kettle,” “fridge,” “spoon,” “microwave,” “knife,” “bowls”]
You can change any element irrespective of where it is positioned.

Adding elements

At times, you may want to add an element in a list to expand your program.
Remember the bird scenario, where you have additional new birds each time
you shoot. It doesn’t apply to that alone; you may want to expand your
database to include new users or add new items to a list. Python provides
various means of adding elements in a list. We will focus on two ways you
can do this as a beginner.

Append an element to the list end

This method is the simplest to use when adding an element to a list. By


appending the element, you add the item to the list end. Remember, we use
the word “append” to add new items. However, for consistency purposes, I
will use our previous kitchen_item example to explain. In this example, we
will add cooking gas to the list.

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]
print(kitchen_item)
kitchen_item.append(“spoon”)
print(kitchen_item) The append()method allows us to add an element at the
end of the list. The output will be:
[“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,” “knife,” “bowls,”
“spoon”]

If you have an empty list, you can utilize the append() method to add a new
list. Assuming we want to add a new list element such as pot, kettle, and
microwave, we can do that as follows:

kitchen_item [] kitchen_item.append(“pot”) kitchen_item.append(“kettle”)


kitchen_item.append(microwave”) print(kitchen_item)

This code will produce:


[“pot,” “kettle,” “microwave,”]
It is very common to build the list this way because you may not know the
particular data type the users want to keep track of in the program. However,
to give the users full control, first define an empty list, which will hold
values of the users. With this, you can use the append method to add new
elements to the list created.

Inserting elements

The second way of adding an element in a list is by inserting the element to


the position you want through the insert() method. You have to specify the
index of both the new element and the value, respectively. For instance, we
want to insert a “spoon” after the microwave item on the list.

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]

print(kitchen_item)
kitchen_item.insert(3, “spoon”)
print(kitchen_item)

Your output will be:


[“pot,” “kettle,” “fridge,” “dishwasher,” “spoon” “microwave,” “knife,”
“bowls”]

What happened in the example above is that I inserted the value “spoon” at
the third index. The insert method enables us to create a space between the
“dishwasher” and the “microwave” while storing the value “spoon” to the
location created.

Removing elements

There are situations that may warrant you to remove an item in a list. For
instance, a player may decide to remove a bird; he shoots down from the sky
from the active list. Perhaps, you want to delete a customer’s account or
cancel their account. You can remove such detail from the list. You can use
the following two ways to remove elements in a list.

Remove items using del statement


Python provides a unique way of removing or deleting an item if you know
the position of such an item from the list. Look at the code below:
kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”
“knife,” “bowls”]

print(kitchen_item)
del kitchen_item [4]
print(kitchen_item)

What did you think will be deleted from the snippet above? If your answer is
a dishwasher, then you are wrong. Remember that the Python index begins
at 0. This means we start counting 0 from the first element. Therefore, the
final output will be:

[“pot,” “kettle,” “dishwasher,” “microwave,” “knife,” “bowls”]


You can remove any item from the position of your choice.
Using the pop() method to remove an item

There are situations where you want to use an item value after removing it
from the list. For instance, you want to know the coordinates of the bird you
shot, to enable you to draw an explosion in such a position. The function of
the pop()method is to remove the last item in the list. For clarity, let us pop
an example.

kitchen_item = [“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,”


“knife,” “bowls”]

print(kitchen_item)
popped.kitchen_item = kitchen_item.pop()
print(kitchen_item)
print(popped.kitchen_item

I won’t explain the first two lines since you are already conversant with it.
However, if you forget, I will refresh your memory. The first line begins by
declaring “kitchen_item” as a variable with values including pop, kettle,
fridge, dishwasher, microwave, knife, and bowls. The second line prints out
the items in the kitchen_item list.
In the third line, we popped a value from our list and store the value to the
new variable “popped.kitchen_item” additionally, we print out the remaining
items in the kitchen_item list. From the code above, our output will be:

[“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,” “knife,” “bowls”]


[“pot,” “kettle,” “fridge,” “dishwasher,” “microwave,” “knife”] bowls

The first line shows the complete kitchen_items, whereas the second shows
the remaining items after the popped method was used. Finally, line three
shows the item removed from our list.
NINE

Python Tuples, Sets, and Loops


Tuples are collections of data types in Python that can't be changed but can
be arranged in a specific order by using the order keyword. Numerals are
written within round brackets to allow for the inclusion of duplicate items, as
shown in the syntax below.

Tuple = (“string001”, “string002”, “string003”) print (Tuple)

As with the Python List, you can display a single string from a Tuple by
referencing the string's position within a square bracket in the print
command.

Tuple = (“string001”, “string002”, “string003”, “string004”)


print (Tuple [1])
OUTPUT – (“string002”)
Negative indexing can also be applied to Python Tuples, as demon‐ strated in
the following example:
Tuple = (“string001”, “string002”, “string003”, “string004, “string005”)
print (Tuple [-2])
OUTPUT – (“string004”)

Additionally, you can specify a range of indexes by specifying the start and
end of the range. The result of such a command on a Python Tuple is a new
Tuple containing only the specified items, as illustrated below:
Tuple = (“string001”, “string002”, “string003”, “string004”,
“string005”, “string006”)
print (Tuple [1:5])
OUTPUT – (“string002”, “string003”, “string004”, “string005”)

Bear in mind that the first item is at position 0 and the range's final posi‐
tion, which is the fifth in this example, is not included.
You can also specify a range of negative indexes to Python Tuples, as shown
in the example below:

Tuple = (“string001”, “string002”, “string003”, “string004”,


“string005”, “string006”)
print (Tuple [-4: -2])
OUTPUT – (“string004”, “string005”)

Remember, the last item is at position -1 and the final position of this range,
which is the negative fourth position in this example, is not included in the
output.

Unlike Python lists, you cannot directly change the data value of Python
Tuples after they have been created. However, conversion of a Tuple into a
List and then modifying the data value of that List will allow you to create a
Tuple subsequently from that updated List. Let’s look at the example below:

Tuple1 = (“string001”, “string002”, “string003”, “string004”,


“string005”, “string006”) List1 = list (Tuple1)

List1 [2] = “update this list to create new tuple”


Tuple1 = tuple (List1)
print (Tuple1)

OUTPUT – (“string001”, “string002”, “update this list to create new tuple”,


“string004”, “string005”, “string006”)
You can also determine the length of a Python Tuple using the “len()”
function, as shown in the example below:
Tuple = (“string001”, “string002”, “string003”, “string004”,
“string005”, “string006”)
print (len (Tuple))
OUTPUT – 6

You cannot selectively delete items from a Tuple, but you can use the “del”
keyword to delete the Tuple in its entirety, as shown in the example below:

Tuple = (“string001”, “string002”, “string003”, “string004”)

del Tuple
print (Tuple)
OUTPUT – name ‘Tuple’ is not defined

You can join multiple Tuples with the use of the “+” logical operator.
Tuple1 = (“string001”, “string002”, “string003”, “string004”)

Tuple2 = (100, 200, 300)


Tuple3 = Tuple1 + Tuple2
print (Tuple3)

OUTPUT – (“string001”, “string002”, “string003”, “string004”, 100, 200,


300)
You can also use the “tuple ( )” constructor to create a Tuple, as shown in the
example below:
Tuple1 = tuple ((“string001”, “string002”, “string003”, “string004”))
print (Tuple1)

We've all been in a situation at work or at home where we're stuck doing the
same thing over and over again. In history, humankind has been constrained
by the burden of repetitive tasks. Nonetheless, computers unlike humans will
flawlessly repeat any commands, in contrast to humans, who are expected to
make errors from time to time.

Loops

Loops allow you to do something repeatedly, saving time and effort. You can
use them in Python in several ways: while, if-else, and for loops. Therefore,
Loops, in Python, are a sequence of statements which are executed
repeatedly until a certain condition is met. In Python, loops can be used with
functions like while and for to repeatedly process data or allow execution to
continue on subsequent lines.

Unlike languages that use loops as their main control flow construct, like
C++ and Java that have looping constructs built-in and do not allow for
much flexible control flow outside of looping constructs, Python uses its
built-in iteration construct instead.

In this section, we will learn about loops in Python programming. Just like
the name suggests, loops repeat a block of code until a certain condition is
met. In Python, we have three types of loops, and we will be exploring them
all in this chapter.

While loops

This particular loop will continue working until a certain condition is met. In
this first example, we will use an iteration variable named I to show the even
numbers up until it reaches 10.

1. i=0
2. while i <=10: # Note if you do not add the equal sign, Python will not
print the last value of 10
3. print (i) # Printing i to the screen
4. i+=2 # Adding two on every loop revolution

# Do not forget to press on shift+tab to close this block of code. Program


output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link]

0
2
4
6
8
10

Process finished with exit code 0


Now, just as we used an operator to decide when to stop, this time we’ll use
the length of a list to stop the loop. In this case, we are going to print the
names of everyone on a list along with a welcome message.

1. nameList=[Jaden, Bram, Faith, Caroline, 'Jose', 'Jack']


2. while nameList:
3. print (f"Welcome {[Link](-1)}, to Smith’s party") # Pop() method
takes the last name of the list, prints it and then removes it from the list

#Remember to press on shift+tab to close this code block


Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] Welcome
Jaden, to Smith’s party Welcome Bram, to Smith’s party Welcome Faith, to
Smith’s party Welcome Caroline, to Smith’s party Welcome Collins, to
Smith’s party Welcome Patrick, to Smith’s party Process finished with exit
code 0

If you do not like to use the pop method while utilizing lists, you can use the
length of a list in your loop. Some programmers prefer not to use the pop
method, as it removes values from the list that may be needed in the future.
Look at the example below that accomplishes that without losing any item
from the list.

1. nameList=[Jaden, Bram, Faith, Caroline, Collins, Patrick] # List variable


with all names.
2. x = 0 # Initial value for loop break.
3. while x < len(nameList): # While x is smaller than the length of the list.
4. print (f"Welcome {nameList[x]}, to Smith’s party") # Printing the
welcome message.
5. x += 1 # Iterating one to x on every cycle.

Program output:
C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link]
Welcome Patrick, to Smith’s party
Welcome Collins, to Smith’s party
Welcome Caroline, to Smith’s party
Welcome Faith, to Smith’s party
Welcome Bram, to Smith’s party
Welcome Jaden, to Smith’s party
Process finished with exit code 0

Another method of stopping a loop is using a break command. In the


example below, the program is trying to identify the closest number to 1000
that is divisible by 14.

1. i = 1000 # The initial value of i


2. while i >= 0: # This will keep the loop running until i is equal to zero.
3. if i % 14 ==0: # If the remainder of the division by 14 is to zero.
4. print (i) # Printing the required value.
5. break # Stop (break) the program.
6. i-=1 # Subtracting one on each revolution of the loop

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] 994
Process finished with exit code 0

In the following while loop example, we'll create a program that prompts for
a password. If the password is incorrect three times, it will send a message to
the user requesting that they try again later. The program, on the other hand,
will display a success message if the pass‐ word is correct.

pwd1 = "password" # The password that is saved in the program.

1. i = 0
2. pwdPass = False
3. while i < 3: # This will give the user three attempts
4. userPwd = input(f"Please insert the password: ") # Daving user password
into a variable.
5. i += 1 # Incrementing is to break the loop after three attempts.
6. if pwd1 == userPwd: # Checking saved passwords with the user
password.
7. pwdMsg = "You're pure of heart, you may pass."
8. break # Breaking the loop as there is no need to run it again.
9. else : # Kust like an if statement you can have an else statement in a while
loop
10. pwdMsg = "You're unworthy, only the pure of heart may pass!" 11. print
(pwdMsg) # Printing the message after the loop is finished.

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] Please
insert the password: Password Please insert the password: PASSWORD
Please insert the password: password You're pure of heart, you may pass.
Process finished with exit code 0

Finally, we're going to use a while loop to create an old-school simple game.
The user will decide whether to start or stop a toy train in this game, with the
option to quit.

Let’s take a look at the code.

1. userCommand = '' # Creating an empty variable to store the user


command.
2. while True: # This will keep the loop going until it is broken inside the
loop
3. userCommand = input('>>> ') # We use this to give the program a retro
look.
4. if [Link]() == 'start':
5. # Note the lower case method, this is to avoid lower or upper case
problems with the user.
6. print ('train has started')
7. elif [Link]() == 'stop':
8. print ('train has stopped')
9. elif [Link]() == 'quit':
10. print ('See you later...')
11. break # This will break the program if the user wants to quit. 12. elif
[Link]() == 'help':
13. print (f"""
14. Start ===> To start the train
15. Stop ===> To stop the train
16. Quit ===> To exit program """)
17. else :
18. print (
19. "Sorry, I can't understand you. type Help for assistance.") # This is
displayed so that the user knows what the options are.

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] >>> Start
train Sorry, I can't understand you. type Help for assistance. >>> HELP Start
===> To start the train Stop ===> To stop the train Quit ===> To exit
program >>> Start train has started >>> stop train has stopped >>> Quit See
you later... Process finished with exit code 0

For loops

A for loop is typically used when you know exactly how many times you
want to loop. When a break is possible spontaneously, you should use a
while loop. Additionally, 'for loops' are extremely useful when working with
strings. The first example demonstrates how Python iterates over a [Link]
item in 'Roger': # This is the condition of the for loop. 1. print (item)

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] R o g e r
Process finished with exit code 0

Remember the exercise we did when printing out the names on a list? It is a
breeze in comparison when using a ‘for loop’. Let’s check it out.

1. nameList = [Jaden, Bram, Faith, Caroline, Collins, Patrick] # Initial list of


names
2. for item in nameList: # This will run every item of the list.
3. print (item) # This will print every item on the list.

# Do not forget to use shift and tab to close the block of code. Program
output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] Jaden
Bram Faith Caroline Collins Patrick Process finished with exit code 0

The range function is a built-in function that can be used with the ‘for loop’.
This function can be used to print a range of numbers beginning with zero.

1. for item in range(5): # This range will give us an output from zero to four
2. print (item)

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] 0 1 2 3 4
Process finished with exit code 0

The range function has the option to select a specific range – for exam‐ ple,
from 5 to 12. It can also specify the steps. That means if you want to iterate
it every time by two, you can add a third parameter to do that. Let’s look at
an example.

1. for item in range(5, 25, 5): # First parameter start range, second parameter
end range, third parameter steps
2. print (item)

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] 5 10 15 20
Process finished with exit code 0

Now for this last example, let’s imagine that you want to add all of the prices
of a shopping cart that are saved on a list.
1. priceList = [10.99, 15.25, 11.00, 244.39] # List of prices.
2. totalPrice = 0 # variable to hold the total price.
3. for price in priceList: # Note that you can call your variable any name that
you want.
4. totalPrice += price # Adding current list item to price.
5. print (totalPrice) # Printing the total price.

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] 281.63
Process finished with exit code 0

Nested loops

In essence, nested loops are created by nesting two loops together to achieve
the desired result. This is typically done when a set of instruc‐ tions needs to
be run multiple times in blocks. In this first example, we'll use nested loops
to list a set of coordinates.

1. for x in range(5): # The first loop will create the x coordinates.


2. for y in range(5): # The second loop will create the y coordinates.
3. print (f'({x}, {y})') # This will print the coordinates as you would expect.

Program output:

C:\Users\...\PycharmProjects\GettingStarted\venv\Scripts\[Link]
C:/Users/…/PycharmProjects/GettingStarted/[Link] (0, 0) (0,
1) (0, 2) (0, 3) (0, 4) (1, 0) (1, 1) (1, 2) (1, 3) (1, 4) (2, 0) (2, 1) (2, 2) (2, 3)
(2, 4) (3, 0) (3, 1) (3, 2) (3, 3) (3, 4) (4, 0) (4, 1) (4, 2) (4, 3) (4, 4) Process
finished with exit code 0

Python sets

In Python, sets are collections of unorganized and unindexed data types. Sets
are not permitted to contain duplicate items and must be enclosed in curly
brackets, as illustrated in the syntax below:
set = {“string1”, “string2”, “string3”} print (set)

In contrast to the Python List and Tuple, you cannot display desired items
from a Set by referencing their position, as the Python Set is not arranged in
any distinct order. For this reason, items lack indexing, however, the ‘for
loop’ can be used on Sets. Unlike Python Lists, Python Sets cannot have
their data values changed directly after they are created. You can, however,
use the "add ()" method to add a single item to Set and the "update ( )"
method to update one or more items in an existing Set. Consider the
following example:

set = {“string1”, “string2”, “string3”} set. add (“newstring”) print (set)


OUTPUT – {“string1”, “string2”, “string3”, “newstring”} set = {“string1”,
“string2”, “string3”} set. update ([“newstring1”, “newstring2”,
“newstring3”,) print (set)

OUTPUT – {“string1”, “string2”, “string3”, “newstring1”, “newstring2”,


“newstring3”}
You can also determine the length of a Python Set using the “len()” func‐
tion, as shown in the example below:
set = {“string1”, “string2”, “string3”, “string4”, “string5”, “string6”,
“string7”}
print (len(set))
OUTPUT – 7
To delete a specific item from a Set , the “remove ()” method can be used as
shown in the code below:
set = {“string1”, “string2”, “string3”, “string4”, “string5”}

set. remove (“string4”)


print (set)
OUTPUT – {“string1”, “string2”, “string3”, “string5” }

You can also use the “discard ( )” method to delete specific items from a Set,
as shown in the example below:

set = {“string1”, “string2”, “string3”, “string4”, “string5”} set. discard


(“string3”)
print (set)
OUTPUT – {“string1”, “string2”, “string4”, “string5” }

The “pop ( )” method can be used to delete only the last item of a set. It must
be noted here that since the Python Sets are unordered, any item that the
system deems as the last item will be removed.
As a result, the output of this method will be the item that has been removed.

set = {“string1”, “string2”, “string3”, “string4”, “string5”} A = [Link] ( )


print (A) print (set) OUTPUT – String2 {“string1”, “string3”, “string4”,
“string5” }

To delete the entire Set, the “del” keyword can be used, as shown below.

set = {“string1”, “string2”, “string3”, “string4”, “string5”} delete set print


(set) OUTPUT – name ‘set’ is not defined

To delete all the items from the Set without deleting the variable itself, the
“clear ()” method can be used, as shown below:
set = {“string1”, “string2”, “string3”, “string4”, “string5”}

[Link] ( )
print (set) OUTPUT – set ( )

You can join multiple sets with the use of the “union ( )” method. The output
of this method will be a new set that contains all items from both the sets.
You can also use the “update ( )” method to insert all the items from one set
into another without creating a new set.

Set1 = {“string1”, “string2”, “string3”, “string4”, “string5”} Set2 = {15, 25,


35, 45, 55} Set3 = [Link] (Set2) print (Set3)

OUTPUT – {“string1”, 15, “string2”, 25, “string3”, 35, “string4”, 45,


“string5”, 55}

Set1 = {“string1”, “string2”, “string3”, “string4”, “string5”} Set2 = {15, 25,


35, 45, 55}
[Link] (Set2)
print (Set1)
OUTPUT – {25, “string1”, 15, “string4”,55, “string2”, 35, “string3”, 45,
“string5”}
You can also use the “set ( )” constructor to create a Set, as shown in the
example below:

Set1 = set ((“string1”, “string2”, “string3”, “string4”, “string5”)) print (Set1)

OUTPUT – {“string3”, “string5”, “string2”, “string4”, “string1”}


TEN

Your First Program


Writing one's first line of code and successfully executing it always boosts
one's confidence and sense of pride. I hope you're all excited to write and
execute your first Python program, as this will be your first significant step
into the world of Python programming. To begin, let us examine the most
well-known programming example: printing the 'Hello World!!' statement.
To keep things simple, we'll write the code in the interactive mode of the
IDLE that we installed earlier, using the chevron prompt.

We simply need to use the print() method to print the statement. We'll pass
the string to print inside the method and then press the Enter key. That is all.
Congratulations! We have just completed the execution of our first Python
program. The string “Hello World!!” will be printed to the console as the
output.

Variables
Containers are required to store data. We then need to allocate a certain
amount of memory for storing and processing this provides this container in
the form of variables for Consider a variable to be the name given to an
object. Using it, we can refer to that object at any time within the program's
environment. Vari‐ ables may contain data of any type, including numbers,
strings, floating points, Boolean values, and characters. In the following
section, we will learn about these data types.

Assigning values to variables

To assign values to a variable, we use the assignment operator (=). One of


the notable features of Python is that it is dynamically typed. Thus, to assign
values to a variable, we do not need to specifically declare the variables
beforehand with a data type (as must be done in other programming
languages like C, C++, Java, etc.). The data type of the variable gets
automatically decided at runtime by the interpreter during execution. This
could be done as:
data. Python data storage.

Note: We can use the type() function to identify the data type of a variable.
As can be seen from the output of the print() statement in each case, the class
to which those variables belong gets printed.

Multiple variable assignments

Python also provides us with an interesting feature that we can use to assign
values to multiple variables in a single statement. This feature is not
available in many programming languages.
Data
types

Now that we know that variables can be used to store data items, we must
learn about what kinds of data they can store. Python supports data in
multiple forms, and the data belongs to a certain class. We know that Python
is an object-oriented language and that each data type is actually a class. The
variables that we use to store data are the instances/objects of those classes.
Following are some of the most commonly used data types in Python:

String

Strings are continuous sequences of character data enclosed within single or


double quotation marks. The data enclosed inside the pair of opening and
closing quotation marks is part of the string. The data type is represented
under the str class.

Representation of string

Single-line strings

As discussed, single-line strings can be represented by putting data inside the


single and double quotation blocks. We can assign string values to the
variables and then reference these strings using the variable names. Also, we
can use the type() method to verify the data type of the variables, as can be
seen in the following example:
Multi-line strings

To assign a variable multi-line string, we must enclose it inside triple single


quotes. This can be done and verified as seen in the following example:

Numeric

The numeric data type in Python can be used for storing numerical data that
is present in the form of integers, floating values, complex numbers, etc.
Python offers support for all this numeric data. There are four different
classes in which we can divide the numeric data. These are:

Integers: Integers are stored inside the int class.


Long integers: Integers with very large values are kept under the long class.
Float: Floating point numbers/real values belong to the float class.
Complex numbers: Python also offers us the ability to use complex
numbers, which are stored inside the complex class.
Boolean

The Boolean data type gives us the ability to use True and False values.
They are covered under the bool class. Any non-zero value can be thought of
as a True value, whereas False is represented by zero.

List

Lists are one of the sequence data types that can be used to store data of
multiple data types. Items in the list are stored inside square brackets ([]) and
are separated from each other by commas (,). Lists can be compared with
arrays that are available in other programming languages. Lists are mutable
and offer us multiple methods to manipu‐ late data.

Data
type conversion
When we are writing a piece of code, there are certain cases in which we
need to change the data type of a variable. For those explicit cases, Python
provides us with a range of handy functions that can be used to change the
data type. Some of the functions are noted below in the table:

User input values

Now that we have a basic idea about the data types that are used in Python,
we will learn how to ask users to input data inside the program. For this
purpose, we will be using the input() method.

In this part, we will be writing the code inside a script. Then we will execute
that script with the help of the command line. This will give you an idea
about how to write a Python script and execute it with a command prompt.
We will start by writing the script inside a text file. You are free to use any
text editor of your choice. Here, for explanation purposes, we are writing the
script with the help of the Notepad text editor available in Windows OS.

Then, we will then save this script with the name of the form ‘file_‐
[Link]’. Use of the .py extension to save the file is necessary because it
signifies that it is a Python script.

Note that the file is being saved on the Desktop having file_name
‘Input_file.py’. After saving the file, we will move to the command line and
change our current working directory to the Desktop because our script is
present at that location. Now, we will call the Python interpreter to execute
this script. This can be done using the following command:

Python [Link]
After we run the command, the script will get executed. The input() method
will halt for a moment and ask the user to enter the data.

When we enter the data and hit enter, the next line in the program will get
executed and the print() statement will print the name using the name
variable.

Note: It is mandatory to change the directory to the location where our file is
located to run the script. Otherwise, our Python command will never find the
script file and it will return a trace back error. ELEVEN

File Management
Input and output are considered when developing programs. You provide
data to the program, the program processes the data, and then returns an
output. For instance, a calculator will accept the numbers and operations that
you specify. It will then perform the operation you requested and output the
result to you.

A program can receive input and produce output in a variety of ways. One of
those methods is by reading and writing data to and from files.

To begin learning how to work with files, you should familiarize yourself
with the open() function. open() takes one mandatory parameter and two
optional parameters. The first and most important parameter is the name of
the file.

The second parameter specifies the access mode, and the third para‐ meter
specifies the buffering mode or size of the buffer. String data is required for
the file name parameter.

Although the access mode requires string data, there is a predefined set of
string values that is defaulted to "r." The buffer size parameter must be an
integer and is set to zero by default. Create a file named sample‐ [Link] in
your Python directory to practice using the open() function. Consider the
following sample code:

>>> file1 is equal to open ("[Link]") >>>


Keep in mind that the file method returns a file object. The example
statement assigns the file object to the variable file1.

The file object has a number of attributes, three of which are as follows:
Name: This field contains the file's name.
Mode: This field contains information about the access mode used to access
the file.
Closed: If the file has been opened, this method returns False; otherwise, it
returns True.
When the open() function is called, the file is set to be open.

At this point, you can access those attributes.

>>> file1 is equal to open ("[Link]") >>> nameoffile1


'[Link]' >>> mode file1'r' >>> [Link] False >>> _

Whenever you are finished with a file, close them using the close() method.

>>> file1 = open("[Link]") >>> [Link] False >>> [Link]()


>>> [Link] True >>> _

Remember that closing the file does not delete the variable or object. To
reopen the file, just open and reassign the file object.
For example:

>>> file1 = open("[Link]") >>> [Link]() >>> file1 =


open([Link]) >>> [Link] False >>> _

Reading from a file

Before proceeding, open the [Link] in your text editor. Type "Hello
World" in it and save. Go back to Python.
To read the contents of the file, use the read() method.
For example:

>>> file1 = open("[Link]") >>> [Link]() 'Hello World' >>> _

File pointer

Python initializes the file pointer whenever you access a file. The file pointer
is analogous to the cursor in a word processor. Any operation on the file
begins at the location of the file pointer. When you open a file and specify
the default access mode, "r" (read-only), the file pointer is set to the file's
beginning. The tell() method can be used to determine the current position of
the file pointer.
For example:

>>> file1 = open("[Link]") >>> [Link]() 0 >>> _

Most of the actions you perform on the file move the file pointer. For
example:

>>> file1 = open("[Link]") >>> [Link]() 0 >>> [Link]() 'Hello


World' >>> [Link]() 11 >>> [Link]() '' >>> _

To move the file pointer to a position you desire, you can use the seek()
function.
For example:

>>> file1 = open("[Link]") >>> [Link]() 0 >>> [Link]() 'Hello


World' >>> [Link]() 11 >>> [Link](0) 0 >>> [Link]() 'Hello World'
>>> [Link](1) 1 >>> [Link]() 'hello World' >>> _

The seek() method has two parameters. The first is offset, which sets the
pointer’s position depending on the second parameter. Also, an argu‐ ment
for this parameter is required.

The second parameter is optional. It is for whence, which dictates where the
“seek” will start. It is set to 0 by default.

If set to 0, Python will set the pointer’s position to the offset argument. If it
is set to 1, Python will set the pointer’s position relative or in addi‐ tion to
the current position of the pointer.

If set to 2, Python will set the pointer’s position relative or in addition to the
file’s end.

Note that the last two options require the access mode to have binary access.
If the access mode does not have binary access, the last two options will be
useful to determine the current position of the pointer [seek(0, 1)] and the
position at the end of the file [seek(0, 2)].

For example:
>>> file1 = open("[Link]") >>> [Link]() 0 >>> [Link](1) 1 >>>
[Link](0, 1) 0 >>> [Link](0, 2) 11 >>> _

File access modes

To write to a file, you'll need to understand more about Python's file access
modes. File operations are classified into three categories: read‐ ing, writing,
and appending.

Reading enables you to view and copy any portion of the contents of a file.
Writing enables you to overwrite the contents of an existing file and create a
new one. Appending enables you to modify the file's content while
preserving the rest of the file's content.

File access modes are classified as string and binary. String access enables
you to view the contents of a file as if it were a text file. Binary access
enables you to interact with a file in its most basic form: binary.

In your sample file, accessing it using string access allows you to read the
line “Hello World.” Accessing the file using binary access will let you read
“Hello World” in binary, which will be b'Hello World'.

For example:

>>> x = open("[Link]", "rb") >>> [Link]() b'Hello World' >>> _

When editing text files, having access to strings is advantageous. Other types
of data, such as images, compressed files, and executables, can also benefit
from binary access. This book teaches you only how to manage text files.

There are numerous possible values for the file access mode parameter of the
open() function, but you do not need to memorize the combina‐ tion. All you
need is a working knowledge of letter combinations.

Each letter and symbol stand for an access mode and operation. For
example:

r = read only—file pointer placed at the beginning r+ = read and write a =


append—file pointer placed at the end a+ = read and append
w = overwrite/create—file pointer set to 0 since you create the file
w+ = read and overwrite/create
b = binary
By default, file access mode is set to string. You need to add b to allow
binary access. For example: "rb."

Writing to a file

When writing to a file, you must always remember that Python over‐ writes
and_not_insert_file.
For example:

>>> x = open("[Link]", "r+") >>> [Link]() 'Hello World' >>>


[Link](0) 0 >>> [Link]("text") 4 >>> [Link]() 4 >>> [Link]() 'o World' >>>
[Link](0) 0 >>> [Link]() 'texto World' >>> _

Perhaps you anticipated the resulting text to be "textHello World." The file
object's write method replaces each character one by one, starting at the
pointer's current position.

Using files

As with other high-level languages, Python supports the concept of files.


Apart from reading input from files and writing output to files, Python
includes some useful file and directory manipulation hacks that come in
handy when writing automated scripts on file systems.

To open/create a file
Sample code

>>>>f = open(“[Link]”) #returns a file object >>>>line=[Link]() #read


line by line from the file >>>>while line: # till eof >>>>print line #print the
line >>>> line=[Link]() #read line by line from the file >>>>[Link]()
#close the file object

The while loop can be replaced using a for loop and the same result can be
achieved. The open() API can take two parameters, the first being the file
name and the second the parameter to indicate the permission mode in which
the file is opened—to read, write and execute. For exam‐ ple, to write to a
file, it needs to be opened with write permission as follows:

Sample code
>>>>[Link](“[Link]”,w)

>>>>[Link](“hello!”) #this writes the word “hello” to the file by name


[Link].
>>>>[Link](“Python is a fantastic language to use.\ extremely easy for
beginners to learn.\n”)

>>>>[Link]()
Now, if the file is opened, it will look like below.
hello! Python is a fantastic language to use.
Extremely easy for beginners to learn.

Note that the line starting with “extremely..” is printed in the second line—
this is due to the newline format “escape sequence” used while writing to the
file – ‘\n’. Several such escape sequences (a character preceded by \) defined
in the language can be used to format how the output appears in a file or any
other standard output.

Other common operations that can be performed on the file object are the
following:
In addition, predefined functions available in the “os” module, such as
renaming and deleting files can be used on os objects. In addition, Python
provides several API to achieve common file operations provided by Linux
commands such as mkdir to create a new directory or chdir to change
directory path, etc.

For example:
import os #imports the os module [Link](); # gives the current working
directory

Therefore, knowing how to use efficient files helps in writing many Python
scripts useful to any programmer every day.
Python is a programming language that possesses a number of charac‐
teristics that make it extremely appealing to programmers and develop‐ ers.
To begin, Python is a free programming language, which means that it is
accessible to anyone. Additionally, Python is an open-source language that
means that you can contribute to the source code if you so desire. Indeed,
Python is a language that is supported by a commu‐ nity that works
collaboratively to improve it via the internet. Python is a high-level
programming language.

This means that Python does not require compilation in the same way that
other programming languages such as C or C++, Fortran, and others do. This
also implies that Python's syntax is extremely simple to use and learn. These
characteristics enable Python programs to be developed, interpreted, and
maintained inexpensively. As a result, it enables efficient sharing and
collaboration in order to develop Pythonbased applications.

Python's simplicity of syntax and high-level programming does not imply


that it is a slow programming language. Indeed, Python is regarded as a
highly competitive and productive programming language. When compared
to other low-level programming languages that are well- known for their
speed, a Python script can be 3rd or 5th the size of a comparable C++ or
Java script.

Python does not require compilation, in addition to requiring less typing and
debugging. After developing a Python script, it can be run directly without
the need to compile or link to additional tools or libraries. Another aspect
that contributes to Python's appeal is its portability. Python is a portable
language that can be used in any operating envi‐ ronment or system without
modification.

Python code can be executed on Windows, UNIX / LINUX, Mac, large


servers, Android, or iOS tablets. Even graphical user interface applications
can be developed in a portable manner by utilizing Python's support for
portable options.

In contrast to other programming languages such as Java or C, Python


provides a dynamic typing environment. In Python, variables can be used
without prior declaration or type specification. Any variable can be used
without specifying its type, which simplifies code development.

One of Python's most appealing features is the libraries that come


preinstalled. These libraries, alternatively referred to as packages, are a
collection of code tools that enable the execution of basic and common
tasks. Python includes a standard library by default, which contains modules
such as the math module for mathematical and numerical programming.
Additionally, Python supports the use of third-party libraries.

There are numerous third-party packages available online that enable the use
of advanced tools for a particular domain (e.g. Numpy library for Numerical
programming with Python, Pandas, Matplotlib for devel‐ oping figures and
so on). Thus, when programming in Python, you have access to a large
number of tools and pre-coded and built-in objects that are readily available.
You never start from scratch because it is highly likely that the function you
wish to use has already been coded and made publicly available.

Python is a hybrid language in the sense that it is capable of integrating with


and being integrated with other programming languages. For example, you
can use pre-coded or compiled C or C++ libraries within Python.
Additionally, Python code can be invoked from C or C++ scripts. In general,
when you choose Python as the language for devel‐ oping your applications,
you gain the following advantages:

1. Simple syntax and minimal typing


2. A program that executes quickly
3. A portable and usable program that runs on any operating system
4. An easily maintainable and well-organized program
5. Never start from scratch with a plethora of ready-to-use packages and
codes
6. Integrated components that enable the execution of code written in C,
C++, or any other language in order to accelerate the execution of specific
sections of the code. These are some of the characteristics and benefits of
Python as a programming language.

This book will show you how to create basic programming structures, such
as loops. After that, you will learn about expressions, variables, and
operators. Additionally, you will examine novel data structures such as
tuples.

Additionally, you will learn how to create a variety of Python programs


using loops and control statements. Additionally, you will learn how to
manipulate data, as well as how to use the break and continue state‐ ments
effectively.

The topics are explained using a variety of examples and an attempt is made
to emphasize good Python programming practices. We hope you enjoy
reading and that you learn some new Python concepts.

[Link]

You might also like