Python Programming 3 Books in 1
Python Programming 3 Books in 1
Python Programming 3 Books in 1
PROGRAMMING
3 BOOKS IN 1
Learn machine learning, data science and
analysis with a crash course for beginners.
Included coding exercises for artificial
intelligence, Numpy, Pandas and Ipython.
JASON TEST
© Copyright 2020 - All rights reserved.
The content contained within this book may not be reproduced, duplicated or
transmitted without direct written permission from the author or the publisher.
Under no circumstances will any blame or legal responsibility be held against
the publisher, or author, for any damages, reparation, or monetary loss due to
the information contained within this book. Either directly or indirectly.
Legal Notice:
This book is copyright protected. This book is only for personal use. You cannot
amend, distribute, sell, use, quote or paraphrase any part, or the content within
this book, without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for educational
and entertainment purposes only. All effort has been executed to present
accurate, up to date, and reliable, complete information. No warranties of any
kind are declared or implied. Readers acknowledge that the author is not
engaging in the rendering of legal, financial, medical or professional advice. The
content within this book has been derived from various sources. Please consult a
licensed professional before attempting any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is the
author responsible for any losses, direct or indirect, which are incurred as a
result of the use of information contained within this document, including, but
not limited to, — errors, omissions, or inaccuracies.
TABLE OF CONTENTS
PYTHON FOR BEGINNERS
Introduction
1.Python code optimization with ctypes
2.Finding the Perfect Toolkit: Analyzing Popular Python Project Templates
3.How are broad integer types implemented in Python?
4.Create a bot in Python to learn English
5.The thermal imager on the Raspberry PI
6.Finding a Free Parking Space with Python
7.Creating games on the Pygame framework | Part 1
Creating games on the Pygame framework | Part 2
Creating games on the Pygame framework| Part 3
8.Object-Oriented Programming (OOP) in Python 3
Conclusion
JASON TEST
Introduction
Name
Motivating problem
Decision
Effects
Factory
Abstract factory
Builder
Prototype
Singleton
Object pool
Structural Patterns
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Behavioral patterns
Chain of responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
type checking:
expansion of the IDE functionality in terms of
providing information about the expected types of
arguments and the type of return value for functions:
overload of functions and work with generics:
interaction with other languages:
use in predicate logical functions:
mapping of requests in databases:
marshaling parameters in RPC (remote procedure
call)
1. Basic optimizations
2. Styles
3. Python compilation
4. Structures in Python
5. Call your code in C
6. Pypy
O3 maximizes optimization:
And now we will begin to write Python code using the
resulting shared object file .
Structures in Python Below are two data
structures that are used in my C code.
And here is the translation of these structures into Python.
A few notes:
In C,
if you try to calculate 220,000 using the built-in function
powl, you will get the output inf.
But
in Python, making this easier than ever is easy: It must be
under the hood that Python is doing something very
beautiful, and today we will find out the exactly what it does
to work with integers of arbitrary size!
Presentation and Definition Integer in Python,
this is a C structure defined as follows:
ob_size like 3
ob_digit like [0, 0, 1]
We created a demo REPL that will show how Python stores
an integer inside itself, and also refers to structural
members such as ob_size, ob_refcountetc.
Integer Long Operations Now that we have a
pure idea of how Python implements integers
of arbitrary precision, it is time to understand
how various mathematical operations are
performed with them.
Addition Integers are stored "in numbers,"
which means that addition is as simple as in
elementary school, and the Python source code
shows us that this is how addition is
implemented. A function with a name x_add in
a file longobject.c adds two numbers.
N o,write
this is not one of the hundreds of articles on how to
your first Hello World bot in Python. Here you will
not find detailed instructions on how to get an API token in
BotFather or launch a bot in the cloud. In return, we will
show you how to unleash the full power of Python to the
maximum to achieve the most aesthetic and beautiful code.
We perform a song about the appeal of complex structures -
we dance and dance. Under the cut asynchrony, its system
of saves, a bunch of useful decorators, and a lot of beautiful
code.
Disclaimer : People with brain OOP and adherents of the
“right” patterns may ignore this article.
Idea To understanding what it is like not to
know English in modern society, imagine that
you are an 18th-century nobleman who does
not know French. Even if you are not very well
versed in history, you can still imagine how
hard it would be to live under such
circumstances. In the modern world, English
has become a necessity, not a privilege,
especially if you are in the IT industry.
The project is based on the catechism of the future: the
development of a neural network as a separate unit, and
education, which is based on games and sports spirit.
Isomorphic paradigms have been hanging in the air since
ancient times, but it seems that over time, people began to
forget that the most straightforward solutions are the most
effective.
Here is a shortlist of the basic things I want to put together:
Be able to work with three user dictionaries
Ability to parse youtube video/text, and then add
new words to the user's dictionary
Two basic skills training modes
Flexible customization: full control over user
dictionaries and the environment in general
Built-in admin panel
Naturally, everything should work quickly, with the ability
to easily replenish existing functionality in the future.
Putting it all together, I thought that the best embodiment
of my idea into reality would be a Telegram bot. My tale is
not about how to write handlers for the bot correctly - there
are dozens of such articles, and this is simple mechanical
work. I want the reader to learn to ignore the typical
dogmas of programming. Use what is profitable and
effective here and now.
“I learned to let out the cries of unbelievers past my ears
because it was impossible to suppress them.”
self._counter = 0
self.CACHE SIZE = cache st ze def add (self, d s: class,
file: str) -> NDne:
All or's to fasten a class to a sa ver
+ cls - Inst an ce of the class + file - The fi1 e the
instari ce is 'orking with self._cache_files.append (file)
self._cl asses.append (cls) if fi1e i s eotptl’ (fi1e): return
hDne 1 ogger. opt d an.' = True) .debug (fT or {cl s . class
names) file (file) is not empty' ') fa data in sells oad (file) :
is.save nDn Caclti ng (data) cl ear_file (file) sel
f._counter = 0
norm
= up.nint8 ((f, 100 - Twin) • 255, (Tmax-Tmin)) norm.shy = (24.32) T n = 40
Tmin = 20
Results The script polls the thermal imaging
matrix and outputs the frames to the monitor
console on which the Raspberry PI is
connected, four times per second. This is
enough not to experience significant
discomfort when shooting objects. To visualize
the frame, the OpenCV package is used. When
the “s” button is pressed, the thermal imaging
“heat maps” in jpg format are saved in the
folder with the script.
For more information, I deduced the minimum and
maximum temperatures on the frame. That is, looking at the
color, you can see what approximately the temperature of
the most heated or chilled objects. The measurement error
is approximately a degree with a larger side. The thermal
range is set from 20 to 40 degrees. Exit the script by
pressing Ctrl + C.
The script works approximately the same on both the
Raspberry Pi Zero W and the Pi 3 B +. I installed the VNC
server on the smartphone. Thus, picking up raspberries
connected to a power bank and a smartphone with VNC
running, you can get a portable thermal imager with the
ability to save thermal images. Perhaps this is not entirely
convenient, but quite functional.
After the first start, an incorrect measurement of the
maximum temperature is possible. In this case, you need to
exit the script and rerun it.
That is all for today. The experiment with a home-made
thermal imager turned out to be successful. With the
helping of this device, it is quite possible to conduct a
thermal imaging inspection of the house on your own, for
example.
Due to the lower temperature contrast than indoors, the
pictures were not very informative. In the photo above, the
whole house is on two sides. On the bottom - photos of
different windows.
In the code, I changed only the temperature range.
Instead of +20 ... + 40, I set -10 ... + 5.
6. FINDING A FREE PARKING SPACE
WITH PYTHON
I live in a proper city. But, like in many others, the search for
a parking space always turns into a test. Free spaces
quickly occupy, and even if you have your own, it will be
difficult for friends to call you because they will have
nowhere to park.
So I decided to point the camera out the window and use
deep learning so that my computer tells me when the space
is available: It may sound complicated, but writing a
working prototype with deep learning is quick and easy. All
the necessary components are already there - you just need
to know where to find them and how to put them together.
So let's have some fun and write an accurate free parking
notification system using Python and deep learning
Decomposing the task When we have a difficult task that we
want to solve with the help of machine learning, the first
step is to break it down into a sequence of simple tasks.
Then we can use various tools to solve each of them. By
combining several simple solutions, we get a system that is
capable of something complex.
Here is how I broke my task: The video stream from the
webcam directed to the window enters the conveyor input:
Through the pipeline, we will transmit each frame of the
video, one at a time.
The first point is to recognize all the possible parking
spaces in the frame. Before we can look for unoccupied
places, we need to understand in which parts of the image
there is parking.
Then on each frame you need to find all the cars. This will
allow us to track the movement of each machine from frame
to frame.
The third step is to determine which places are occupied
by machines and which are not. To do this, combine the
results of the first two steps.
Finally, the program should send an alert when the
parking space becomes free. This will be determined by
changes in the location of the machines between the frames
of the video.
Each of the step can be completed in different ways using
different technologies. There is no single right or wrong way
to compose this conveyor: different approaches will have
their advantages and disadvantages. Let's deal with each
step in more detail.
Review of exercises (# 2)
Exercise: "Legacy of the dogs"
Create a Petsclass that contains dog instances: this class
is completely separate from the Dogclass. In other words, a
Dogclass is not inherited from the Petsclass. Then assign
three instances of the dog to the Petsclass instance . Start
with the following code below. Save the file as pets_class.py
. Your output should look like this:
Start Code:
Solution: “Dog Inheritance”
1. What class?
2. What an example?
3. What is the relationship between class and
instance?
4. What Python syntax is used to define a new
class?
5. What is the spelling convention for a class
name?
6. How do you create or create an instance of a
class?
7. How do you access the attributes and behavior
of an instance of a class?
8. What kind of method?
9. What is the purpose self?
10.
What is the purpose of the init method?
11.
Describe how inheritance helps prevent code
duplication.
12.
Can child classes override the properties of
their parents?
Solution: “Test of understanding” Show hide
JASON TEST
Introduction
ata Science has been very popular over the last couple of years. The main
D focus of this sector is to incorporate significant data into business and
marketing strategies that will help a business expand. And get to a logical
solution, the data can be stored and explored. Originally only the leading IT
corporations were engaged throughout this field, but today information
technology is being used by companies operating in different sectors and fields
such as e-commerce, medical care, financial services, and others. Software
processing programs such as Hadoop, R code, SAS, SQL, and plenty more are
available. Python is, however, the most famous and easiest to use data and
analytics tools. It is recognized as the coding world's Swiss Army Knife since it
promotes structured coding, object-oriented programming, the operational
programming language, and many others. Python is the most widely used
programming language in the world and is also recognized as the most high -
level language for data science tools and techniques, according to the 2018
Stack Overflow study.
In the Hacker rank 2018 developer poll, which is seen in their love-hate
ranking, Python has won the developer's hearts. Experts in data science expect
to see an increase in the Python ecosystem, with growing popularity. And
although your journey to study Python programming may just start, it's nice to
know that there are also plentiful (and increasing) career options.
Data analytics Python programming is extensively used and, along with being
a flexible and open-source language, becomes one of the favorite programming
languages. Its large libraries are used for data processing, and even for a
beginner data analyst, they are very easy to understand. Besides being open-
source, it also integrates easily with any infrastructure that can be used to fix
the most complicated problems. It is used by most banks for data crunching,
organizations for analysis and processing, and weather prediction firms such as
Climate monitor analytics often use it. The annual wage for a Computer Scientist
is $127,918, according to Indeed. So here's the good news, the figure is likely to
increase. IBM's experts forecast a 28 percent increase in data scientists'
demands by 2020. For data science, however, the future is bright, and Python is
just one slice of the golden pie. Luckily mastering Python and other principles of
programming are as practical as ever.
DATA SCIENCE AND ITS SIGNIFICANCE
Data Science has come a long way from the past few years, and thus, it
becomes an important factor in understanding the workings of multiple
companies. Below are several explanations that prove data science will still be
an integral part of the global market.
1. The companies would be able to understand their client in a more efficient
and high manner with the help of Data Science. Satisfied customers form the
foundation of every company, and they play an important role in their successes
or failures. Data Science allows companies to engage with customers in the
advance way and thus proves the product's improved performance and strength.
2. Data Science enables brands to deliver powerful and engaging visuals.
That's one of the reasons it's famous. When products and companies make
inclusive use of this data, they can share their experiences with their audiences
and thus create better relations with the item.
3. Perhaps one Data Science's significant characteristics are that its results
can be generalized to almost all kinds of industries, such as travel, health care,
and education. The companies can quickly determine their problems with the
help of Data Science, and can also adequately address them
4. Currently, data science is accessible in almost all industries, and nowadays,
there is a huge amount of data existing in the world, and if used adequately, it
can lead to victory or failure of any project. If data is used properly, it will be
important in the future to achieve the product 's goals.
5. Big data is always on the rise and growing. Big data allows the enterprise to
address complicated Business, human capital, and capital management
problems effectively and quickly using different resources that are built
routinely.
6. Data science is gaining rapid popularity in every other sector and therefore
plays an important role in every product's functioning and performance. Thus,
the data scientist's role is also enhanced as they will conduct an essential
function of managing data and providing solutions to particular issues.
7. Computer technology has also affected the supermarket sectors. To
understand this, let's take an example the older people had a fantastic
interaction with the local seller. Also, the seller was able to meet the customers'
requirements in a personalized way. But now this attention was lost due to the
emergence and increase of supermarket chains. But the sellers are able to
communicate with their customers with the help of data analytics.
8. Data Science helps companies build that customer connection. Companies
and their goods will be able to have a better and deeper understanding of how
clients can utilize their services with the help of data science.
Data Technology Future: Like other areas are continually evolving, the
importance of data technology is increasingly growing as well. Data science
impacted different fields. Its influence can be seen in many industries, such as
retail, healthcare, and education. New treatments and technologies are being
continually identified in the healthcare sector, and there is a need for quality
patient care. The healthcare industry can find a solution with the help of data
science techniques that helps the patients to take care with. Education is
another field where one can clearly see the advantage of data science. Now the
new innovations like phones and tablets have become an essential characteristic
of the educational system. Also, with the help of data science, the students are
creating greater chances, which leads to improving their knowledge.
Data Science Life Cycle:
Data Structures
A data structure may be selected in computer programming or designed to
store data for the purpose of working with different algorithms on it. Every other
data structure includes the data values, data relationships, and functions
between the data that can be applied to the data and information.
Features of data structures
Sometimes, data structures are categorized according to their characteristics.
Possible functions are:
Linear or non-linear: This feature defines how the data objects are
organized in a sequential series, like a list or in an unordered
sequence, like a table.
Homogeneous or non-homogeneous: This function defines how all
data objects in a collection are of the same type or of different kinds.
Static or dynamic: This technique determines to show to assemble
the data structures. Static data structures at compilation time have
fixed sizes, structures, and destinations in the memory. Dynamic
data types have dimensions, mechanisms, and destinations of
memory that may shrink or expand depending on the application.
Data structure Types
Types of the data structure are determined by what sorts of operations will be
needed or what kinds of algorithms will be implemented. This includes:
Arrays: An array stores a list of memory items at adjacent locations.
Components of the same category are located together since each element's
position can be easily calculated or accessed. Arrays can be fixed in size or
flexible in length.
Stacks: A stack holds a set of objects in linear order added to operations. This
order may be past due in first out (LIFO) or first-out (FIFO).
Queues: A queue stores a stack-like selection of elements; however, the
sequence of activity can only be first in the first out. Linked lists: In a linear
order, a linked list stores a selection of items. In a linked list, every unit or node
includes a data item as well as a reference or relation to the next element in the
list.
Trees: A tree stocks an abstract, hierarchical collection of items. Each node is
connected to other nodes and can have several sub-values, also known as a
child.
Graphs: A graph stores a non-linear design group of items. Graphs consist of a
limited set of nodes, also called vertices, and lines connecting them, also known
as edges. They are useful for describing processes in real life, such as networked
computers.
Tries: A tria or query tree is often a data structure that stores strings as data
files, which can be arranged in a visual graph.
Hash tables: A hash table or hash chart is contained in a relational list that
labels the keys to variables. A hash table uses a hashing algorithm to transform
an index into an array of containers containing the desired item of data. These
data systems are called complex because they can contain vast quantities of
interconnected data. Examples of primal, or fundamental, data structures are
integer, float, boolean, and character.
Utilization of data structures
Data structures are generally used to incorporate the data types in physical
forms. This can be interpreted into a wide range of applications, including a
binary tree showing a database table. Data structures are used in the
programming languages to organize code and information in digital storage.
Python databases and dictionaries, or JavaScript array and objects, are popular
coding systems used to gather and analyze data. Also, data structures are a
vital part of effective software design. Significance of Databases Data systems is
necessary to effectively handle vast volumes of data, such as data stored in
libraries, or indexing services.
Accurate data configuration management requires memory allocation
identifier, data interconnections, and data processes, all of which support the
data structures. In addition, it is important to not only use data structures but
also to select the correct data structure for each assignment.
Choosing an unsatisfactory data structure could lead to slow running times or
disoriented code. Any considerations that need to be noticed when choosing a
data system include what type of information should be processed, where new
data will be put, how data will be organized, and how much space will be
allocated for the data.
PYTHON BASICS
ou can get all the knowledge about the Python programming language in 5
Y simple steps.
Step 1: Practice Basics in Python It all starts somewhere. This first step is
where the basics of programming Python will be learned. You are always going
to want an introduction to data science. Jupyter Notebook, which comes pre-
portioned with Python libraries to help you understand these two factors, which
make it one of the essential resources which you can start using early on your
journey.
Step 2: Try practicing Mini-Python Projects We strongly believe in learning
through shoulders-on. Try programming stuff like internet games, calculators, or
software that gets Google weather in your area. Creating these mini-projects can
help you understand Python. Projects like these are standard for any coding
languages, and a fantastic way to strengthen your working knowledge. You will
come up with better and advance API knowledge, and you will continue site
scraping with advanced techniques. This will enable you to learn Python
programming more effectively, and the web scraping method will be useful to
you later when collecting data.
Stage 3: Learn Scientific Libraries on Python Python can do anything with
data. Pandas, Matplotliband, and NumPyare are known to be the three best used
and most important Python Libraries for data science. NumPy and Pandas are
useful for data creation and development. Matplotlib is a library for analyzing
the data, creating flow charts and diagrams as you would like to see in Excel or
Google Sheets.
Stage 4: Create a portfolio A portfolio is an absolute need for professional data
scientists. These projects must include numerous data sets and leave important
perspectives to readers that you have gleaned. Your portfolio does not have a
specific theme; finding datasets that inspire you, and then finding a way to place
them together. Showing projects like these provide some collaboration to fellow
data scientists, and demonstrates future employers that you have really taken
the chance to understand Python and other essential coding skills. Some of the
good things about data science are that, while showcasing the skills you've
learned, your portfolio serves as a resume, such as Python programming.
Step 5: Apply Advanced Data Science Techniques Eventually, the target is to
strengthen your programming skills. Your data science path will be full of
continuous learning, but you can accomplish specialized tutorials to make sure
you have specialized in the basic programming of Python. You need to get
confident with clustering models of regression, grouping, and k-means. You can
also leap into machine learning-using sci-kit lessons to bootstrap models and
create neural network models. At this point, developer programming could
include creating models using live data sources. This type of machine learning
technique adjusts s its assumptions over time.
Standard Library
The Python Standard library consists of Python's precise syntax, token, and
semantic. It comes packaged with deployment core Python. When we started
with an introduction, we referenced this. It is written in C and covers features
such as I / O and other core components. Together all of the versatility renders
makes Python the language it is. At the root of the basic library, there are more
than 200 key modules. Python ships that library. But aside from this library, you
can also obtain a massive collection of several thousand Python Package Index
(PyPI) components.
1. Matplotlib
‘Matplotlib’ helps to analyze data, and is a library of numerical plots. For
Data Science, we discussed in Python.
2. Pandas
‘Pandas’ is a must for data-science as we have said before. It provides easy,
descriptive, and versatile data structures to deal with organized (tabulated,
multilayered, presumably heterogeneous) and series data with ease (and
fluidly).
3. Requests
‘Requests’ is a Python library that allows users to upload HTTP/1.1 requests,
add headers, form data, multipart files, and simple Python dictionary
parameters. In the same way, it also helps you to access the response data.
4. NumPy
It has basic arithmetic features and a rudimentary collection of scientific
computing.
5. SQLAlchemy
It has sophisticated mathematical features, and SQLAlchemy is a basic
mathematical programming library with well-known trends at a corporate
level. It was created to make database availability efficient and high-
performance.
6. BeautifulSoup
This may be a bit on the slow side. BeautifulSoup seems to have a superb
library for beginner XML- and HTML- parsing.
7. Pyglet
Pyglet is an outstanding choice when designing games with an object-
oriented programming language interface. It also sees use in the
development of other visually rich programs for Mac OS X, Windows, and
Linux in particular. In the 90s, they turned to play Minecraft on their PCs
whenever people were bored. Pyglet is the mechanism powering Minecraft.
8. SciPy
Next available is SciPy, one of the libraries we spoke about so often. It does
have a range of numerical routines that are user-friendly and effective. Those
provide optimization routines and numerical integration procedures.
9. Scrapy
If your objective is quick, scraping at the high-level monitor and crawling the
network, go for Scrapy. It can be used for data gathering activities for
monitoring and test automation.
10. PyGame
PyGame offers an incredibly basic interface to the system-independent
graphics, audio, and input libraries of the Popular Direct Media Library (SDL).
12. Pillow
Pillow is a PIL (Python Imaging Library) friendly fork but is more user efficient.
Pillow is your best friend when you're working with pictures.
13. pywin32
As the name suggests, this gives useful methods and classes for interacting
with Windows.
14. wxPython
For Python, it's a wrapper around wxWidgets.
15. iPython
iPython Python Library provides a parallel distributed computing architecture.
You will use it to create, run, test, and track parallel and distributed
programming.
16. Nose
The nose provides alternate test exploration and test automation running
processes. This intends to mimic the behavior of the py.test as much as
possible.
17. Flask
Flask is a web framework, with a small core and several extensions.
18. SymPy
It is a library of open-source symbolic mathematics. SymPy is a full-fledged
Computer Algebra System (CAS) with a very simple and easily understood
code that is highly expandable. It is implemented in python, and therefore,
external libraries are not required.
19. Fabric
As well as being a library, Fabric is a command-line tool to simplify the use of
SSH for installation programs or network management activities. You can run
local or remote command line, upload/download files, and even request input
user going, or abort activity with it.
20. PyGTK
PyGTK allows you to create programs easily using a Python GUI (Graphical
User Interface).
Bitwise operators
Bitwise operators operate as if they became binary-digit strings on operands.
Bit by bit they work, and therefore the name. For example, in binary two is10,
and in binary seven is 111.
Assignment operators
Python language’s assignment operators are used to assign values to the
variables. a = 5 is a simple task operator assigning ‘a’ value of 5 to the right of
the variable ‘a’ to the left. In Python, there are various compound operators
such as a + = 5, which adds to the variable as well as assigns the same later.
This equals a= a + 5.
Special operators
Python language gives other different types of operators, such as the operator
of the identity or the operator of membership. Examples of these are mentioned
below.
Identity operators
‘Is’ and ‘is not’ are Python Identity Operators. They are used to test if there
are two values or variables in the same memory section. Two equal variables do
not mean they are equivalent.
Membership operator
The operators that are used to check whether or not there exists a
value/variable in the sequence such as string, list, tuples, sets, and dictionary.
These operators return either True or False if a variable is found in the list, it
returns True, or else it returns False Expressions
An expression is a mix of values, variables, operators, and function calls.
There must be an evaluation of the expressions. When you ask Python to print a
phrase, the interpreter will evaluate the expression and show the output.
Arithmetic conversions
Whenever an arithmetic operator interpretation below uses the phrase "the
numeric arguments are converted to a common type," this means the execution
of the operator for the built-in modes operates as follows
If one argument is a complex quantity, then the other is converted to a complex
number; If another argument is a floating-point number, the other argument is
transformed to a floating-point; Or else both will be integers with no need for
conversion.
Atoms
Atoms are the most important expressional components. The smallest atoms
are literals or abstract identities. Forms contained in parentheses, brackets, or
braces are also syntactically known as atoms. Atoms syntax is: atom ::=
identifier | enclosure| literal enclosure ::= list_display| parenth_form| dict_display
| set_display Identifiers (Names)
A name is an identifier that occurs as an atom. See section Lexical Description
Identifiers and Keywords and group Naming and binding for naming and binding
documents. Whenever the name is connected to an entity, it yields the entity by
evaluating the atom. When a name is not connected, an attempt to assess it
elevates the exception for NameError.
Literals
Python provides logical string and bytes and numerical literals of different
types: literal::= string literal | bytes literal | integer | float number | image
number Assessment of a literal yield with the predicted set an object of that
type (bytes, integer, floating-point number, string, complex number). In the
scenario of floating-point and imaginary (complex) literals, the value can be
approximated.
Parenthesized forms
A parenthesized type is an available set of parentheses for the expression:
parenth_form ::= "(" [starred_expression] ")"
A list of parenthesized expressions yields whatever the list of expressions
produces: if the list includes at least one comma, it produces a tuple. If not, it
yields the sole expression that forms up the list of expressions. A null pair of
parentheses generates an incomplete object of tuples. As all tuples are
immutable, the same rules would apply as for literals (i.e., two empty tuple
occurrences does or doesn't yield the same entity).
Displays for lists, sets, and dictionaries For the construction of a list,
Python uses a series or dictionary with a particular syntax called
"displays," each in complementary strands:
The contents of the container are listed explicitly, or They are
calculated using a series of instructions for looping and filtering,
named a 'comprehension.' Common features of syntax for
comprehensions are: comprehension ::=
assignment_expressioncomp_for comp_for ::= ["async"] "for" target_list
"in" or_test [comp_iter]
comp_iter ::= comp_for | comp_if comp_if ::= "if" expression_nocond
[comp_iter]
A comprehension contains one single sentence ready for at least one
expression for clause, and zero or more for or if clauses. Throughout this
situation, the components of the container are those that will be generated by
assuming each of the for or if clauses as a block, nesting from left to right, and
determining the phase for creating an entity each time the inner core block is
approached.
List displays
A list view is a probably empty sequence of square brackets including
expressions: list_display ::= "[" [starred_list | comprehension] "]"
A list display generates a new column object, with either a list of expressions
or a comprehension specifying the items. When a comma-separated database of
expressions is provided, its elements are assessed from left to right and
positioned in that order in the category entity. When Comprehension is provided,
the list shall be built from the comprehension components.
Set displays
Curly braces denote a set display and can be distinguished from dictionary
displays by the lack of colons dividing data types: set_display ::= "{"
(starred_list | comprehension) "}"
A set show offers a new, mutable set entity, with either a series of expressions
or a comprehension defining the contents. When supplied with a comma-
separated list of expressions, its elements are evaluated from left to right and
assigned to the set entity. Whenever a comprehension is provided, the set is
formed from the comprehension-derived elements. Unable to build an empty set
with this {}; literal forms a blank dictionary.
Dictionary displays
A dictionary view is a potentially empty sequence of key pairs limited to curly
braces: dict_display ::= "{" [key_datum_list | dict_comprehension] "}"
key_datum_list ::= key_datum ("," key_datum)* [","]
key_datum ::= expression ":" expression | "**" or_expr dict_comprehension ::=
expression ":" expression comp_for The dictionary view shows a new object in
the dictionary. When a comma-separated series of key / datum pairs is provided,
they are analyzed from left to right to identify dictionary entries: each key entity
is often used as a key to hold the respective datum in the dictionary. This implies
you can clearly state the very same key numerous times in the key /datum
catalog, but the last one given will become the final dictionary's value for that
key.
Generator expressions
A generator expression is the compressed syntax of a generator in the
parenthesis : generator_expression ::= "(" expression comp_for ")"
An expression generator produces an entity that is a new generator. Its syntax
will be the same as for comprehensions, except for being enclosed in brackets or
curly braces rather than parentheses. Variables being used generator expression
are assessed sloppily when the generator object (in the same style as standard
generators) is called by the __next__() method. Conversely, the iterate-able
expression in the leftmost part of the clause is evaluated immediately, such that
an error that it produces is transmitted at the level where the expression of the
generator is characterized, rather than at the level where the first value is
recovered.
For instance: (x*y for x in range(10) for y in range(x, x+10)).
Yield expressions
yield_atom ::= "(" yield_expression ")"
yield_expression ::= "yield" [expression_list | "from" expression]
The produced expression is used to define a generator function or async
generator function, and can therefore only be used in the function definition
body. Using an expression of yield in the body of a function tends to cause that
function to be a generator, and to use it in the body of an asynchronous def
function induces that co-routine function to become an async generator. For
example: def gen(): # defines a generator function yield 123
asyncdefagen(): # defines an asynchronous generator function yield 123
Because of their adverse effects on the carrying scope, yield expressions are
not allowed as part of the impliedly defined scopes used to enforce
comprehensions and expressions of generators.
Input and Output of Data in Python Python
Output Using print() function To display data
into the standard display system (screen), we
use the print() function. We may issue data to a
server as well, but that will be addressed later.
Below is an example of its use.
>>>>print('This sentence is output to the screen') Output:
This sentence is output to the screen Another example is given:
a=5
print('The value of a is,' a) Output:
The value of a is 5
Within the second declaration of print(), we will note that space has been
inserted between the string and the variable value a. By default, it contains this
syntax, but we can change it.
The actual syntax of the print() function will be: print(*objects, sep=' ',
end='\n', file=sys.stdout, flush=False) Here, the object is the value(s) that will
be printed. The sep separator between values is used. This switches into a
character in space. Upon printing all the values, the finish is printed. It moves
into a new section by design. The file is the object that prints the values, and its
default value is sys.stdout (screen). Below is an example of this.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*') print(1, 2, 3, 4, sep='#', end='&') Run code
Output:
1234
1*2*3*4
1#2#3#4& Output formatting
Often we want to style our production, so it looks appealing. It can be done
using the method str.format(). This technique is visible for any object with a
string.
>>> x = 5; y = 10
>>>print('The value of x is {} and y is {}'.format(x,y)) Here the value of x is
five and y is 10
Here, they use the curly braces{} as stand-ins. Using numbers (tuple index),
we may specify the order in which they have been printed.
print('I love {0} and {1}'.format('bread','butter')) print('I love {1} and
{0}'.format('bread','butter')) Run Code
Output:
I love bread and butter
I love butter and bread
People can also use arguments with keyword to format the string.
>>>print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name
= 'John')) Hello John, Goodmorning
Unlike the old sprint() style used in the C programming language, we can also
format strings. To accomplish this, we use the ‘%’ operator.
>>> x = 12.3456789
>>>print('The value of x is %3.2f' %x) The value of x is 12.35
>>>print('The value of x is %3.4f' %x) The value of x is 12.3457
Python Indentation
Indentation applies to the spaces at the start of a line of the compiler.
Whereas indentation in code is for readability only in other programming
languages, but the indentation in Python is very important. Python supports the
indent to denote a code block.
Example
if 5 > 2:
print("Five is greater than two!") Python will generate an error message if you
skip the indentation: Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!") Python Input
Our programs have been static. Variables were described or hard-coded in the
source code. We would want to take the feedback from the user to allow
flexibility. We have the input() function in Python to enable this. input() is syntax
as: input([prompt])
While prompt is the string we want to show on the computer, this is optional.
>>>num = input('Enter a number: ') Enter a number: 10
>>>num
'10'
Below, we can see how the value 10 entered is a string and not a number. To
transform this to a number we may use the functions int() or float().
>>>int('10')
10
>>>float('10')
10.0
The same method can be done with the feature eval(). Although it takes eval
much further. It can even quantify expressions, provided that the input is a
string >>>int('2+3')
Traceback (most recent call last): File "<string>", line 301, in runcode File "
<interactive input>", line 1, in <module> ValueError: int() base 10 invalid
literal: '2+3'
>>>eval('2+3')
5
Python Import
As our software gets larger, splitting it up into separate modules is a smart
idea. A module is a file that contains definitions and statements from Python.
Python packages have a filename, and the .py extension begins with it.
Definitions may be loaded into another module or to the integrated Python
interpreter within a module. To do this, we use the keyword on import.
For instance, by writing the line below, we can import the math module:
import math
We will use the module as follows: import math
print(math.pi)
Run Code
Output
3.141592653589793
So far, all concepts are included in our framework within the math module.
Developers can also only import certain particular attributes and functions,
using the keyword.
For instance:
>>>from math import pi >>>pi
3.141592653589793
Python looks at multiple positions specified in sys.path during the import of a
module. It is a list of positions in a directory.
>>> import sys
>>>sys.path
['',
'C:\\Python33\\Lib\\idlelib', 'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
We can insert our own destination to that list as well.
FUNCTIONS
1. Built-in functions, including help() to ask for help, min() to just get
the minimum amount, print() to print an attribute to the terminal.
More of these functions can be found here.
2. User-Defined Functions (UDFs) that are functions created by users to
assist and support them out;
3. Anonymous functions, also labeled lambda functions since they are
not defined with the default keyword.
Defining A Function: User Defined Functions (UDFs) The following
four steps are for defining a function in Python:
1. Keyword def can be used to declare the function and then use the
function name to backtrack.
2. Add function parameters: They must be within the function
parentheses. Finish off your line with a colon.
3. Add statements which should be implemented by the functions.
When the function should output something, end your function with a return
statement. Your task must return an object None without return declaration.
Example: 1. def hello():
2. print("Hello World")
3.return
It is obvious as you move forward, the functions will become more complex:
you can include for loops, flow control, and more to make things more fine-
grained: def hello(): name = str(input("Enter your name: ")) if name:
print ("Hello " + str(name)) else:
print("Hello World")
return
hello()
In the feature above, you are asking the user to give a name. When no name
is provided, the 'Hello World' function will be printed. Otherwise, the user will
receive a custom "Hello" phrase. Also, consider you can specify one or more
parameters for your UDFs function. When you discuss the segment Feature
Statements, you will hear more about this. Consequently, as a result of your
function, you may or may not return one or more values.
The return Statement
Note that since you're going to print something like that in your hello) (UDF,
you don't really have to return it. There'll be no distinction between the above
function and this one: Example:
1. defhello_noreturn():
2. print("Hello World")
Even so, if you'd like to keep working with the result of your function and try a
few other functions on it, you'll need to use the return statement to simply
return a value, like a string, an integer. Check out the following scenario in which
hello() returns a "hello" string while the hello_noreturn() function returns None:
1. def hello():
2. print("Hello World") 3. return("hello") 4. defhello_noreturn(): 5. print("Hello
World") 6. # Multiply the output of `hello()` with 2
7. hello() * 2
8. # (Try to) multiply the output of `hello_noreturn()` with 2
9. hello_noreturn() * 2
The secondary part gives you an error because, with a None, you cannot
perform any operations. You will get a TypeError that appears to say that
NoneType (the None, which is the outcome of hello_noreturn()) and int (2)
cannot do the multiplication operation. Tip functions leave instantly when a
return statement is found, even though that means they will not return any
result: 1. def run():
2. for x in range(10):
3. if x == 2:
4. return
5. print("Run!")
6. run()
Another factor worth noting when dealing with the ‘return expression’ is many
values can be returned using it. You consider making use of tuples for this.
Recall that this data structure is very comparable to a list's: it can contain
different values. Even so, tuples are immutable, meaning you can't alter any
amounts stored in it! You build it with the aid of dual parentheses). With the
assistance of the comma and the assignment operator, you can disassemble
tuples into different variables.
Read the example below to understand how multiple values can be returned
by your function: 1. # Define `plus()`
2. def plus(a,b):
3.sum = a + b
4.return (sum, a)
5. # "Translate" to a UDF
6. def sum(x, y):
7. returnx+y
When you need a function with no name for a short interval of time, you
utilize anonymous functions and this is generated at runtime. Special contexts
where this is important are when operating with filter(), map() and redu():
0.0 4.5
Clash of Clans USD 2130805
0.0 4.5
Temple Run USD 1724546
0.0 4.5
Pandora – Music USD 1126879
& Radio
0.0 4.0
Facebook USD 2974676
0.0 3.5
Every value is a data point in the table. The first row (just after titles of the
columns) for example has 5 data points:
Facebook
0.0
USD
2974676
3.5
Dataset consists of a collection of data points. We can consider the above
table as a list of data points. Therefore we consider the entire list a dataset. We
can see there are five rows and five columns to our data set.
Utilizing our insight of the Python types, we could perhaps consider we can
store each data point in their own variable — for example, here's how we can
store the data points of the first row: Above, we stored:
To locate a list element index rapidly, determine its location number in the list
and then subtract it by 1. The string 'USD,' for instance, is the third item in the
list (stance number 3), well its index number must be two because 3 – 1 = 2.
The index numbers enable us to locate a single item from a list. Going
backward through the list row 1 from the example above, by executing code row
1[0], we can obtain the first node (the string 'Facebook') of index number 0.
The Model list_name[index number] follows the syntax for locating specific list
components. For example, the title of our list above is row_1 and the index
number of a first element is 0, we get row_1[0] continuing to follow the
list_name[index number] model, in which the index number 0 is in square
brackets just after the name of the variable row_1.
2422346.3333333335
Using Negative Indexing with Lists
There are two indexing systems for lists in Python:
Note that when we use an index number just outside of the scope of the two
indexing schemes, we are going to have an IndexError.
How about using negative indexing to remove from each of the top 3 rows the
user rating (the very last value) and afterwards average it.
row_1 [-1]=rating_1
row_2[-1]=rating_2
row_3[-1]=rating_3
rating_1 + rating_2 + rating_3=total_rating total_rating / 3= average_rating
print(average)
2422346.33333
Slice Python Lists
Rather than selecting the list elements separately, we can pick two
consecutive elements using a syntax shortcut: While selecting the first n
elements from a list called a list (n stands for a number), we can use the list
syntax shortcut [0: n]. In the above example, we had to choose from the list row
3 the first three elements, so we will use row 3[0:3].
When the first three items were chosen, we sliced a portion of the set. For this
function, the collection method for a section of a list is known as list slicing.
List slice can be done in many ways: Retrieving any list slice we need:
When we want to choose the 1st or last ‘x’ elements (x represents a number),
we may use even less complex shortcuts for syntax: a_list[:x] when we need to
choose the first x elements.
a_list[-x:] when we need to choose the last x elements.
See how we retrieve from the first row the first four elements (with Facebook
data): first_4_fb = row_1[:4]
print(first_4_fb)
['Facebook', 0.0, 'USD', 2974676]
From the same row, the last three elements are: last_3_fb = row_1[-3:]
print(last_3_fb)
['USD', 2974676, 3.5]
In the fifth row (data in the row for Pandora) with elements third and fourth
are: pandora_3_4 = row_5[2:4]
print(pandora_3_4)
['USD', 1126879]
Python List of Lists
Lists were previously introduced as a viable approach to using one variable
per data point. Rather than having a different variable for any of the five
'Facebook' data points, 0.0, 'USD,' 2974676, 3.5, we can connect the data points
into a list together and then save the list in a variable.
We have worked with a data set of five rows since then and have stored each
row as a collection in each different variable (row 1, row 2, row 3, row 4, and row
5 variables). Even so, if we had a data set of 5,000 rows, we would probably
have ended up with 5,000 variables that will create our code messy and nearly
difficult to work with.
To fix this issue, we may store our five variables in a unified list: As we're
seeing, the data set is a list of five additional columns (row 1, row 2, row 3, row
4, and row 5). A list containing other lists is termed a set of lists.
The data set variable is already a list, which indicates that we can use the
syntax we have learned to retrieve individual list elements and execute list
slicing. Under, we have:
Often, we will need to obtain individual elements from a list that is a portion of
a list of lists — for example; we might need to obtain the rating of 3.5 from the
data row ['FACEBOOK', 0.0, 'USD', 2974676, 3.5], which is a portion of the list of
data sets. We retrieve 3.5 from data set below utilizing what we have learnt:
Earlier in this example, we obtained 3.5 in two steps: data_set[0] was first
retrieved, and fb_row[-1] was then retrieved. There is also an easy way to get
the same 3.5 output by attaching the two indices ([0] and [-1]); the code
data_set[0][-1] gets 3.5.: Earlier in this example, we have seen two ways to get
the 3.5 value back. Both methods lead to the same performance (3.5), but the
second approach requires fewer coding, as the steps we see from the example
are elegantly integrated. As you can select an alternative, people generally
prefer the latter.
Let's turn our five independent lists in to the list of lists: app_data_set =
[row_1, row_2, row_3, row_4, row_5]
then use:
print(app_data_set)
[
[ ]
List Processes by Repetitive method Earlier, we had an interest in
measuring an app's average ranking in this project. It was a feasible
task while we were attempting to work only for three rows, but the
tougher it becomes, the further rows we add. Utilizing our tactic from
the beginning, we will:
As you have seen that it becomes complicated with five ratings. Unless we
were dealing with data that includes thousands of rows, an unimaginable
amount of code would be needed! We ought to find a quick way to get lots of
ratings back.
Taking a look at the code example earlier in this thread, we see that a
procedure continues to reiterate: within app_data_set, we select the last list
element for every list. What if we can just directly ask Python we would like to
repeat this process in app_data_set for every list?
Luckily we can use it — Python gives us a simple route to repeat a plan that
helps us tremendously when we have to reiterate a process tens of thousands or
even millions of times.
Let’s assume we have a list [3, 5, 1, 2] allocated to a variable rating, and we
need to replicate the following procedure: display the element for each element
in the ratings. And this is how we can turn it into syntax with Python: The
procedure that we decided to replicate in our first example above was "generate
the last item for each list in the app_data_set." Here's how we can transform
that operation into syntax with Python: Let's attempt and then get a good idea
of what's going on above. Python differentiates each list item from
app_data_set, each at a time, and assign it to each_list (which essentially
becomes a vector that holds a list — we'll address this further): In the last figure
earlier in this thread, the code is a much simpler and much more conceptual
edition of the code below: Utilizing the above technique requires that we
consider writing a line of code for each row in the data set. But by using the
app_data_set methodology for each list involves that we write only two lines of
code irrespective of the number of rows in the data set — the data set may have
five rows or a hundred thousand.
Our transitional goal is to use this special method to calculate the average
rating of our five rows above, in which our ultimate goal is to calculate the
average rating of 7,197 rows for our data set. We 're going to get exactly that
within the next few displays of this task, but we're going to concentrate for now
on practicing this method to get a strong grasp of it.
We ought to indent the space characters four times to the right before we
want to write the code: Theoretically, we would only have to indent the code to
the right with at least one space character, but in the Python language, the
declaration is to use four space characters. This assists with readability —
reading your code will be fairly easy for other individuals who watch this
convention, and you will find it easier to follow theirs.
Now use this technique to print each app's name and rating: foreach_list in
app_data_set: name = each_list[0]
rating = each_list[-1]
print(name, rating)
Facebook 3.5
Instagram 4.5
Clash of Clans 4.5
Temple Run 4.5
Pandora - Music & Radio 4.0
Loops
A loop is frequently used to iterate over a series of statements. We have two
kinds of loops, ‘for loop’ and ‘while loop’ in Python. We will study ‘for loop’ and
‘while loop’ in the following scenario.
For Loop
Python's for loop is used to iterate over a sequence (list, tuple, string) or just
about any iterate-able object. It is called traversal to iterate over a sequence.
Syntax of For loop in Python for<variable> in <sequence>: #
body_of_loop that has set of statements # which requires repeated
execution In this case < variable > is often a variable used to iterate
over a < sequence >. Around each iteration the next value is taken
from < sequence > to approach the end of the sequence.
Python – For loop example
The example below illustrates the use of a loop to iterate over a list array. We
calculate the square of each number present in the list and show the same with
the body of for loop.
#Printing squares of all numbers program # List of integer numbers
numbers = [1, 2, 4, 6, 11, 20]
#variable to store each number’s square temporary sq = 0
#iterating over the given list forval in numbers: # calculating square of each
number sq = val * val
# displaying the squares
print(sq)
Output:
1
4
16
36
121
400
For loop with else block
Excluding Java, we can have the loop linked with an optional 'else' block in
Python. The 'else' block only runs after all the iterations are finished by the loop.
Let's see one example: For val in range(5):
print(val)
else:
print("The loop has completed execution")
Output:
0
1
2
3
4
The loop has completed execution Note: else block is executed when the loop
is completed.
Nested For loop in Python
If there is a loop within another for loop, then it will be termed a nested for
loop. Let's take a nested for loop example.
for num1 in range(3):
for num2 in range(10, 14):
print(num1, ",", num2) Output:
0 , 10
0 , 11
0 , 12
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13
While Loop
While loop is also used to continuously iterate over a block of code until a
specified statement returns false, we have seen in many for loop in Python in
the last guide, which is used for a similar intent. The biggest distinction is that
we use for looping when we are not sure how many times the loop needs
execution, yet on the other side when we realize exactly how many times we
have to execute the loop, we need for a loop.
Syntax of while loop
while conditioning:
#body_of_while
The body of the while is a series of statements from Python which require
repetitive implementation. These claims are consistently executed until the
specified condition returns false.
while loop flow
1. Firstly given condition is inspected, the loop is canceled if the condition
returns false, and also the control moves towards the next statement in the
compiler after the loop.
2. When the condition returns true, the set of statements within the loop will
be performed, and the power will then switch to the loop start for the next
execution.
Those two measures continuously occur as long as the condition defined in
the loop stands true.
While loop example
This is an example of a while loop. We have a variable number in this case,
and we show the value of the number in a loop, the loop will have an
incremental operation where we increase the number value. It is a very crucial
component, while the loop should have an operation of increase or decrease.
Otherwise, the loop will operate indefinitely.
num = 1
#loop will repeat itself as long as it can #num< 10 remains true
whilenum< 10:`
print(num)
#incrementing the value of num num = num + 3
Output:
1
4
7
Infinite while loop
Example 1:
This will endlessly print the word 'hello' since this situation will always be true.
while True:
print("hello")
Example 2:
num = 1
whilenum<5:
print(num)
This will endlessly print '1' since we do not update the number value inside
the loop, so the number value would always remain one, and the condition
number<5 would always give back true.
Nested while loop in Python While inside another while loop a while
loop is present, then it will be considered nested while loop. To
understand this concept, let us take an example.
i=1
j=5
while i< 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1
Output:
1,5
2,6
3,7
Python – while loop with else block We may add an 'else' block to a
while loop. The section 'else' is possible. It executes only when the
processing of the loop has ended.
num = 10
whilenum> 6:
print(num)
num = num-1
else:
print("loop is finished")
Output:
10
9
8
7
Loop is finished
ADDING MULTIPLE VALUED DATA IN
PYTHON
ften the creator wants users to input multiple values or inputs in a line. In
O Python, users could use two techniques to take multiple values or inputs in
one line.
We cannot erase characters from a string, or remove them. But it's easy to
erase the string completely by using del keyword.
Python String Operations
There are many methods that can be used with string making it one of the
most commonly used Python data types. See Python Data Types for more
information on the types of data used in Python coding Concatenation of Two or
More Strings The combination of two or even more strings into one is termed
concatenation. In Python, the + operator does that. They are likewise
concatenated by actually typing two string literals together. For a specified
number of times, the * operator could be used to reiterate the string.
Once we execute the code above, we have the following results: He said,
"What's there?"
He said, "What's there?"
He said, "What's there?"
Raw String to ignore escape sequence Quite often inside a string, we
might want to reject the escape sequences. To use it, we can set r or R
before the string. Which means it's a raw string, and it will neglect any
escape sequence inside.
>>>print("This is \x61 \ngood example") This is a
good example
>>> print(r"This is \x61 \ngood example") This is \x61 \ngood example The
format() Method for Formatting Strings The format() sources available and make
with the string object is very flexible and potent in string formatting. Style
strings contain curly braces{} as placeholders or fields of substitution, which are
substituted.
To specify the sequence, we may use positional arguments or keyword
arguments.
The format() technique can have requirements in optional format. Using colon,
they are divided from the name of the field. For example, a string in the given
space may be left-justified <, right-justified >, or based ^.
Even we can format integers as binary, hexadecimal, etc. and floats can be
rounded or shown in the style of the exponent. You can use tons of compiling
there. For all string formatting available using the format() method, see below
example:
Old style formatting
We even can code strings such as the old sprint() style in the programming
language used in C. To accomplish this; we use the ‘%’ operator.
String common Methods for Python The string object comes with
various methods. One of them is the format() method we described
above. A few other frequently used technique include lower(), upper(),
join(), split(), find(), substitute() etc. Here is a wide-range list of
several of the built-in methodologies in Python for working with
strings.
Inserting values into strings Method 1 - the string format method The
string method format method can be used to create new strings with
the values inserted. That method works for all of Python's recent
releases. That is where we put a string in another string:
Using the formatting options within curly brackets, you can do more complex
formatting of numbers and strings — see the information on curly brace string
layout.
This process allows us to give instructions for formatting things such as
numbers, using either: inside the curly braces, led by guidance for formatting.
Here we request you to print in integer (d) in which the number is 0 to cover the
field size of 3:
Shepherd
Martha is 34 years old.
MODULE DATA
working directory:
In this, we defined an add() function within an example titled “ module.” The
function requires two numbers and returns a total of them.
How to import modules in Python?
Within a module, we can import the definitions to some other module or even
to the interactive Python interpreter. To do something like this, we use the
keyword import. To load our recently specified example module, please enter in
the Python prompt.
>>> import example This should not import the identities of the functions
directly in the existing symbol table, as defined in the example. It just imports
an example of the module name there.
Using the name of the module, we can use the dot(.) operator to access the
function. For instance: >>>example.add(4,5.5)
9.5
Python comes with lots of regular modules. Check out the complete list of
regular Python modules and their usage scenarios. These directories are within
the destination where you've installed Python in the Lib directory. Normal
modules could be imported just the same as our user-defined modules are
imported.
There are different ways of importing the modules. You'll find them below:
Python import statement
Using the import statement, we can extract a module by using the dot
operator, as explained in the previous section and access the definitions within
it. Here is another example.
Once we execute the code above, we have the following results: The value of
pi is 3.141592653589793
Import with renaming
We can load a module in the following way by changing the name of it:
We called the module Math as m. In certain instances, this will save us time to
type. Remember that in our scope, the name math is not identified. Therefore
math.pi is incorrect, and m.pi is correctly implemented.
Python from...import statement We can import individual names from
such a module without having to import the entire module. Here is
another example.
In this, only the pi parameter was imported from the math module. We don't
utilize the dot operator in certain cases. We can likewise import different
modules: >>>from math import pi, e >>>pi
3.141592653589793
>>>e
2.718281828459045
Import all names
With the following form, we can import all terms (definitions) from a module:
# import all names from standard module math from math import *
print("The value of pi is," pi) Above, we have added all of the math module
descriptions. This covers all names that are available in our scope except those
that start with an underscore. It is not a good programming technique to import
something with the asterisk (*) key. This will lead to a replication of an
attribute's meaning. This also restricts our code's readability.
Python Module Search Path
Python looks at many locations when importing a module. Interpreter
searches for a built-in module instead. So if not included in the built-in module,
Python searches at a collection of directories specified in sys.path. The
exploration is in this sequence: PYTHONPATH (list of directories environment
variable) The installation-dependent default directory
We can insert that list and customize it to insert our own location.
Reloading a module
During a session, the Python interpreter needs to import one module only
once. This makes matters more productive. Here is an example showing how
that operates.
Assume we get the code below in a module called my_module:
Now we'll see a list of the names sorted (alongside add). Many other names
that start with an underscore are module-associated (not user-defined) default
Python attributes. For instance, the attribute name contains module __name__.
>>> import example >>>example.__name__
'example'
You can find out all names identified in our existing namespace by using dir()
function with no arguments.
Executing modules as scripts Python module running with python
fibo.py <arguments>the program will be running in such a way, just
like it was being imported, but including the __name__ set to
"__main__." That implies this program is inserted at the end of the
module: If __name__ == "__main__": import sys fib(int(sys.argv[1])) You
could even create the file usable both as a script and as an importable
module since this code parsing the command - line interface runs only
when the module is performed as the "main" file: $ python fibo.py 50
0 1 1 2 3 5 8 13
When the module is imported, the code will not be executed: >>>
>>> import fibo
>>>
It is most often used whether to get an efficient user interface to a module or
for test purposes (the module runs a test suite as a script).
“Compiled” Python files
To speed up loading modules, Python caches the compiled version of each
module in the __pycache__ directory with the name module.version.pyc, in which
the version encapsulates the assembled file format; it normally includes the
firmware version of Python. For instance, the compiled edition of spam.py in
CPython launch 3.3 will be cached as __pycache__/spam.cpython-33.pyc. This
naming convention enables the coexistence of compiled modules from various
updates and separate versions of Python.
Python tests the source change schedule against the compiled edition to see if
it is out-of-date and needs recompilation. That's a fully automated system. Even
the assembled modules become platform-independent, so different algorithms
will use the same library between systems. In two situations Pythoniswill not
check the cache: ➢ First, it often recompiles the output for the module, which is
loaded explicitly from the command line but does not store it.
➢ Second, when there is no root module, it will not search the cache. The
compiled module must be in the source directory to facilitate a non-source
(compiled only) release, and a source module should not be installed.
Some tips for users:
To minimize the size of a compiled file, you can use the -O or -OO
switches in the Python order. The -O switch erases statements of
assert, the -OO switch removes statements of assert as well as
strings of doc. Although some codes may support getting these
options available, this method should only be used if you are aware
of what you are doing. "Optimized" modules usually have such an
opt-tag and are tinier. Future releases may modify the optimal
control implications.
A project run no faster once it is read from a.pyc file than how it
was read from a.py file; just one thing about.pyc files that are
faster in the speed with which they will be loaded.
A compile all modules can generate .pyc files in a directory for all
of the other modules.
More details on this process are given in PEP 3147, along with a
flow chart of the decision making.
Standard Modules
Python has a standard modules library, mentioned in a separate section, the
Python Library allusion (hereafter "Library Reference"). A few modules are
incorporated into the interpreter; that provide direct exposure to processes that
are not component of the language's base but are nonetheless built-in, whether
for effectiveness or to supply access to primitive operating systems such as
source code calls. The collection of these modules is an alternative to customize
and also relies on the framework underlying it. The winreg module, for instance,
is only available on Microsoft windows. One particular module is worthy of
certain interest: sys, which is integrated into every Python interpreter. The
sys.ps1 and sys.ps2 variables classify strings which are used as primary and
secondary instructions: >>>
>>> import sys >>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C>print('Yuck!')
Yuck!
C>
Only when the interpreter is in interactive mode are those two variables
defined. The sys.path variable is a collection of strings that defines the search
path for modules used by the interpreter. When PYTHONPATH is not a part of the
set, then it will be defined to a predefined path taken from either the
PYTHONPATH environment variable or through a built-in default. You can change
it with regular list procedures: >>>
>>> import sys
>>>sys.path.append('/python/ufs/guido/lib/') Packages
Packages are indeed a way to construct the namespace of the Python module
by using "pointed names of the module." For instance, in a package called A.,
the module title A.B specifies a submodule named B. Even as the use of modules
prevents the writers of various modules from stopping to know about the global
variable names of one another, any use of dotted module names prevents the
developers of multi-module bundles like NumPy or Pillow from needing to worry
more about module names of one another. Consider making a series of lists of
modules (a "package") to handle sound files and sound data in an even manner.
There are several various programs of sound files usually familiar with their
extension, for example: ‘wav,.aiff,.au,’ though you'll need to build and maintain
a massive collection of modules to convert between some of the multiple
formats of files. There are several other different operations that you may like to
run on sound data (such as blending, adding echo, implementing an equalizer
function, producing an optical stereo effect), and you'll just be writing an infinite
series of modules to execute those interventions. Here is another feasible
package layout (described in terms of a hierarchical file system):
While loading the bundle, Python checks for the packet subdirectory via the
folders on sys.path. To allow Python view directories that hold the file as
packages, the __init__.py files are needed. This protects directories with a
common name, including string, from accidentally hiding valid modules, which
later appear mostly on the search path of the module. In the correct order;
__init__.py can only be a blank file, but it could also implement the package
preprocessing code or establish the variable __all__ described below
CONCLUSION
Research across almost all fields has become more data-oriented, impacting
both the job opportunities and the required skills. While more data and methods
of evaluating them are becoming obtainable, more data-dependent aspects of
the economy, society, and daily life are becoming. Whenever it comes to data
science, Python is a tool necessary with all sorts of advantages. It is flexible and
continually improving because it is open-source. Python already has a number of
valuable libraries, and it cannot be ignored that it can be combined with other
languages (like Java) and current frameworks. Long story short -Python is an
amazing method for data science.
PYTHON CRASH COURSE
JASON TEST
DAY 1
What Is Python?
P ython is a
programming
high-level, object-oriented, construed
language with complex semblance.
Combined with dynamic typing and dynamic binding, its
high-level data structures make it very attractive for Rapid
Application Development as well as for use as a scripting or
glue language for connecting existing components. Python's
quick, easy to understand syntax, stresses readability, and
hence reduces the expense of running the software. Python
connects modules and packages that promote the
modularity of the software and reuse of code. For all major
platforms, the Python interpreter and the comprehensive
standard library are available free of charge in source or
binary form and can be freely distributed.
Programmers also fall in love with Python because of the
increased productivity it brings. The edit-test-debug process
is amazingly quick since there is no compilation phase.
Python debugging programs are simple: a mistake or bad
feedback would never trigger a segmentation fault.
Alternatively, it creates an exception when the translator
detects an error. If the program miscarries to catch the
exception, the parser will print a stack trace. A source-level
debugger allows you to inspect local and global variables,
check arbitrary expressions, set breakpoints, walk through
the code one line at a time, etc. The debugger itself is
written in Python, testifying to the introspective power of
Python. On the other side, often the fastest way to debug a
system is to add a few print statements to the source: the
quick process of edit-test-debug renders this simple
approach quite efficient.
Who is the Right Audience?
The resolve of this book is to get you up to speed with
Python as easy as possible so that you can create programs
that work — games, data analysis, and web applications —
while building a programming base that will serve you well
for the rest of your life. Python Crash Course is designed for
people of any age who have never programmed in or
worked in Python before. This book is for you if you want to
learn the basics of programming quickly so you can focus on
interesting projects, and you like to test your understanding
of new concepts by solving meaningful issues. Python Crash
Course is also great for middle and high school teachers
who would like to give a project-based guide to
programming to their pupils.
What You Will Learn?
The sole purpose of this book is to make you generally a
good programmer and, in particular, a good programmer for
Python. As we provide you with a solid foundation in general
programming concepts, you can learn quickly and develop
good habits. You should be prepared to move on to more
sophisticated Python methods after working your way
through the Python Crash Course, and it will make the next
programming language much easier to grasp. You will learn
basic programming concepts in the first part of this book,
which you need to know to write Python programs. These
concepts are the same as those you would learn in almost
any programming language when starting out.
You can learn about the different data types and ways you
can store data within your applications in lists and
dictionaries. You'll learn how to build data collections and
work efficiently through those collections. You'll learn to use
while and when loops to check for certain conditions so that
you can run certain sections of code while those conditions
are true and run certain sections when they aren't true — a
strategy that can significantly automate processes. To make
your programs accessible and keep your programs going as
long as the user is active, you'll have to accept input from
users. You 're going to explore how to apply functions as
reusable parts of your software, and you only have to write
blocks of code that execute those functions once, which you
can use as many times as you want. You will then extend
this concept with classes to more complicated behavior,
making programs fairly simple to respond to a variety of
situations.
You must learn how to write programs to handle common
errors graciously. You will write a few short programs after
going on each of these basic concepts, which will solve
some well-defined problems. Finally, you can take the first
step towards intermediate programming by learning how to
write checks for your code so that you can further improve
your programs without thinking about bugs being
implemented. For Part I, all the details will allow you to take
on bigger, more complicated tasks.
Why Python?
Every year we consider whether to continue using Python
or move on to another language — maybe one that is newer
to the programming world. But for a lot of reasons, I keep on
working on Python. Python is an incredibly efficient
language: the programs will do more than many other
languages will need with fewer lines of code. The syntax of
Python, too, should help write clean code. Compared to
other languages, the code will be easy to read, easy to
debug, and easy to extend and expand on. People use
Python for many purposes: making games, creating web
applications, solving business problems, and developing
internal tools for all types of applications interesting
ventures. Python is also heavily utilized for academic
research and theoretical science in scientific fields.
One of the main reasons I keep on using Python is
because of the Python community, which includes an
incredibly diverse and welcoming group of people.
Community is important for programmers since
programming is not a practice of solitude. Most of us will ask
advice from others, even the most seasoned programmers,
who have already solved similar problems. Getting a well-
connected and supportive community is essential to help
you solve problems and the Python community fully
supports people like you who are using Python as your first
programming language.
DAY 2
4
In this example, range() only prints the numbers 1
through 4. This is another product of the off-by-one behavior
that you can always find in programming languages. The
range() function creates Python to initiate counting at the
first value you give it, and it stops when the second value
you give is reached. Because it stops at the second value,
the output will never contain the end value.
Value, which would have been 5. You will use range(1,6)
to print the numbers from 1 to 5: for value in range(1,6):
print(value) This time the output begins at 1 and ends at 5:
1
2
3
4
5
If your output is changed than what you expect when you
are using range(), try adjusting your end value by one.
Using range() to Create a List of Numbers If you
want to create a list of numbers, you can convert the
results of range) (directly to a list using the list)
(function. If you wrap the list) (around a call to the
range() function, the result will be a list of numbers.
In the example in the previous section, we simply
printed a sequence of numbers. We can use list) (to
convert the same set of numbers to a list: numbers =
list(range(1,6)) print(numbers) And this is the
output:
[1, 2, 3, 4, 5]
Besides, we can use the range() function to tell Python to
skip numbers within a given range. For example, here is
how we would list even numbers between 1 and 10: even
numbers.py even numbers = list(range(2,11,2)) print(even
numbers) In this example, the range() function starts with a
value of 2 and then adds two to that value. It adds 2
repetitively until it ranges or passes the final value, 11, and
produces the following result: [2, 4, 6, 8 , 10]
You can create almost any number set you want to use
the range) (function. Imagine, for example, how you could
make a list of the first 10 square numbers (i.e., the square
of each integer from 1 to 10). In Python, two asterisks (* *)
are exponents. Here's how you can add the first 10 square
numbers in the list: We start with an empty list called U
squares. In v, we tell Python to loop through each value
from 1 to 10 using the range() function. Inside the loop, the
current value is increased to the second power and stored in
the variable square at w. At x, every new square value is
added to the list of squares. When the loop is finished, the
list of squares is printed at y: [4, 9, 16, 25, 36, 49, 64, 81,
and 100]
To inscribe this code more concisely, bypass the
temporary variable square and apply each value directly to
the list: squares = [] for value in range(2,11): u
squares.append(value**2) print(squares) The coding at u
functions the same way as the lines at w and x in
squares.py. Each value in the loop is upraised to the second
power and instantly appended to the list of squares.
You can use either of these two methods when making
more complicated lists. Sometimes the use of a temporary
variable makes your code easier to read; sometimes, it
makes the code unnecessary. Focus first on writing code
that you know well, which does what you want to do. Then
look for more efficient methodologies as you look at your
code.
Simple Statistics with a List of Numbers A few
Python functions are unique to a number set.
For instance, you can easily find the total, limit,
and sum of the number list: >>> digit = [2, 3,
4, 6, 7, 8, 0] >>> min(digits)0 >>> max(digit)
8>>> sum(digits) 35
DAY 6
Tuples
100
Let’s observe what happens if we change one of the items
in the tuple dimensions: dimensions = (400, 100) u
dimensions[0] = 500
U's code attempts to change the value of the first
element, but Python returns a sorting error. Because we are
trying to alter a tuple that can not be done with that type of
object, Python tells us that we can not assign a new value to
a tuple item: Traceback (most recent call last): File
"dimensions.py", line 3, in <module> dimensions[0] = 500
TypeError: 'tuple' object doesn’t support item assignment
This is useful because we want Python to make a mistake
when a line of code attempts to alter the dimensions of the
rectangle.
100
Writing over a Tuple
100
Modified dimensions:
800
200
When compared to lists, tuples are easy data
constructions. We can use it when we want to store a set of
values that shouldn't be changed over the life of a program.
Indentation
PEP 8 recommends using four spaces per indentation
level. Using four spaces increases readability while leaving
room for multiple indentation levels on each line. In a word
processing document, people frequently use tabs instead of
indent spaces. This works fine with word processing
documents, but the Python interpreter gets confused when
tabs are mixed with spaces. Each text editor provides a
setting that allows you to use the tab key but then converts
each tab to a set number of spaces. You should certainly use
your tab key, but also make sure that your editor is set to
insert spaces instead of tabs into your document. Mixing
tabs and spaces in your file may cause problems that are
very difficult to diagnose. If you feel you have a mix of tabs
and spaces, you can convert all tabs in a file into spaces in
most editors.
Line Length
Many Python programmers propose that each line be less
than 80 characters in length. Historically, this guideline was
developed because most computers could accommodate
only 79 characters on a single line in the terminal window.
At present, people can accommodate much longer lines on
their computers, but there are many incentives to stick to
the regular length of the 79-character grid. Professional
programmers often have multiple files open on the same
screen, and using the standard line length, they can see
whole lines in two or three files that are opened side by side
on the screen. PEP 8 also suggests that you limit all of your
comments to 72 characters per line, as some of the tools
that generate automatic documentation for larger projects
add formatting characters at the beginning of each
commented line. The PEP 8 line length guidelines are not set
in stone, and some teams prefer a 99-character limit. Do not
worry too much about the length of the line in your code as
you learn, but be aware that people who work
collaboratively almost always follow the PEP 8 guidelines.
Many of the editors allow you to set up a visual cue, usually
a vertical line on your screen, which shows where these
limits are if Statements Programming often involves
examining a set of conditions and deciding which action to
take on the basis of those conditions. Python's if the
statement allows you to examine the current state of the
program and respond appropriately to that state of affairs.
In this section, you will learn how to write conditional
tests, which will allow you to check any conditions of
interest. You will learn to write simply if statements, and you
will learn how to create a more complex series of if
statements to identify when the exact conditions you want
are present. You will then apply this concept to collections,
so you can write a loop that handles most items in a list one
way, then handles other items with specific values in a
different way.
A Simple Example
The following short example shows how if the tests allow
you to respond correctly to specific situations. Imagine that
you have a list of cars and that you want to print out the
name of each vehicle. Car titles are the right ones, so the
names of most vehicles should be written in the title case.
But, the value 'BMW' should be printed in all cases. The
following code loops through the car list Names and looks
for the 'BMW' value. Whenever the value is 'BMW,' it is
printed in the upper case instead of the title case:
vehicles.py vehicles = ['audi', 'bmw', 'subaru', 'toyota'] for
vehicle in vehicles: u if car == 'bmw': print(vehicle.upper())
else: print(vehicle.title()) The loop in this model first checks
if the current value of the car is 'bmw' u. If it is, the element
is printed in uppercase. If the value of the vehicle is other
than 'bmw', it is printed in title case: Audi
BMW
Subaru
Toyota
Each explanation incorporates a variety of topics that you
can hear more in this chapter. Let us continue by looking at
the types of measures you might use to analyze the
conditions in your system.
Conditional Tests
At the heart of each, if the statement is an expression
that can be evaluated as True or False and called a
conditional test. Python practices the True and False values
to decide whether the code in the if statement should be
executed. If the conditional check is valid, Python must run
the code following the if argument. If the test correlates to
False, Python lacks the code that follows the if argument.
Checking for Equality
Most of the conditional tests compare the current value of
a variable to a specific value of interest. The most common
conditional test tests that the value of the variable is equal
to the value of the interest: u >>> vehicle = 'bmw' v >>>
vehicle == 'bmw' True The U line sets the value of the
vehicle to 'bmw' using a single equivalent symbol, as you
have seen countless times before. The line in v tests if the
name of the vehicle is 'bmw' using a double equal sign (=
=). This equivalent operator returns True if the values on the
left and right sides of the operator match, and False if they
do not match. The values in this example will suit, so Python
will return Real. If the value of the car is anything other than
'bmw,' this test returns False: u >>> vehicle = 'audi' v >>>
vehicle == 'bmw' False A single equal sign is actually a
statement; you could read the code at u as "Set the value of
the vehicle equal to 'audi'." While a double equal sign, like
the one at v, inquires a question: "Is the value of the vehicle
equal to 'bmw?' "Most programming languages use the
same sign in this way.
Ignoring Case When Checking for Equality
Testing for equality is a sensitive case in
Python. For example , two values with different
capitalisations are not considered to be equal:
>>> vehicle = 'Audi' >>> vehicle == 'audi'
False This conduct is beneficial if the situation
matters. But if the case does not matter and
instead you just want to test the value of the
variable, you can convert the value of the
variable to the lowercase before you make the
comparison: >>> vehicle = 'Audi' >>>
vehicle.lower() == 'audi' True This test will be
Valid no matter how the 'Audi' meaning is
encoded, as the test is now case-insensitive.
The lower() function does not change the value
that was initially stored in the vehicle, so you
can do such kind of comparison preserving the
entire variable: u >>> vehicle = 'Audi' v >>>
vehicle.lower() == 'audi' True w >>> vehicle
'Audi'
U stores the capitalized string 'Audi' in the variable
engine. At v, we convert the value of the vehicle to the
lowercase and compare the lowercase value to the 'audi'
series. The two strings are paired, so Python returns Real. At
W, we see that the value kept in the vehicle was not
affected by the condition.
Testing. Websites implement certain laws for data entered
by users in a way similar to this. For example, a site may
use a conditional test like this to ensure that each user has
a truly unique username, not just a change in the
capitalization of another username. When someone else is
Submits a new username, the new username will be
translated to lowercase and compared to lowercase versions
of all current usernames. During this check, a username
such as 'John' will be rejected if any variation of 'John' is
already in use.
Checking for Inequality If you want to
determine whether two values are not equal,
you can combine an exclamation point and an
equal sign! (=). The exclamation mark is not as
it is in other programming languages. Let us
use another argument if you want to discuss
how to use inequalities Director. Director. We
must store the required pizza topping in a
variable and then print a message if the person
has not ordered anchovies: toppings.py
requested_topping = 'mushrooms' u if
requested_topping != 'anchovies': print("Hold
the anchovies!") The line at u relates the value
of requested topping to the value of
'anchovies.' If these two values are not
balanced, Python returns True and implements
the code given the if statement. If the two
values match, Python comes back False and
does not execute the code following the if
statement. Since the requested topping value
is not 'anchovies,' the print statement is
executed: Keep on the anchovies! Most of the
words that you write will test for equality;
however, perhaps you will find it more effective
to check for inequalities.
Numerical Comparisons
Checking numerical values is very easy. For instance , the
given code checks whether a person is 20 years of age:
>>> age = 20 >>> age == 20 True Also, You can check to
see if two numbers are not the same. For example, if the
answer is not correct, the following code prints a message:
magic_ answer = 19 number.py u if answer != 46:
print("That is not the correct answer. Please try again!") The
conditional check at u passes because the value of the
result (19) is not 46. The indented code block is executed
because the test passes: That is not the correct answer.
Please try again!
You may also include different mathematical comparisons
in your conditional statements, such as less than, less than
or equal to, greater than, and greater than or equal to: >>>
age = 19 >>> age < 21 True >>> age <= 21 True >>>
age > 21 False >>> age >= 21 False Could statistical
analogy be used as part of an if statement that can help you
diagnose the exact conditions of interest?
Checking Multiple Conditions You may want to
test different conditions at the same time. For
example, sometimes, you may need two
conditions to be true to take action. Other
times, you might be satisfied with only one
condition being True. Keywords and or can help
you in these situations.
Using and to Check Multiple Conditions To assess if
both conditions are true at the same time, use the
keyword and combine the two conditional tests; if
each test passes, the overall expression is true. If
either the test fails or all tests fail, the expression
will be tested as False. For example, you can check
whether there are two people over 21 using the
following test: u >>> age_0 = 22 >>> age_1 = 20 v
>>> age_0 >= 21 and age_1 >= 21 False w >>>
age_1 = 22 >>> age_0 >= 21 and age_1 >= 21 True
At u we describe two ages, age 0 and age 1. At v, we
check whether the two ages are 21 or not. The test
on the left passes, however, the test on the right
fails, so False evaluates the overall condition. We are
going to change the age 1 to 22. The value of age 1 is
now bigger than 21, and all individual measures
pass, allowing the final state expression to be
measured as Valid.
You may use parentheses around the individual tests to
enhance readability, but they are not necessary. If you were
using parentheses, the exam should look like this: (age_0
>= 21) and (age_1 >= 21) Using or to Check Multiple
Conditions The keyword or helps you to review different
criteria as well, but it fails when one or both of the checks
fails. An object or function can only fail if all separate
measures fail.
Let us look again at two ages, but this time we are going
to look for only one person over the age of 21: u >>> age_0
= 22 >>> age_1 = 10 v >>> age_0 >= 21 or age_1 >= 21
True w >>> age_0 = 20 >>> age_0 >= 21 or age_1 >= 21
False We start at u again with two age variables. If the age 0
check in v passes, the overall expression value is Valid. We
are going to lower the age of 0 to 10. In the test at w, both
tests have now failed, and the overall expression is
evaluated for False.
DAY 7
I fwriting
you understand the conditional tests, you can start
the statements. Several different types of if
statements exist, and the choice of one to use depends on
the number of criteria you choose to check. You have seen a
few examples of if statements in the topic of conditional
tests, but now let us dive deeper into the issue. The
simplest kind of argument that has one test and one action.
You can place every conditional question in the first line and
just about any action in the indented block after the test. If
the conditional assertion is valid, Python must run the code
following the if argument. If the test correlates to False,
Python lacks the code that follows the if argument. Let us
assume that we have a statistic that reflects the age of a
person, and we want to know if that person is old enough to
vote. The following code checks whether a person can vote:
voting.py age = 21 u if age >= 20: v print("You are old
enough to vote!") U Python checks whether the age value is
greater than or equal to 18. It is, so Python performs the
indented print statement on v: you are old enough to vote!
Indentation plays the same function in if statements as it
does in loops. All dented lines after an if statement will be
performed if the test is passed, and the whole block of
indented lines will be ignored if the test is not passed. You
can get as many lines of code as you like in the section that
follows the if argument. Add another line of production if the
person is old enough to vote, asking whether the user has
registered to vote: age = 21 if age >= 20: print("You are old
enough to vote!") print("Have you registered to vote yet?")
Conditional check succeeds, and all print comments are
indented, such that all lines are printed: You are old enough
to vote!
Have you registered to vote yet?
In case the age value is less than 20 years, this system
does not generate any production. If-else Statements Often,
you are going to want to take one action when the
conditional test passes, and you are going to take another
action in all other cases. The if-else syntax of Python makes
this possible. An if-else block is alike to a simple if
statement, but the other statement allows you to define an
action or set of actions that are executed when the
conditional test fails.
We are going to display the same message we had before
if the person is old enough to vote, but this time we are
going to add a message to anyone who is not old enough to
vote: age = 19 u if age >= 20: print("You are old enough to
vote!") print("Have you registered to vote yet?") v else:
print("Sorry, you are too young to vote.") print("Please
register to vote as soon as you turn 20!") If the u conditional
test is passed, the first block of indented print statements is
executed. If the test evaluates to False, the next block on v
is executed. Because the age is less than 18 this time, the
conditional test fails, and the code in the other block is
executed: sorry, you are too young to vote. Please register
for the ballot as soon as you turn 20! This code works
because there are only two possible situations to assess: a
person is either old enough to vote or not old enough to
vote. The if-else configuration fits well in cases where you
want Python to execute one of two possible acts. In a easy
if-else chain like this, one of the actions is always executed.
The if-elif-else Chain You will often need to test
more than two possible situations and to
evaluate them; you can use Python's if-elif-else
syntax. Python executes only one block of the
if-elif-else sequence. It will run each
conditional check in order for one to pass.
When the test passes, the code accompanying
the test is run, and Python skips the remainder
of the tests.
Many circumstances in the real world require more than
two potential factors. Consider, for example, an amusement
park that charges diverse rates for different age of people:
Admission for anyone under age 5 is free.
Admission for anyone between the ages of 5 and 20 is $5.
Admission for anyone age 20 or older is $10.
How do we use an if statement to decide the admission
rate of a person? The following code tests are performed for
a person's age group, and then an admission price message
is printed: amusement_ age = 12 park.py u if age < 5:
print("Your admission cost is $0.") if Statements 85 v elif
age < 20: print("Your admission cost is $5.") w else:
print("Your admission cost is $10.") If the test at u measures
whether a person is under 4 years of age. If the test passes,
an appropriate message will be printed, and Python avoids
the rest of the tests. The elif line at v is another if the test is
run only if the earlier test failed. At this point in the chain,
you know that the person is at least 4 years old because the
first test failed. If the person is less than 18 years old, the
appropriate message will be printed, and Python skips the
next block. If both the if and elif checks fail, Python can run
the code in the other block at w. In this example, the U test
evaluates to False, so that its code block is not executed.
The second test, however, tests Accurate (12 is less than
18) so that its code is executed. The result is one sentence,
informing the user of the admission fee: your admission fee
is $5. Any age greater than 17 would have caused the first
two tests to fail. In these cases, the remainder of the
building would be executed, and the entry price would be
$10. Rather than printing the entry price within the if-elif-
else sequence, it would be more straightforward to set only
the price within the if-elif-else chain and then to provide a
clear print declaration that runs after the chain has been
assessed: age = 12 if age < 5: u price = 0
elif age < 20: v price = 5 else: w price = 10
x print("Your admission cost is $" + str(price) + ".") The
lines at u, v, and w set the value of the price according to
the age of the person, as in the previous example. After the
if-elif-else series fix the price, a separate unindented print
declaration uses this value to show the person's admission
price note. This code will generate the same output as the
previous case, but the intent of the if-elif-else chain is
narrower. Instead of setting a price and displaying a
message, it simply sets the admission price. This revised
code is simpler to change than the original approach. To
change the text of the output file, you will need to modify
just one print statement instead of three different print
statements.