Python For Beginners - Edward Thornton
Python For Beginners - Edward Thornton
EDWARD THORNTON
© Copyright 2021 - All rights reserved.
Contents
Introduction v
1. What Is Python? 1
2. Python Capabilities 16
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 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
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.
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.
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.
What is programming?
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.
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.
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.
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. 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.
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.
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.
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
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.
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.
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.
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.
I int; i=5;
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
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
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.
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.
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
Integration 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
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
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.
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!"
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.
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.
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
Loop
Python categories
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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."
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".
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”
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.
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.
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.
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.
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.
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.
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
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
X
x
my_dict
my_list9
UPPERCASE
lowercase
UPPERCASE_WITH_UNDERSCORES lowercase_with_underscores
CamelCase or CapWords
mixedCase
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
Variables by instance
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
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
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_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
def adder(x, y): """Function to get the sum of two numbers.""" return x + y
class Doc(obj): """ Explain function docstring.
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:
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
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.
Functions in Python
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.
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.
Fundamentals of functions
Example:
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.
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.
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:
Integer
Complex number Floating number
Example:
Parameters
The all () method accepts a single parameter:
Iterable- Any iterable (tuple, list, dictionary, etc.) which has the
elements.
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 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 () 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.
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.
Drawbacks of recursion
Recursive calls consume a lot of time and memory. Sometimes the logic of
recursion is difficult to follow.
Python lambda functions
The following is the syntax for the Python lambda function: Lambda
arguments: expression
Syntax
Python modules
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
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:
Example Start IDLE. Navigate to the File menu and click New Window.
Type the following:
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.
Example
Start IDLE.
Navigate to the File menu and click New Window.
Type the following:
Example
Start IDLE.
Navigate to the File menu and click New Window. Type the following:
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.
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.
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
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 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.
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.
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
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.
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.
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:
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.
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.
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:
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:
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?
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.
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:
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.
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
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:
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
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.
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
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:
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.
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.
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.
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:
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}
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.
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.
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.
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:
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.
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:
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.
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.
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.
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:
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.
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.
print(kitchen_item)
If you decide to print this code, the output will be as follows:
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.
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?
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:
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.
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,
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:
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:
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.
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:
Inserting elements
print(kitchen_item)
kitchen_item.insert(3, “spoon”)
print(kitchen_item)
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.
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:
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.
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:
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
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.
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:
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:
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:
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”)
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
0
2
4
6
8
10
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.
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
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.
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.
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.
# 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.
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:
You can also use the “discard ( )” method to delete specific items from a Set,
as shown in the example below:
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.
To delete the entire Set, the “del” keyword can be used, as shown below.
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.
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.
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.
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
Representation of string
Single-line strings
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:
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:
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:
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.
Whenever you are finished with a file, close them using the close() method.
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:
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:
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:
Most of the actions you perform on the file move the file pointer. For
example:
To move the file pointer to a position you desire, you can use the seek()
function.
For example:
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 >>> _
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:
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:
Writing to a file
When writing to a file, you must always remember that Python over‐ writes
and_not_insert_file.
For example:
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
To open/create a file
Sample code
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]()
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 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.
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.
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.
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]