Python Programming

До загрузки: 30 сек.



Благодарим, что скачиваете у нас :)

Если, что - то:

  • Поделится ссылкой:
  • Документ найден в свободном доступе.
  • Загрузка документа - бесплатна.
  • Если нарушены ваши права, свяжитесь с нами.
Формат: pdf
Найдено: 23.08.2020
Добавлено: 30.09.2020
Размер: 2.03 Мб

1

PWKRQ3rogramming For
Beginners
The B eg in ner’s G uid e t o L earn in g t h e B asic s o f
P yth on. T ip s a n d T ric k s t o M aste r P ro gra m min g
Q uic k ly w ith P ra ctic al E xam ple s
James Herr on2

Table Of Contents
Intr oduction
A Compr ehensive Backgr ound
Version 1
Version 2
Version 3
How to Download and Install PWKRn
Install And Run PWKRQ,Q0DF26X
Install And Run PWKRQ,Q8QL[$QG/LQXx
Install And Run PWKRQ,QW indows
The PWKRQ(QYLURQPHQWDOVariables To Note
Opening A Console On Mac OS X
Opening A Console On Linux
Opening A Console On W indows
Interacting With PWKRn
Starting and Interacting with PWKRn
Variable
Basic Operators
Loops
Native PWKRQ'DWDWpes
Numbers
Strings
Lists
Tuples
Dictionary
Boolean Logic And Conditional
Constructing "While" Loops In PWKRn
Constructing "For Loops" Loops In PWKRn
Conclusion3

Introduction
PWKRQ is presumabl the easies t-to-learn and nicest-to-use programming
language in widespread use. PWKRQFRGHLVFOHDUWRUHDGDQGZULWHDQGLt
is short without being crSWLF3thon is a verSRZHUIXOODQJXDJHZKLFh
means that we can normall write far fewer lines of PWKRQ code than
would be needed for an equivalent application written in, say, C++ or
Java.
PWKRQ is a cross-platform language: so the same PWKRQ program can be
run on Windows and Unix-like sVWHPV such as Linux, BSD or Mac OS
X, just cop the file or files that make up the program to the target
machine, with no “building” or compiling required. It is possible to build
PWKRQ programs that appl platform-specific functionality, but this is
unusuall important since almost all of PWKRQ’ s standard librar and
most maximum third-part libraries are completel and transparently
cross-platform.
One of PWKRQ’ s exceptional strengths is that it comes with a ver full
standard library , this provides us to do such tasks as download a file from
the Internet, unpack a compress ed archive file or build a web server , just
one or a few lines of code. And in expanding to the standard library,
thousands of third-part libraries are free, some providing more strong
and sophisticate d tools than the standard librar just like the T wisted
networking librar and the NumP numeric librar while others give
functionalit that is too functional to be included in the standard librar-
for insta nce, the SimP simulation package. Most maximum of the third-
part libraries is accessible from the PWKRQ Package Index,
pSLSthon.or g/pSL.
PWKRQ can be used to program in procedural, object-oriented, and to a
minor extent, in a functional style, although at heart PWKRQ is an object-
oriented language. This book explains how to write both proced ural and
object-oriented programs, and also shows PWKRQ’s functional
programming features.
The goal of this book is to show RX how to write PWKRQ programs in
good idiomatic PWKRQ 3 stOH and to be a helpful reference for the
PWKRQODQJXDJHDIWHUWKHLQLWLDOUHDGLQJ.4

The book is designed to be useful to various different audiences,
including self-taught and hobbLVW programmers, students, scientists,
engineers, and others who neces sitate programming as part of their work.
To be of use to such a wide range of people without boring the conscious
or losing the less-experience d, this book assumes at least some
programming experience. This book is structured in such a wa as to
make RXDVSURGXFWLYHDVSRVVLEOHDVTXLFNO as possible.5

A Comprehensive Backgr ound
The programming language Python was invented in the late 1980s. Its
implementation was begun in December 1989 b Guido van Rossum at
CWI in the Netherlands as a foll ower to ABC able of complaint handling
and interfacing with the Amoeba operating sVWHP Van Rossum is
PWKRQ
V main author , and his continuing central role in choosing the
direction of PWKRQ is reflected in the license given to him b the PWKRn
community , Be nevolent Dictator for Life. (However , van Rossum
walked down as leader on Jul 12, 2018) PWKRQ was nominated for the
BBC TV show Mont3thon's FlLQJ&LUFXV.
PWKRQ 2.0 was issued on October 16, 2000, with several major new
features, including a cFOHGHWHFWLQJ garbage collector for memory
management and assistance for Unicode. However, the most major
change was to the developmen t method itself, with a shift to a more
transparent and communitEDFNHGSURFHVV.
PWKRQ 3.0, an important, backward-incompatible release, was released
on December 3, 2008, after a lar ge period of testing. Man of its
important features have also been backported to the backward-
compatible, while bQRZXQVXSSRUWHG3thon 2.6 and 2.7.
EarlKLVWRUy
In Febru ar 1991, Van Rossum wrote the code (labeled version 0.9.0) to
alt.sources. Then present at this stage in development was he develop
classes with inheritance, exception handling, functions, the core
datatSHV of a list, dict, str. A lso in this initial announcement was a
module sVWHP borrowed from Modula-3; Van Rossum explains the
module as "one of PWKRQ
V important programming units".PWKRQ
s
exception model also follows Modula-3's, with the addition of an else
clause. In 1994 comp.lang.pWKRQ the prime discussion forum for
PWKRQ was formed, signaling a milestone in the growth of PWKRQ
s
userbase.
Version 1
PWKRQ arrived version 1.0 in Januar 1994. The main new features
included in this announcement were the functional programming tools
lambda, map, and filter and reduce. Van Rossum asserted that "PWKRn6

acquired lambda, reduce (), filter () and map (), courtes of a Lisp hacker
who missed them and of fered working patches".
The last version published while Van Rossum was at CWI was PWKRn
1.2. In 1995, Van Rossum resumed his work on PWKRn at the
Corporation for National Research Initiatives in Reston, Virginia from
where he issued several versions.
B version 1.4, PWKRQ had procured several new features. Important
among these are the Modula-3 inspired keZRUG arguments (which are
also related to Common Lisp's keZRUG arguments) and built-in support
for complex numbers. Also included is a primar form of data hiding by
name mangling, though this is simplEpassed.
During Van Rossum's sta at CNRI, he began the Computer
Programming for EverERG (CP4E) initiative, intending to make
programming more available to more people, with a basic "literac in
programming languages, related to the primar English literac and
mathematics skills needed b most maximum emploHUV PWKRQ served
a central role in this: because of its center on clean sQWD[ it wa s already
fitting, and CP4E's goals bore connections to its predecessor , ABC. The
project was supported b DARP A. As of 2007, the CP4E project is
inactive. While PWKRQ attempts to be simpl learnable and not too
arcane in its sn tax and semantics and moving out to non-prog rammers
is not an existing concern.
Version 2
PWKRQ 2.0, released in October 2000, introduced list comprehensions, a
feature borrowed from the functional programming languages SETL and
Haskell. PWKRn's sQWD[ for this construct is ver related to Haskell's,
apart from Haskell's liking for punctuation characters and PWKRQ
s
preference for alphabetic keZRUGV PWKRQ 2.0 also started a garbage
collection sVWHPILWWHGRIFROOHFWLQJUHIHUHQFHFcles.
PWKRQ 2.1 was restricted to PWKRQ 1.6.1, as well as PWKRQ 2.0. Its
permit was renamed PWKRQ Software Foundation License. All code,
documentation, and specifications added, from the time of PWKRQ 2.1's
alpha release on, is granted b the PWKRQ Software Foundatio n, a non-
profit organization formed in 2001, modeled after the Apache Software
Foundation. The release included a modification to the language
specification to help nested scopes, like other staticall scoped
languages.7

PWKRQ 2.2 was released in December 2001; a major innovation was the
unification of PWKRQ
V tSHV (tSHV written in C) and classe s (tSHs
written in PWKRQ into one hierarchy . This single unification made
PWKRQ
V object model purel and consistentl object-oriented. Also
added were generators that were inspired b,FRQ.
PWKRQ 2.5 was released in September 2006 and introduced them with
the state ment, which encloses a code block within a context manager ,
allowing Resource Acquisition Is Initialization (RAII)-like behavior and
replacing a common trILQDOO idiom.
PWKRQ 2.6 was issued to corre spond with PWKRQ 3.0 and added some
points from that release, as well as a "warnings" mode that highlighted
the perfo rmance of features that were removed in PWKRQ 3.0. Likewise,
PWKRQ 2.7 conc urred with and added points from PWKRQ 3.1, which was
released on June 26, 2009. Parallel 2.x and 3.x deliverance then ceased,
and PWKRQ 2.7 was the eventual release in the 2.x series. In November
2014, it was declared that PWKRQ 2.7 would be maintained until 2020,
but user s were inspired to move to PWKRQ 3 as soon as possible . PWKRn
2.7 supp ort ended on 2020-01-01, but a final release of the code as it
appeared on 2020-01-01, 2.7.18 occurred on 2020-04-20. This marks the
end-of-life of PWKRQ.
Version 3
PWKRQ 3.0 was released on December 3, 2008. It was designed to rectify
fundamental design flaws in the language-the changes required could not
be implemented while retaining full backward compatibilit with the 2.x
series, which necessitated a new major version number. The guiding
polic of PWKRQ 3 was: "reduce specialt duplication b eliminating old
waVRIGRLQJWKLQJV.
PWKRQ 3.0 was developed with identical philosoph as in previous
versions. However, PWKRQ had gained new and redundant waV to
program. The identical task, PWKRQ 3.0 had an emphasis on eliminating
duplicative constructs and modules.
But, Pthon 3.0 continued a multi-paradigm language. Coders could still
attend object-oriented, structured, and functional programming
paradigms, among others. But within such large choices, the features
were intended to be more accessible in PWKRQ 3.0 than the were in
PWKRQ[.8

How to Download and Install PWKRn
Man working frameworks, for instance, macOS and Linux, accompany
PWKRQ pre-introduced. The rendition of PWKRQ that accompanies RXr
operation framework is called RXUIUDPHZRUN3thon.
The framework PWKRQ is completel obsolete, and ma not be a full
PWKRQ establishment. Fundamentally, RX have the latest rendition of
PWKRQVRou can ef fectivelWUDFNWKHPRGHOVULJKWQRw .
There are two significant forms of accessible PWKRQ PWKRQ 2,
otherwise called inheritance PWKRQ and PWKRQ 3. PWKRQ 2 was
dischar ged in the HDU 2000 and ought to arrive at its finish of-life on
Januar7KLVFRXUVHFHQWHUVRQ3thon 3.
It is part into three segments:
Windows
macOS
Linux
Simpl discover the area for RXU working framework and follow the
means to get RXU3&VHWXS.
On the off chanc e that RX have an alternate working framework, look at
the PWKRQ 3 Ins tallation and Setup Guide kept up on realpWKo n.com to
check whether RXU26LVVHFXUHG.9

Install And Run PWKRQ,Q0DF26X
1. Go to https://www .pWKRQRrg/downloads/ pWKRQ official site
and click Download PWKRQ (Y ou ma see different version
name and choose RXUVXLWDEOHYHUVLRQ .
2. When the downl oad is finished, open the package and follow
the instr uctions. The PWKRQ will be successfull installed
when the sVWHP will show the message as "The installation
was successful".
3. It's advised to download a good text editor before RX get
started. If RX are a beginner , I recommend RX download
Sublime[ https://www .sublimetext.com/2 ] Text. It's free.
4. The installation method is right forward. Run the Sublime
Text Disk Image file RX downloaded and follow the
guidance.
5. Open Sublime Text and go to File > New File (Shortcut:
Cmd+N). After that, please save the file b clicking (Cmd+S
or File > Save) with PWKRQ extension as .p extension as
hello.pRUP-first-program.py
6. W rite the code and save it again. For beginners, RX can copy
the code below:
print("Hello, W orld!")
This program Output:s: Hello W ord
7. Go to Tool > Build (Shortcut: Cmd + B). You will notice the
Output: at the bottom of Sublime Text. Congratulations,
RX
YHVXFFHVVIXOO run RXUSULPDU PWKRQSURJUDP.
Install And Run PWKRQ,Q8QL[$QG/LQXx
There are some easVWHSVWRLQVWDOO3thon on Unix/Linux machine.
1. Open a Web browser and go to
https://www .pWKRQRrg/downloads/ .
2. Follow the link to download zipped source code available for
Unix/Linux.
3. Download and extract files.10

4. Editing the Modules/Setup file if RX want to customize
some options.
5. run ./configure script
6. make
7. make install
BWKLVZD PWKRQZLOOEHLQVWDOOHGDWXVXDOORFDWLRQ /usr/local/bin and
its libraries at /usr/local/lib/pWKRQ;;. Here RXU3thon version is XX.
Install And Run PWKRQ,QW indows
Go to https://www .pWKRQRrg/downloads/ pWKRQ official site
and click Download PWKRQ (Y ou ma see different version
name and choose RXUVXLWDEOHYHUVLRQ .
When the download is finished, double-click the file and follow
the guidance to install it. At the time of installing PWKRQ a
program called IDLE will be installed also. It gives a graphical
user interface to work with PWKRQ.
Now open that IDLE program, then cop the following code and
press enter .
print("Hello, W orld!")
To generate a fil e in IDLE, go to File > New Window (Shortcut :
Ctrl+N).
After that write pWKRQ code and then please save the file by
clicking (Cmd+S or File > Save) with PWKRQ extension as .py
extension as hello.pRUP-first-program.py
Follow the Run > Run module (Here, RX can use the shortcu t
ke as F5) and RX can see the Output:. Congratulation, RX
ve
successfullUXQour first PWKRQSURJUDP.
The PWKRQ(QYLr onmental Variables To Note
Setting up P ATH
Man directories ma contain different executable files and programs,
where a search path is accomplished b the operating sVWHP and it is
registered bWKHGLUHFWRULHVWRH[HFXWHWKH26VHDUFKHV.11

The path is saved in an environ ment variable, which is a nam ed string
kept b the operating sVWHP This variable contains data available to the
command shell and other programs.
The path variable is defined as PA TH in Unix or Path in Windows (Unix
is case sensitive; W indows is not).
The path details are handled by the installer in Mac OS. To invoke the
PWKRQ interpret er from an appropriate directory, RX need to add the
PWKRQGLUHFWRU to RXUSDWK.
Setting path at Unix/Linux
Follow the follo wing rules for adding the pWKRQ director to the path for
a specific session in Unix −
TSH the setenv PA TH as "$P ATH:/usr/local/bin/pWKRQ and
press Enter keLQWKHFVKVKHOO.
TSH the export PA TH as "$P ATH:/usr/local/bin/pWKRQ and
press Enter keLQWKHEDVKVKHOORI/LQX[.
TSH the P A TH as "$P ATH:/usr/local/bin/pWKRQ and press
Enter keLQWKHVKRUNVKVKHOORI/LQX[.
Note − /usr/local/bin/pWKRQ is the path of the PWKRn
directory .
Setting path at W indows
Follow the follo wing rule for adding the pWKRQ director to the path for
a specific session in W indows −
TSH the path as "%path%;C:\PWKRQ and then press Enter ke at the
command prompt.
Point to be noted that the path of the PWKRQGLUHFWRU is “C:\PWKRQ”
Running PWKRn
There are three separate waVWRVWDUW3thon –
Script fr om the Command-line
A Py thon script can be performed at the command line b entre ating the
interpreter on RXUDSSOLFDWLRQDVH[SODLQHGLQWKHIROORZLQJH[DPSOH.
$pWKRQVFULSWS # Unix/Linux
or
pWKRQVFULSWS # Unix/Linux12

or
C:>pWKRQVFULSWS # Windows/DOS
Point to be noted that, RX shoul d be aware that the file permission mode
allows execution.
Interactive Interpr eter
It is good to start PWKRQ on the Unix, DOS or other technolog that
affords a command-line editor or shell window .
$pWKRQ8QL[/LQXx
or
pWKRQ8QL[/LQXx
or
C:>pWKRQWindows/DOS
Enter pWKRn the command line.
Please, start coding directlLQWKHLQWHUDFWLYHLQWHUSUHWHr .
Here is provided all the existing command line options list:
# Option & Description
1 -d
provide debug Output:
2 -O
produce enhanced bWHFRGH UHVXOWLQJLQSo files)
3 -S
For looking to the PWKRQSDWKVRQVWDUWXSou should not run
the import site
4 -v
verbose Output: (complete trace on import statements)
5 -X
This is just using strings or damage the class-based built-in
exceptions and it is starting from version 1.6.
6 -c cmd
run PWKRQVFULSWVHQWLQDVFPGVWULQg
7 File
run PWKRQVFULSWIURPJLYHQILOe
Integrated Development Environment
PWKRQ can be run from a Graphical User Interface (GUI) based
environment. It helps PWKRQZKHUHour sVWHPKDVD*8,DSSOLFDWLRQ.13

Unix − IDLE is the verILUVW8QL[,'(IRU3thon.
Macintosh − The Macintosh version of PWKRQ along with
the IDLE IDE is available from the main website,
downloadable as either MacBinarRU%LQ+H[
GILOHV.
Windows − PWKRQW in is the first Windows interface for
PWKRQDQGLVDQ,'(ZLWKD*8,.
If RX can't set up the environment properly, then RXU sVWHP admin can
help RX You will assure that the PWKRQ environment is properl set up
and working perfectlILQH.
Opening A Console On Mac OS X
OS X’s standard console is a program named Terminal. Open Terminal
b navigating to Applications, then Utilities, then double-click the
Terminal application. You can also simpl search for it in the sVWHm
search tool in the top right.
A command-line T erminal is a tool for interacting with RXU computer . A
window will start with a command-line prompt message, something like
this:
mFRPSXWHUaPusername$
Opening A Console On Linux
Several Linux distributions (e.g Ubuntu, Fedora, Mint) ma have
different console programs, normall referred to as a terminal. The exact
terminal of RXU startup, and how, can depend on RXU distribution. On
Ubuntu, RX will possibl want to open Gnome Terminal. It should show
a prompt like this:
mXVHUQDPH#Pcomputer:~$
Opening A Console On W indows
Window’ s console is named the Command Prompt, named cmd. A
simple wa to get to it is b using the ke combination Windows+R
(W indows meaning the Window s logo button), which should start a Run
dialog. Then tpewrite cmd and hit Enter or click Ok. You can also hunt
for it from the start menu. It should look like:
C:\Users\mXVHUQDPH>14

Window’ s Comm and Prompt is not reall as strong as its counte rparts on
Linux and OS X, RX might like to begin the PWKRQ Interpreter (see just
below) straight or using the IDLE program that PWKRQ comes with. You
can find these in the Start menu.
Using PWKRn
The pthon application that RX have installed will b defau lt act as
something named an interpreter . An interpreter uses text comm ands and
runs them as RX enter them -ver helpful for trLQJ things out. Simply
tSH pWKRQ at RXU console hit Enter , and RX should enter PWKRQ’ s
Interpreter .
Interacting W ith PWKRn
After Python opens, it will show RX some contextual data similar to
this:
PWKRQ GHIDXOW6HS1 1:28:25)
[GCC 5.2.0] on linux
TSHKHOSFRSright", "credits" for more data.
>>>
Note
The prom pt >>> on the last line shows that RX are now in an interactive
PWKRQ interpret er session, also named the “PWKRQ shell”. This is strange
from the normal terminal command prompt!
You can now start some code for pWKRQWRUXQT r:
print("Hello world")
Press Enter and notice what happens. After displaLQJ the results, PWKRn
will return RX back to the interactive prompt, where RX could enter the
different command:
>>> print("Hello world")
Hello world
>>> (1 + 4) * 2
1015

An extremel helpful command helps () , which enters a help
functionalit to search all the stuff pWKRQ lets RX do, right from the
interpreter . Pres s q to close the guidance window and return to the
PWKRQSURPSW.
To leave the interactive shell and go behind to the console (the sVWHm
shell), press Ctrl-Z and then Enter on Windows, or Ctrl-D on OS X or
Linux. Alternatively , RX could additionall run the pWKRQ command
exit() !16

Starting and Interacting with PWKRn
Variable
A name d location it's called variable and it used to store data in the
memory . It's helpful to think of variables as a container that holds data
which can be changed later throughout programming. Depend on the data
tSH of a variable, the interprete r allocates memor and decides what can
be store d in the reserved memory. Consequently , b assigning various
data tSHV to the variables, RX can store integers, decimals or characters
in these variables.
Assigning V alues to Variables
There is no need an exact declaration in PWKRQ variables to store
memor space. When a value is assigned to a variable the declaration
occurs automatically . The equal sign '=' is applied to assign values to
variables.
The operand to the left of the '=' operator is the sign of the variable and
the operand to the right of the '=' operator is the value stored in the
variable. As example–
#!/usr/bin/pWKRQ3
number = 10 # An integer
assignment
price = 100.05 # A floating point
name = "Steve" # A string
print (number)
print (price)
print (name)
Here, 10, 100.05 and "Steve" are the values
assigned to number , price, and name
variables, sequentially .
Outpu
t:
10
100.05
Steve
Multiple Assignment
PWKRQ permits RX to assign a single value to different variables
concurrently . As example –17

a = b = c = 10
Here, an integer object is created with the value 10, and all the three
variables are assigned to the same memor location. If RX want, RX can
also assign multiple objects to multiple variables. For example –
a, b, c = 10, 20, "steve"
Here, two integer objects with values 10 and 20 are assigned to the
variables a and b sequentially , and one single string object with the value
"steve" is assigned to the variable c.
Standard Data T SHs
Man types of data can be stored in memory . As an example, somebod
s
age is stored as a numeric value and his or her residence is stored as
alphanumeric characters. PWKon has man standard data tSHs that are
used to define the operations pleasant on them and the storage sVWHP for
each of them.
There are five standard data tSHVLQ3thon Language−
Numbers
String
List
Tuple
Dictionary
PWKRQ1XPEHUs
Number data tSHV store numeri c values. when a value is assigned to the
number data tSHVWKHQQXPEHUREMHFWVDUHFUHDWHG$VH[DPSOH–
var1 = 10
var2 = 20
Using the del statement the reference to a number object can be also
deleted. The sQWD[RIWKHGHOVWDWHPHQWLV–
del var1[,var2[,var3[....,varN]]]]
Using the del statement a single object or multiple objects can be deleted.
As example –
del var
del var_a, var_b
Three dif ferent numerical tSHVDUHVXSSRUWHGE PWKRQ−
int (signed integers)18

float (floating point real values)
complex (complex numbers)
In PWKo n3 all the integers have denoted as long integers. Therefore,
there is no separate number tSH.
Examples
Some examples of numbers are given below−
Int float complex
10 0.0 2.16j
200 12.30 35.j
-245 -42.5 3.234e-26j
078 22.3+e15 .568J
-0360 -60. -.5656+0J
-0x290 -52.32e200 3e+56J
0x39 90.2-E16 6.23e-3j
A complex number build up an ordered pair of real floating-point
numbers indicated b x + M where x and are real numbers and j is the
imaginarXQLW.
PWKRQ6WULQJs
Strings in PWKRQ are identified as an adjacent set of characters described
in the quotation marks. PWKRQ supports either pair of single or double
quotes. Subsets of strings can be taken using the slice operator [] and [:]
with indexes starting at 0 at the starting of the string and opera ting their
waIURPWRWKHHQG.
The plus '+' sign means the string concatenation operator and the asterisk
'*' means the repetition operator . For example –
#!/usr/bin/pWKRQ3
str = 'Hello PWKRQ'
print (str) # Prints complete string
print (str[0]) # Prints first character
print (str[2:5]) # Prints characters 3 rd 5 th
print (str[2:]) # Prints string 3 r d character
print (str * 2) # Prints string two times
print (str + "T est") # Prints concatenated string
Output: Hello PWKRQ!
H19

llo
llo PWKRQ!
Hello PWKRQ+HOOR3thon!
Hello PWKRQTest
PWKRQ/LVWs
In PWKRQ
V compound data tSes, lists are the most varied. A list holds
items divided b commas and surrounded within square brackets ([]). To
some space, lists are related to arraV in C. One of the variations within
them is that all the items referring to a list can be of the different data
tSH.
The values store d in a list can be obtained using the slice operator ([ ]
and [:]) with indexes starting at 0 at the beginning of the list and working
their wa to end -1. The plus (+) sign means the list concatenation
operator , and the asterisk (*) means the repetition operator . As example –
#!/usr/bin/pWKRQ3
list = [ 'wx]

6WHYH
]
tinOLVW >
6WHYH
]
print (list) # Prints complete list
print (list[0]) # Prints first component of the list
print (list[1:3]) # Prints components starting from 2nd till
3rd
print (list[2:]) # Prints components starting from 3rd
element
print (tinOLVW
 3ULQWVOLVWWZRWLPHs
print (list + tinOLVW 3ULQWVFRQFDWHQDWHGOLVWs
Output
:
['wx]

6WHYH
]
wxz
[786, 3.23]
[3.23, 'Steve', 80.2]
[123, 'Steve', 123, 'Steve']
['wx]

6WHYH
,
'Steve']
PWKRQ'LFWLRQDUy
PWKRQ
V dictionaries are sort of hash-table tSH The act like associative
arraV or hashes found in Perl and consist of keYDOXH pairs. A
dictionar ke can be about an PWKRQ tSH but are usuall numbers or
strings. V alues, on the other hand, can be anXQUHVWULFWHG3thon object.20

Dictionaries are surrounded by curl braces ‘{ }’ and values can be
assigned and entered using square braces ‘[ ]’. As example –
#!/usr/bin/pWKRQ3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinGLFW ^
QDPH

VWHYH

FRGH

GHSW
:
'marketing'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinGLFW 3ULQWVFRPSOHWHGLFWLRQDUy
print (tinGLFWNHs()) # Prints all the kes
print (tinGLFWYDOXHV 3ULQWVDOOWKHYDOXHs
Outpu
t:
This is one
This is two
{'name': 'steve', 'code': 1005, 'dept':
'marketing'}
dict_keV >
QDPH

FRGH

GHSW
@)
dict_values(['steve', 1005,
'marketing'])
Dictionaries have no idea of command within the elements. It is wrong to
saWKDWWKHHOHPHQWVDUHRXWRIRUGHUWKH are totallXQRUGHUHG.
Data T SH&RQYHUVLRn
Occasionally , it maEHQHHGHGWRSHUIRUPFRQYHUVLRQVZLWKLQWKHEXLOWLn
tSHVTo convert within tSHVXVHWKHWpe-names as a function, simply .
There are various built-in functions to complete the conversion from one
data tSH to another . These functions return a new object expressing the
converted value.
Sr.N
o.
Function & Description
1 int(x [,base])
Converts ‘x’ to an integer . The base defines the base if ‘x’ is a
string.
2 float(x)
Converts ‘x’ to a floating-point number .
3 complex(real [,imag])
Creates a complex number .21

4 str(x)
Converts object ‘x’ to a string representation.
5 repr(x)
Converts object ‘x’ to an expression string.
6 eval(str)
Evaluates a string and returns an object.
7 tuple(s)
Converts ‘s’ to a tuple.
8 list(s)
Converts ‘s’ to a list.
9 set(s)
Converts ‘s’ to a set.
1 0 dict(d)
Makes a dictionary . ‘d’ must be a sequence of (key ,value)
tuples.
11 fr ozenset(s)
Converts ‘s’ to a frozen set.
12 chr(x)
Converts an integer to a character .
13 unichr(x)
Converts an integer to a Unicode character .
14 ord(x)
Converts a single character to its integer value.
15 hex(x)
Converts an integer to a hexadecimal string.
16 oct(x)
Converts an integer to an octal string.
Basic Operators
The constructs which can manipulate the value of operands are called
operators.
Suppose the expression 5 + 3 = 8. Here, 5 and 3 are called operands and
+ is called operator .
TSHVRI2SHUDWRr
The following tSHVRIRSHUDWRUVDUHVXSSRUWHGLQ3thon language.
Arithmetic Operators22

Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identit2SHUDWRUs
Let us have a glance on all operators one bRQH.
Arithmetic Operators
Consider variable 'x' contains 10 and variable '
FRQWDLQVWKHQ–
Operator Description Example
+ Addition Values are added on each sides of
the operator .
x +  0
-Subtraction Subtracts right-hand operand from
the left-hand operand.
x –  0
*
Multiplication
Multiplies values on both sides of
the operator
x *  0
/ Division Divides left-hand operand bULJKW-
hand operand
x /  5
% Modulus The left-hand operand is shared by
the right-hand operand and returns
the remainder
[ 0
** Exponent Works exponential (power)
calculation on operators
x** Wo
the power 20
// Floor Division - The division of
operands wherever the result's the
quotient during which the digits
when the decimal point is
removed. But if one of the
operands is negative, the outcome
is floored, i.e., rounded awaIURm
zero (towards negative infinit)
10//5 = 2 and
7.0//2.0 = 3.0,
-11//3 = -4,
-11.0//3 = -4.0
Comparison Operators
Relational operators are the operators who compare the values on both
sides of them and choose the relation among them.
Consider variable 'a' holds 10 and variable 'b' holds 20, then –
Operato Description Example23

r
== The condition will be true when
the values of two operands are
equal.
(a == b) is not true.
!= The condition will be true when
the values of two operands are not
equal.
(a!= b) is true.
> The condition will be true when
the value of the left operand is
greater than the value of the right
operand.
(a >b) is not true.
< The condition will be true when
the value of the left operand is less
than the value of the right operand.
(a < b) is true.
>= The condition will be true when
the value of the left operand is
greater than or equal to the value
of the right operand.
(a >= b) is not true.
<= The condition will be true when
the value of the left operand is less
than or equal to the value of the
right operand.
(a <= b) is true.
Assignment Operators
Consider variable 'a' holds the value 10 and variable 'b' holds the value
20, then –
Operator Description Example
= Values are Assigned
from right side
operands to left side
operand.
c = a + b
assigns value of a + b
into c
+=Add AND It adds right operand to
the left operand then
assigns the result to the
left operand.
c += a
or
c = c + a
-= Subtract AND The right operand is
subtracted from the left
operand then assigns
c -= a
or
c = c - a24

the result to left
operand.
*= Multipl$1D The right operand is
multiplied bWKHOHIt
operand and the result
assigns to the left
operand.
c *= a
or
c = c * a
/= Divide AND The right operand is
divided bWKHOHIt
operand and assigns the
result to the left
operand.
c /= a
or
c = c / a
%= Modulus AND It takes modulus
applLQJWZRRSHUDQGs
and allows the result to
left operand
c %= a
or
c = c % a
**= Exponent AND The result is assigned
to the left operand from
exponential (power)
calculation on the
operators.
c **= a
or
c = c ** a
//= Floor AND The value from the
floor division on
operators is assigned to
the left operand.
c //= a
or
c = c // a
Example
Consider variable 'a' holds the value 10 and variable 'b' holds the value
20, then –
#!/usr/bin/pWKRQ3
a =10
b =20
c =0
c = a + b
print=(Line 1 - V alue of c is , c)
c += a
print=(Line 2 - Value of c is , c )
c *= a
print=(Line 3 - Value of c is , c )
c /= a25

print=(Line 4 - Value of c is , c )
c =2
c %= a
print=(Line 5 - Value of c is , c)
c **= a
print=(Line 6 - Value of c is , c)
c //= a
print=(Line 7 - Value of c is , c)
Output:
Line 1 - Value of c is 30
Line 2 - Value of c is 40
Line 3 - Value of c is 400
Line 4 - Value of c is 40.0
Line 5 - Value of c is 2
Line 6 - Value of c is 1024
Line 7 - Value of c is 102
Bitwise Operators
Bitwise operator acts on bits and performs the bit-bELW operation.
Consider if a = 30; and b = 15; Now in the binar format the will be as
follows −
PWKRQ
V built-in function bin() can be used to obtain the binary
representation of an integer number .
a = 0001 1110
b = 0000 1 111
-----------------
a &b = 0000 1 110
a | b = 0001 1 111
a ^ b = 0001 0001
~a = 1 110 0001
The following Bitwise operators have suggested PWKRQODQJXDJH–
Operator Description Example
& Binary
AND
The result of Binar$1'Ls
1 while both bit of two
operands is 1.
(a & b)
(means 0000 1 110)
| Binar2R
The result of Binar25LV1
while anRQHELWRIWZo
operands is 1.
(a | b) = 31 (means
0001 1 111)
^ Binar;2R The result of Binar;25Ls (a ^ b) = 17 (means26

1 while anRQHELWRIWZo
operands is 1 but not both
0001 0001)
~ Binar2QHs
Complement
It’s unarDQGKDVWKHHf fect
of 'flipping' bits.
(~a ) = -31 (means
1110 0001 in 2's
complement form due
to a signed binary
number .
<< Binary
Left Shift
The left operand's value is
moved left bWKHQXPEHURf
bits defined bWKHULJKt
operand.
a << 2 = 480 (means
1110 0000)
>> Binary
Right Shift
The left operand's value is
moved right bWKHQXPEHURf
bits defined bWKHULJKt
operand.
a >> 2 = 1 (means
0000 0001)
Example
#!/usr/bin/pWKRQ3
a =30 # 30 = 0001 1 110
b =15 #15 = 0000 1 111
print('a=',a,':',bin(a),'b=',b,':',bin(b))
c =0
c = a & b; # 14 = 0000 1 110
print("result of AND is ", c,':',bin(c))
c = a | b; # 31 = 0001 1 111
print("result of OR is ", c,':',bin(c))
c = a ^ b; # 17 = 0001 0001
print("result of EXOR is ", c,':',bin(c))
c =~a; # -31 = 1 110 0001
print("result of COMPLEMENT is ",
c,':',bin(c))
c = a <<4; # 480 = 1 110 0000
print("result of LEFT SHIFT is ", c,':',bin(c))
c = a >>4; # 1 = 0000 0001
print("result of RIGHT SHIFT is ", c,':',bin(c))
Outpu
t:
a= 30 : 0001 1110 b= 15 : 00001 111
result of AND is 14 : 00001 110
result of OR is 31 : 0001 1111
result of EXOR is 17 : 0001000127

result of COMPLEMENT is -31 :
-00011111
result of LEFT SHIFT is 480 :
111100000
result of RIGHT SHIFT is 1 :
00000001
Logical Operators
PWKRQ language allows the following logical operators. Consider
variable a holds T rue and variable b holds False then
Operator Description Example
and Logical AND
The condition will be
true when the both
operands are true.
(a and b) is False.
or Logical OR
The condition will be
true when anRIWKe
two operands are non-
zero.
(a or b) is True.
not Logical NOT
Applied to reverse the
logical state of its
operand.
Not(a and b) is T rue.
Membership Operators
Membership in a sequence is tested b PWKRQ membership operators,
like as strings, lists, or tuples. Two membership operators are described
here –
Operator Description Example
In
When it finds a
variable in the
specified sequence
and false otherwise
then it evaluates to
true.
‘a’ in y , when in
results in a 1 then ‘b’
is a member of
sequence ‘b’.
not in
When it does not find
a variable in the
specified sequence
and false otherwise
then it evaluates to
true.
‘a’ not in ‘b’, when
not in results in a 1
then ‘a’ is not a
member of sequence
‘b’.28

Identit2SHUDWRUs
The memor locations of two objects are compared in Identit operators.
T wo IdentitRSHUDWRUVDVGHVFULEHGKHUH–
Operato
r
Description Example
is When the variables on each side of
the operator point to the same
object and false otherwise are
assessed to true.
‘a’ is ‘b’,
when is results in 1
then id(a) equals
id(b).
is not When the variables on each side of
the operator do not point to the
same object and false otherwise
are assessed to true.
‘a’ is not ‘b’, when is
not results in 1 then
id(a) is not equal to
id(b).
Example
#!/usr/bin/pWKRQ3
a = 30
b = 30
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print= (Line 2 - a and b become same identit)
else:
print =(Line 2 - a and b do not become same identit)
if ( id(a) == id(b) ):
print =(Line 3 - a and b become same identit)
else:
print =(Line 3 - a and b do not become same identit)
b = 40
print =('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print =(Line 5 - a and b do not become same identit)
else:
print= (Line 5 - a and b become same identit)
Output: Line 1 a= 30 : 140351590504288 b= 30 :
140351590504288
Line 2 - a and b become same identity
Line 3 - a and b become same identity
Line 4 a= 30 : 140351590504288 b= 40 :
14035159050460829

Line 5 - a and b do not become same identity
Operators Precedence
# Operator & Description
1
**
Exponentiation (increase to the power)
2
~ + -
Complement, unarSOXVDQGPLQXs
3
* / % //
Multiply, divide, modulo and floor division
4
+ -
Addition and subtraction
5
>><<
Right and left bitwise shift
6
&
Bitwise 'AND'
7
^ |
Bitwise exclusive `OR' and regular `OR'
8
<= <>>=
Comparison operators
9
<> == !=
EqualitRSHUDWRUs
1
0
= %= /= //= -= += *= **=
Assignment operators
1
1
is is not
IdentitRSHUDWRUs
1
2
in not in
Membership operators
1
3
not or and
Logical operators
Loops
Normally , statem ents are executed consecutivel − The first statement in
a functio n is executed first, followed b the second, and so on. There
ma be a circumstance when it is needed to execute a block of code
numerous numbers of times.
Programming languages produce different control structures that permit
more complex execution paths.30

A loop statement permits us to execute a statement or group of
statements several times. The given diagram shows a loop statement –
The describing tSHV of loops are provided b PWKRQ programming
language for handling looping requirements.
# Loop T SH 'HVFULSWLRn
1
while loop
When a given condition is TRUE, it repeats a statement or group
of statements. It checks the condition before executing the loop
body.
2
for loop
Performs a sequence of statements numerous times then
abbreviates the code that runs the loop variable.
3
nested loops
One or more loop can be used inside anDQRWKHUZKLOHRUIRr
loop.
Loop Contr ol Statements
The execution from its usual sequence is changed b the Loop control
statements. All objects are created automaticall in scope are destroHd
while the execution leaves a scope.
These control statements are supported b3thon Language.
# Contr ol Statement & Description31

1 break statement
The loop statement is terminated bWKHEUHDNVWDWHPHQWDQGLn
the following loop execution is transferred to the statement
immediately .
2 continue statement
Causes the loop to leap the remainder of its bodDQGLQVWDQWOy
recheck its condition earlier to replicating.
3 pass statement
The pass statement is used in PWKRQHGLWRUZKHQDVWDWHPHQWLs
needed correctlEXWou do not want anFRPPDQGRUFRGHWo
execute.
Let us see each loop control statement swiftly .
Iterator and Generator
An iterator is an object which supports a programmer to travers e through
all the elements of a collection , despite its specific implementation. In
PWKRQDQLWHUDWRUREMHFWH[HFXWHVWZRPHWKRGVLWHU DQGQH[W .
An Iterator can be created bXVLQJ6WULQJ/LVWRUT uple objects.
list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object are often traversed using regular for statement!
usr/bin/pWKRQ3
for x in it:
print (x, end=" ")
or using next() function
while True:
tr:
print (next(it))
except StopIteration:
sVH[LW ou have to import sVPRGXOHIRUWKLs
Using the LHOG method, a gener ator is a function that returns or LHOGV a
sequence of values.
When a generator function is called, it returns a generator object without
even starting execution of the function. When the next() method is called
for the first time, the function starts executing until it reaches the return
statement, which returns the LHOGHG value. The LHOG keeps track i.e.32

remembers the last execution and the second next() call contin ues from
the previous value.
Example
A generator is defined b the following example, which produces an
iterator for all the Fibonacci numbers.
#!usr/bin/pWKRQ3
import ss
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
LHOGa
return
LHOGa
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
tr:
print (next(f), end=" ")
except StopIteration:
sVH[LW )
Native PWKRQ'DWDWpes
Ever object in PWKRQ has a tp e. The tSH function allows us to inspect
the tSHRIREMHFt
>>> tSH WRGD)

PWKRQ has just a handful of primitive or native data tSHV built into the
language.
Native data tSHVKDYHWKHIROORZLQJSr operties:
1. There are simple expressions that evaluate to objects of these
tSHVFDOOHGOLWHUDOV.
2. There are built-in functions, operators, and methods to
manipulate these tSHVRIYDOXHV.33

As we have seen, numbers are native; numeric literals evaluate to
numbers, and mathematical operators manage number objects.
>>> 12 + 3000000000000000000000000
3000000000000000000000012
In case, PWKRQ involves three native numeric tSHV integers (int) , real
numbers (float) , and complex numbers (complex).
>>> tSH )

>>> tSH )

>>> tSH M)

The name float appears from the wa in which real numbers are denoted
in PWKo n: a "floating point" representation. While the details of how
numbers are expressed are not a question for this text, some high-level
dif ferences between int and float objects are necessar to know .
Inappropriate, int objects can onl represent integers, but the represent
them exactly , without an approximation. On the other hand, float
objects can express a wide range of fractional numbers, without not all
rational numbers are representable. Nonetheless, float objects are often
applied to express real and ratio nal numbers approximately , up to some
number of significant figures.
PWKRQKDVPDQ native datatSHV.
Here are the important ones:
1. Booleans are either T rue or False.
2. Numbers will be integers (1 and 2), floats (1.1 and 1.2),
fractions (1/2 and 2/3), or even complex numbers.
3. Strings are sequences of Unicode characters, e.g. an Html
document.
4. BWHVDQGEte arraVHJDMSHJLPDJHILOH.
5. Lists are ordered sequences of values.
6. Tuples are ordered, immutable sequences of values.
7. Sets are unordered bags of values.34

8. Dictionaries are unordered bags of keYDOXHSDLUV.
Of cour se, there are more tSes than these. EverWKLQJ is an object in
PWKRQ so there are tSHV like module, function, class, method, file, and
even edited code.
Numbers
Numeric values are stored b Number data tSHV The are immutable
data tSHV This means, alternating the value of a number of data tSe
Output:s a newlDOORFDWHGREMHFW.
At the time of assigning a val ue, the Number objects are created. As
example –
var1 =10
var2 =20
B using the del statement, the reference to a number object also can be
deleted. The del statement sQWD[LV–
del var1[,var2[,var3[....,varN]]]]
Using the del statement can delete a single object or multiple objects. As
example –
del var
del var_a, var_b
Different tSHVRIQXPHULFDODUHVXSSRUWHGE PWKRQ−
int (sign ed integers) − Normall it is called just integers or
ints. The are positive or negative total numbers with no
decimal point. In PWKRQ 3 Integers are of infinite size.
PWKRQ 2 holds two integer tSHV - int and long. there's no
'long integer' in PWKRQDQmore.
float (floating point real values) − It is also called floats. Real
numbers are represented b them and written with a decimal
point dividing the integer and the fractional parts. In scientific
notation, floats can also be repre sented with E or e indicating
the power of 10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) − are of the form a + bJ, where a
and b are floats and J (or j) denotes the square root of -1
(which is an unreal number). The real part of the number is a,
and the unreal part is b. In PWKRQ programming, Complex
numbers are not applied so much.35

It is probable to denote an integer in hexadecimal or octal form.
>>> number = 0xA0F #Hexa-decimal
>>> number
2575
>>> number = 0o37 #Octal
>>> number
31
Examples
Some examples of numbers are given here.
int float complex
10 0.0 2.16j
200 12.30 35.j
-245 -42.5 3.234e-26j
078 22.3+e15 .568J
-0360 -60. -.5656+0J
-0x290 -52.32e200 3e+56J
0x39 90.2-E16 6.23e-3j
A comp lex number consists of an ordered pair of real floating-point
numbers indicated b a + bj, where a is the real part and b is the unreal
part of the complex number .
Number TSH&RQYHUVLRn
PWKRQ transforms numbers inwardl in an illustration including mixed
tSHV to a common tSH for amends. Sometimes, RX need to control a
number apparentl from one tpe to another to meet the conditions of an
operator or function parameter .
TSHLQW [ WRFRQYHUW[WRDSODLQLQWHJHr .
TSHORQJ [ WRFRQYHUW[WRDORQJLQWHJHr .
TSHIORDW [ WRFRQYHUW[WRDIORDWLQJSRLQWQXPEHr .
TSH complex(x) to convert x to a complex number with real
part x and unreal part zero.
TSH complex(x, to convert x and to a complex number
with real part x and unreal part y. x and are numeric
expressions.
Mathematical Functions36

PWKRQ introduces the following functions that produce mathematical
calculations.
# Function & Returns ( Description )
1
abs(x)
The absolute value of x: the (positive) range from zero to x.
2
ceil(x)
The ceiling of x: the least integer not less than x.
3
cmp(x, )
-1 if ![LI[ y , or 1 if [,W
V'HSUHFDWHGLQ3thon 3.
Instead usereturn (x>  [).
4
exp(x)
The exponential of x: e x
5
fabs(x)
The absolute value of x.
6
floor(x)
The floor of x: the lar gest integer not bigger than x.
7
log(x)
natural logarithm of x, for x > 0.
8
log10(x)
base-10 logarithm of x for x > 0.
9
max(x1, x2,...)
The largest of its ar guments: the value nearest to positive infinity
1
0
min(x1, x2,...)
The smallest of its ar guments: the value nearest to negative infinity .
1
1
modf(x)
The both( fractional and integer )parts of x in a two-item tuple.
Each part has a similar sign as x. The integer returned as a float .
1
2
pow(x, )
The value of x**y.
1
3
round(x [,n])
x rounded to the decimal point from n digits. PWKRQURXQGVDZDy
from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
1
4
sqrt(x)
The squared root of x for x > 0.
Random Number Functions
In games, simulations, testing, security, and privac applications random
numbers are used. PWKRQ introduces the following functions that are37

generallXVHG.
# Function & Description
1
choice(seq)
A blind item from a list, tuple, or string.
2
randrange ([start,] stop [,step])
A randomlVHOHFWHGHOHPHQWIURPUDQJH VWDUWVWRSVWHS .
3
random()
A blind float r, such that 0 is less than or equal to r and r is less than
1
4
seed([x])
Sets the integer opening value applied in generating random
numbers. Call this function before calling anHDFKUDQGRPPRGXOe
function. Returns None.
5
shuffle(lst)
Randomizes the items of a list in place. Returns None.
6
uniform(x, )
A random float r , like x < r, or equal to r and r < y .
Trigonometric Functions
Following functions are introduced in PWKRQ language that performs
trigonometric calculations.
# Function & Description
1
acos(x)
Return the arc cosine of x, in radians.
2
asin(x)
Return the arc sine of x, in radians.
3
atan(x)
Return the arc tangent of x, in radians.
4
atan2(y , x)
Return atan([ LQUDGLDQV.
5
cos(x)
Return the cosine of x radians.
6
hSRW [)
Return the Euclidean norm, sqrt(x*x +
).
7
sin(x)
Return the sine of x radians.
8
tan(x)
Return the tangent of x radians.38

9 degrees(x)
Converts angle x from radians to degrees.
1
0
radians(x)
Converts angle x from degrees to radians.
Mathematical Constants
The module also represents two mathematical constants –
# Constants & Description
1
pi
The mathematical constant pi.
2
e
The mathematical constant e.
Strings
The most popular data tSH in PWKRQ is Strings. A string can create
simpl b embedding characters in quotes. Single quotes in PWKRQ is
treated as doubl e quotes. It is ver simple to create a string as assigning
a value to a variable. As example –
var1 ='Hello W orld!'
var2 ="PWKRQ3URJUDPPLQJ"
Accessing Values in Strings
The character tSHLVQRWVXSSRUWHGE PWKRQWKHVHDUHWUHDWHGDVVWULQJs
of length one, thus also granted a substring.
F or getting access to substrings, RX can use the square brackets for
splitting along with the index or contents to obtain RXU substring. As
example –
#!/usr/bin/pWKRQ3
var1 = 'Hello W orld!'
var2 = "PWKRQ3URJUDPPLQJ"
print ("var1[0]: ", var1[0])
print ("var2[0:6]: ", var2[0:6])
Output
:
var1[0]: H
var2[0:6]: PWKRn
Updating Strings39

You can "update " an extant string b (re)assigning a variable to another
string. The new value can be related to its prior value or to a co mpletely
dif ferent string altogether . As example –
#!/usr/bin/pWKRQ3
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] +
'PWKRQ
)
Outpu
t:
Updated String :- Hello
PWKRn
Escape Characters
There is a list of escape or non-p rintable characters in the following table
that can be represented with backslash notation.
An escape character gets explain ed; in a single quoted as well as double-
quoted strings.
Backslash notation
Hexadecimal
character
Description
\a 0x05 Bell or alert
\b 0x09 Backspace
\cx Control-x
\C-x Control-x
\e 0x2b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn
Octal notation, there
n is in the range 0.7
\r 0x0d Carriage return
\s 0x10 Space
\t 0x08 Tab
\v 0x0b V ertical tab
\x Character x
\xnn
Hexadecimal
notation, there n is in
the range 0.9, a.f, or
A.F40

String Special Operators
Consider string variable 'a' holds 'Hello' and variable 'b' holds 'PWKRQ
,
then –
Operato
r
Description Example
+
Concatenation - Adds values on both
sides of the operator
a + b will give
HelloPWKRn
*
Repetition - Produces new strings,
concatenating several copies of the
same string
a*2 will give -
HelloHello
[]
Slice - Provides the character from the
given index
a[1] will give e
[ : ]
Range Slice - Provides the characters
from the given range
a[1:4] will give
ell
In
Membership - Returns true if a
character remains in the given string
H in a will give 1
not in
Membership - Returns true if a
character does not remains in the given
string
M not in a will
give 1
r/R
Raw String - Overcomes original
meaning of Escape characters. The
sQWD[IRUUDZVWULQJVLVVSHFLILFDOOy
the same as for regular strings with the
exception of the raw string operator ,
the letter "r," which leads the quotation
marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed
directlOHDGLQJWKHILUVWTXRWHPDUN.
print r'\n' prints \n
and print
R'\n'prints \n
%
Format - Executes String formatting See at next
section
String Formatting Operator
string format operator % is One of the coolest features in PWKRQ This
operator is unusual to strings and proceeds for the pack of having
functions from C's printf() family . Here is an easH[DPSOH–
#!/usr/bin/pWKRQ341

print =(M name is %s and weight is %d kg! % ('Steve',
21))
Outpu
t:
MQDPHLV6WHYHDQGZHLJKWLVNJ!
The list of a complete set of sPEROV is given here which can be used
along with % −
# Format SPERO &RQYHUVLRn
1
%c
Character
2
%s
string conversion via str() prior to formatting
3
%i
signed decimal integer
4
%d
signed decimal integer
5
%u
unsigned decimal integer
6
%o
octal integer
7
%x
hexadecimal integer (lowercase letters)
8
%X
hexadecimal integer (UPPERcase letters)
9
%e
exponential notation (with lowercase 'e')
1
0
%E
exponential notation (with UPPERcase 'E')
1
1
%f
floating point real number
1
2
%g
the shorter of %f and %e
1
3
%G
the shorter of %f and %E
Some other supported sPEROs and functionalit are given here in the
table –
Sr.N
o.
SPERO )XQFWLRQDOLWy42

1 *
argument specifies width or precision
2
-
left justification
3
+
displaWKHVLJn
4

leave a blank space before a positive number
5
#
add hexadecimal leading '0x' or '0X' or the octal leading zero (
'0' ), depending on whether 'x' or 'X' were used.
6
0
pad from left with zeros (instead of spaces)
7
%
'%%' leaves RXZLWKDVLQJOHOLWHUDO
'
8
(var)
mapping variable (dictionarDr guments)
9
m.n.
m is the least whole width and n is the number of digits to
perform after the decimal point (if appl.)
Triple Quotes
B allowing strings pWKRQ
V triple quotes rescue the Span multiple lines,
including verbatim NEWLINEs, T ABs, and anRWKHUVSHFLDOFKDUDFWHUV.
Triple quotes build of three connected single or double quotes in the
sQWD[.
#!/usr/bin/pWKRQ3
TABB ( \t ) and theZLOOVKRZXSWKDWZD when displaHG.
NEWLINEs inside the string, whether explicitlVXSSOLHGOLNe
this inside the brackets
[ \n ], or just a NEWLINE inside
the variable assignment will also show up.
"""
print (para_str)
Output: this is a lar ge string that is produced of dif ferent
lines and non-printable characters such as
TABB ( ) and theZLOOVKRZXSWKDWZD when
displaHG.43

NEWLINEs inside the string, whether explicitly
supplied like
this inside the brackets
[
], or just a NEWLINE inside
the variable assignment will also show up.
Note: how all single unique character has been changed to its printed
form, right down to the least NEWLINE at the end of the string between
the "up." and closing triple quotes. Also, remark that NEWLINEs
transpire either with an exact carriage return at the end of a line or its
escape code (\n) –
The backslash at new strings does not treat a special character at all.
EverFKDUDFWHUSXWLQWRDUDZVWULQJVWDs the waZURWHLW–
#!/usr/bin/pWKRQ3
print ('C:\\nowhere')
The following Output: is produced when the above code is executed.
C:\nowhere
Now it is a time to use of raw string. We would set an expression in
r'expression' as heeds –
#!/usr/bin/pWKRQ3
print (r'C:\\nowhere')
The following Output: is produced when the above code is executed.
C:\\nowhere
Unicode String
In PWKRQDOOVWULQJVILOHGLQWHUQDOO as 8-bit ASCII, thus it's dutERXQd
to connect 'u' to create it Unicode. it's now not required currently. In
PWKRQDOOVWULQJVDUHGLDJUDPPDWLFLQ8QLFRGH.
Built-in String Method
To manipulate strings, pWKRQLQFOXGHVWKHIROORZLQJEXLOWLQPHWKRGV-
Sr .N
o.
Methods & Description
1
capitalize()
Capitalizes first letter of string
2 center(width, fillchar)44

Returns a string padded with fillchar with the initial string
centered to a total of width columns.
3
count(str, beg = 0,end = len(string))
Counts what number times str happens in string or in a very
substring of string if beginning index beg and ending index end
are given.
4
decode(encoding = 'UTF-8',err ors = 'strict')
Decodes the string applLQJWKHFRGHFILOHGIRUHQFRGLQJ.
encoding defaults to the default string encoding.
5
encode(encoding = 'UTF-8',errors = 'strict')
Returns encoded string version of string; on error , default is to
grow a ValueError except errors is given with 'ignore' or
'replace'.
6
endswith(suffix, beg = 0, end = len(string))
Determines if a string or a substring of string (if starting index
beg and ending index end are given) ends with a suf fix; returns
true if so and false otherwise.
7
expandtabs(tabsize = 8)
Expands tabs in a string too manVSDFHVGHIDXOWVWRVSDFHs
per tab if tabsize not given.
8
find(str, beg = 0 end = len(string))
Decide if str occurs in a string or a substring of string if starting
index beg and ending index end are given returns index if
found and -1 otherwise.
9
index(str , beg = 0, end = len(string))
Alike as find(), but grows an exception if str not found.
10
isalnum()
Returns true if a string has at least 1 character and all
characters are alphanumeric and fake unless.
11
isalpha()
Returns true if a string has at least 1 character and all
characters are alphanumeric and fake unless.
12
isdigit()
Returns true if a string contains onlGLJLWVDQGIDOVHXQOHVV.
13
islower()
Returns true if a string has at least 1 cased character and all
cased characters are in lowercase and false unless.
14 isnumeric()45

Returns true if a Unicode string contains onlQXPHULc
characters and false unless.
15
isspace()
Returns true if a string contains onlZKLWHVSDFHFKDUDFWHUVDQd
false unless.
16
istitle()
Returns true if a string is properlWLWOHFDVHGDQGIDOVHXQOHVV.
17
isupper()
Returns true if a string has at least one cased character and all
cased characters are in uppercase and false unless..
18
join(seq)
Merges (concatenates) the string representations of factors in
sequence seq into a string, with separator string.
19
len(string)
Returns the length of the string
20
ljust(width[, fillchar])
Returns a space-padded string with the primarVWULQJOHIW-
justified to a total of width columns.
21
lower()
Converts all uppercase letters in string to lowercase.
22
lstrip()
Removes all leading whitespace in string.
23
maketrans()
Returns a translation table to be applied in translate function.
24
max(str)
Returns the maximum alphabetic character from the string str .
25
min(str)
Returns the minimum alphabetic character from the string str.
26
replace(old, new [, max])
Replaces all occurrences of old in a string with new or at most
max occurrences if max gave.
27
rfind(str , beg = 0,end = len(string))
Same as find(), but search backwards in string.
28
rindex( str , beg = 0 and end = len(string))
Same as index(), but search backwards in string.
29
rjust(width,[, fillchar])
Returns a space-padded string with the primarVWULQJULJKW-
justified to a total of width columns..46

30 rstrip()
Removes all trailing whitespace of string.
31
split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided)
and returns a list of substrings; divide into at most num
substrings if given.
32
splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and passes a list of
each line with NEWLINEs removed.
33
startswith(str, beg=0,end=len(string))
Determines if a string or a substring of string (if starting index
beg and closing index end are provided) begins with substring
str; returns true if so and false unless.
34
strip([chars])
Performs both lstrip() and rstrip() on string
35
swapcase()
Inverts case for all letters in string.
36
title()
Returns "titlecased" version of the string, this is, all words start
with uppercase and the rest are lowercase.
37
translate(table, deletechars="")
Translates string according to interpretation table str(256
chars), excluding those in the del string.
38
upper()
Converts lowercase letters in string to uppercase.
39
zfill (width)
Returns original string left padded with zeros to a sum of width
characters; designed for numbers, zfill() retains anVLJn
provided (less one zero).
40
isdecimal()
Returns true if a Unicode string contains onlGHFLPDl
characters and false unless.
Lists
The sequence is the most basic data structures in PWKRQ Every part of a
sequence is allocated a number - its location or index. In a sequ ence the
first index is zero, the second index is one, and so forth. Six built-in tSHs
of seque nces are in PWKRQ but in this book, we would see the most
popular ones are lists and tuple s. You can do several things with all the47

sequence tSHs. These methods include indexing, slicing, joining,
multiplLQJ and monitoring for membership. In this book, PWKRQ has
built-in functions for getting the length of a sequence and getting its
largest and smallest elements.
PWKRQ/LVWs
The list is the common multipurpose data tSH available in PWKRQ 3,
which can be listed as a list of comma-marked values (items) within
square brackets. The items in a list need not be the same tSH and it is the
important thing about a list.
Like putting different comma-se parated values between square brackets,
creating a list is simple. As example –
List indices start at 0, and lists can be sliced, concatenated as Similar to
string indices.
Accessing V alues in Lists
To enter values in lists, appl the square brackets for slicing along with
the index or indices to get value available at that index. As example–
list1 = ['Banana', ‘W atermelon’, 1990, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
Output:
list1[0]: Banana
list2[1:5]: [2, 3, 4, 5]
The following Output: is produced when the above code is executed-
Updating Lists
Giving the slice on the left-hand side of the assignment operator, RX can
renew single or multiple elements of lists and also can add to elements in
a list with append () method. As example –
#!/usr/bin/pWKRQ3
list = ['Banana', 'W atermelon', 1990, 2000]
print =(Value available at index 2 : , list[2])
list[2] = 2001
print =(New value available at index 2 : ,
list[2])
Outpu
t:
Value available at index 2 :
199048

New value available at index 2
: 2001
Note − append () method is explained in the
subsequent section.
The following Output: is produced when the above code is executed-
Delete List Elements
You can use either the Del statement, to remove a list element if Ru
know correctl which element (s) RX are deleting and If RX do not
know exactl which items to delete then use the remove() method. As
example –
#!/usr/bin/pWKRQ3
list = ['Banana', 'W atermelon', 1990, 2000]
print (list)
del list[2]
print =(After deleting value at index 2 : , list)
Output:
['Banana', 'Watermelon', 1990, 2000]
After deleting value at index 2 : ['Banana',
'Watermelon', 2000]
Note- In the subsequent section remove () method is discussed.
Basic List Operations
Just like strings lists respond to the + and * operators. The mean
sequence and repetition here too, without that the Output: is a new list,
not a string.
In case, lists react to all of the prevailing sequence operations we used on
strings in the previous chapter .
PWKRQ([Sression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!',
'Hi!']
Repetition
3 in [1, 2, 3] True Membership
for x in [2,3,4] : print (x,end =
' ')
2 3 4
Iteration
Indexing, Slicing, and Matrixes49

Indexing and slicing works the same wa for lists as the do for strings
because lists are sequences,
Appropriating the following input –
L = ['C++'', 'Java', 'PWKRQ
]
PWKRn
Expr ession
Results
Description
L[2] 'PWKRQ' Offsets start at zero
L[-2] 'Java'
Negative: count from the
right
L[1:] ['Java', 'PWKRQ
] Slicing fetches sections
Built-in List Functions and Methods
PWKRQDGGVWKHDSSUR[LPDWHOLVWIXQFWLRQV–
Sr.N
o.
Function & Description
1
cmp(list1, list2)
No longer available in PWKRQ.
2
len(list)
Gives the total length of the list.
3
max(list)
Returns item from the list with max value.
4
min(list)
Returns item from the list with min value.
5
list(seq)
Converts a tuple into list.
PWKRQDGGVWKHIROORZLQJOLVWPHWKRGV–
Sr.N
o.
Methods & Description
1
list.append(obj)
Appends object obj to list
2
list.count(obj)
Returns count of how numerous times obj happens in the list
3
list.extend(seq)
Appends the contents of seq to list50

4 list.index(obj)
Returns the lowest index in the list that obj performs
5
list.insert(index, obj)
Inserts object obj into list at offset index
6
list.pop(obj = list[-1])
Removes and returns final object or obj from list
7
list.remove(obj)
Removes object obj from list
8
list.reverse()
Reverses objects of list in place
Tuples
A sequence of immutable PWKRQ objects is tuples. Just like lists, Tuples
are sequences. Tuples are sequences, unlike lists; this is the main
difference between tuples and lists. Lists use square brackets but Tuples
use parentheses.
As like Putting different comma-separated values, Creating a tuple is
simple. Optionally , RX can set those comma-separated values within
parentheses also. As example –
tup1 = ('Banana', 'W atermelon', 1990, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The blank tuple is written as two parentheses containing nothing –
tup1 = ();
Include a comma, to write a tup le containing a single value even there is
onlRQHYDOXH–
tup1 = (50,)
tuple indices start at 0, just like string indices. The can be sliced,
concatenated, and so on.
Accessing V alues in Tuples
To enter values in a tuple, use the square brackets for slicing along with
the index or indi ces to get the value obtainable at that index. As example

#!/usr/bin/pWKRQ3
tup1 = ('Banana', 'W atermelon', 1990, 2000)51

tup2 = (1, 2, 3, 4, 5, 6)
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
Output:
tup1[0]: Banana
tup2[1:5]: (2, 3, 4, 5)
You cannot update or change the values of tuple elements because Tuples
are permanent. You are able to take parts of the existing tuples to create
new tuples as the following example describes –
#!/usr/bin/pWKRQ3
tup1 = (10, 20,30)
tup2 = ('abc', 'x]
)
# Following action is not valid for
tuples
# tup1[0] = 100;
tup3 = tup1 + tup2
print (tup3)
Outpu
t:
(10, 20, 30, 'abc', 'x]
)
Delete T uple Elements
It is not possible to remove individual tuple elements but nothing wrong
with putting together another tuple with the undesired elements
discarded. Just use the del statem ent to explicitl remove an entire tuple.
As example-
#!/usr/bin/pWKRQ3
tup = ('Banana', 'W atermelon', 1990, 2000)
print (tup)
del tup;
print =(After deleting tup : )
print (tup)
Output:
('Banana', 'Watermelon', 1990, 2000)
After deleting tup :
Traceback (most recent call last):
File "main.pOLQHLQPRGXOH>
print (tup)
NameError: name 'tup' is not defined
Note − an exclu sion is raised. After Del tup, tuple does not exist
anPRUH.52

Basic Tuples Operations
As like strings, Tuples respond to the + and * operators. They involve
concatenation and repetition here too, except that the result is a new
tuple, not a string.
As a matter of fact, tuples react to all of the general sequence operations
we did on strings in the earlier chapter .
PWKRQ([Sression Results
len((5,6,7)) 3
(5,6,7) + (8,9,10) (5,6,7,8,9,10)
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!')
3 in (5,6,7) True
for x in (6,7) : print (x, end = '
')
6 7
Indexing, Slicing, and Matrixes
Indexing and slicing work the same wa for tuples as the do for strings
because tuples are sequences.
Assuming the following input –
T=('C++', 'Java', 'PWKRQ
)
PWKRQ([Sr ession Results Description
T[2] 'PWKRQ' Offsets start at zero
T[-2] 'Java'
Negative: count from
the right
T[1:] ('Java', 'PWKRQ
)
Slicing fetches
sections
No Enclosing Delimiters
No enclo sing Delimiters is either set of various objects, comma-marked,
written without identifLQJVmbols as explained in these short examples.
Built-in T uple Functions
PWKRQLQYROYHVWKHVXEVHTXHQWWXSOHIXQFWLRQV–
Sr.N
o.
Function & Description
1 cmp(tuple1, tuple2)53

Compares elements of both tuples.
2
len(tuple)
Gives the total length of the tuple.
3
max(tuple)
Returns item from the tuple with max value.
4
min(tuple)
Returns item from the tuple with min value.
5
tuple(seq)
Converts a list into tuple.
Dictionary
Each ke is segregated from its value b a colon (:), the items are
segregated b commas, and the entire thing is surrounded in curl braces.
A blank A blank dictionar without an objects is inscribed with just two
curlEUDFHVOLNHWKLV^`.
KeVDUHXQLTXHZLWKLQDGLFWLRQDUy . The keVDUHDQLPPXWDEOHGDWDWpe
such as strings, numbers, or tuples. Values are not unique within a
dictionary . The values of a dictionarFDQEHRIVHYHUDOVWDQGDUGV.
Accessing V alues in Dictionary
To acces s dictionar elements, use the usual square brackets along with
the keWRUHDFKLQJLWVYDOXH7KHUHLVDQHDV example –
#!/usr/bin/pWKRQ3
dict = {'Name': 'Shara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:
dict['Name']: Shara
dict['Age']: 7
If we tr to access a data item with a key , which is not a part of the
dictionary , we see an error as results –
#!/usr/bin/pWKRQ3
dict = {'Name': 'Shara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice']
Outpu
t:
File "main.pOLQH4
print "dict['Alice']: ", dict['Alice']
^54

SQWD[(UURU0LVVLQJSDUHQWKHVHVLn
call to 'print'
Updating Dictionary
B adding a new entr or a ke- value pair, RX can update a dictionar or
update a dictionar b modif LQJ an existing entry, or deleting an
existing entrDVVKRZQLQDQHDV example presented here.
#!/usr/bin/pWKRQ3
dict = {'Name': 'Shara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "JPS School" # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output:
dict['Age']: 8
dict['School']: JPS School
Delete Dictionar(OHPHQWs
You can either clear the whole contents of a dictionar or remove
individual dictionar elements. You can additionall delete an entire
dictionarLQDVLQJOHRSHUDWLRQ.
Just using the Del statement RX can explicitl remove a whole
dictionary . There is an easLQVWDQFH–
#!/usr/bin/pWKRQ3
dict = {'Name': 'Shara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entrZLWKNH 'Name'
dict.clear() # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output:
An exception is grown because, after Del dict,
the dictionarGRHVQRWHQGXUHDQmore.
Traceback (most recent call last):
File "main.pOLQHLQPRGXOH>
print ("dict['Age']: ", dict['Age'])
TSH(UURU
Wpe' object is not subscriptable
Pr operties of Dictionar.Hs
There are no restrictions in Dictionar values. The can be standard
objects either user -defined objects or anDUELWUDU PWKRQREMHFW.55

But, it is not true for the keV.
Remember the two important points about dictionarNHs –
Not more than one entr for each key. This means no duplica te ke is
allowed. The last assignment will win when duplicate keV are
encountered during the assignment. For instance –
#!/usr/bin/pWKRQ3
dict = {'Name': 'Shara', 'Age': 7, 'Name': 'Emma'}
print ("dict['Name']: ", dict['Name'])
Output: dict['Name']: Emma
The following Output: is produced when the above code is executed-
KeV must be permanent. This implies RX can use strings, numbers or
tuples as dictionar keV but something like ['ke
@ is not allowed. There
is an easLQVWDQFH–
#!/usr/bin/pWKRQ3
dict = {['Name']: 'Shara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
Outpu
t:
Traceback (most recent call last):
File "main.pOLQHLn

dict = {['Name']: 'Shara', 'Age':
7}
TSH(UURUXQKDVKDEOHWpe: 'list'
The following Output: is produced when the above code is executed-
Built-in Dictionar)XQFWLRQVDQG0HWKRGs
PWKRQDGGVWKHVXEVHTXHQWGLFWLRQDU functions –
Sr .N
o.
Function & Description
1
cmp(dict1, dict2)
No longer available in PWKRQ.
2
len(dict)
Gives the total length of the dictionary . This would be equal to
the number of items within the dictionary .
3
str(dict)
Produces a printable string representation of a dictionary
4 tSH YDULDEOH)56

Returns the tSHRIWKHSDVWYDULDEOH,IWKHGHFODUHGYDULDEOHLs
a dictionary, then it would return a dictionarWpe.
PWKRQDGGVWKHVXEVHTXHQWGLFWLRQDU methods –
Sr.
No.
Method & Description
1 dict.clear()
Removes all elements of dictionar dict
2 dict.cop )
Returns a shallow copRIGLFWLRQDU dict
3 dict.fr omkeV )
Make a new dictionarZLWKNHs from seq and values set to
value.
4 dict.get(key , default=None)
For keNHy, RXFDQUHWXUQVYDOXHRUGHIDXOWLINH not in
dictionary.
5 dict.has_ke NH)
Removed, use the in operation instead.
6 dict.items()
Returns a list of dict 's tuple pairs
7 dict.keV )
Returns list of dictionarGLFW
VNHs
8 dict.setdefault(key , default = None)
Similar to get(), however can set dict[ke@ GHIDXOWLINH is
not alreadLQGLFt
9 dict.update(dict2)
Adds dictionar dict2 's keYDOXHVSDLUVWR dict
Boolean Logic And Conditional
The Boolean data tSH can be 1 of two values, either True or False. Use
Booleans in programming to perform comparisons and to control the
flow of the application.
Booleans express the true values that are associated with the logic branch
of mathematics, which informs algorithms in computer science. Named
for the mathema tician George Boole, the word Boolean constantl begins
with a capitaliz ed B. The value s True and False will also regularl be
with a capital T and F respectively , as theDUHVSHFLDOYDOXHVLQ3thon.57

In this chapter , we’ll go over the basics RXOO need to understand how
Booleans work, including Boolean comparison and logical operators, and
truth tables.
Comparison Operators
In programming, comparison operators are used to comparing values and
evaluate down to a single Boolean value of either T rue or False.
The table below shows the Boolean comparison operators.
Operato
r
What it means
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
To unde rstand how these operators work, let’s assign two integers to two
variables in a program:
x = 5
 8
We know that in this example since x has a value of 5, it is less than y
which has a value of 8.
ApplLQJWKRVHWZRYDULDEOHVDQGWKHLUDVVRFLDWHGYDOXHVOHW’ s go through
the operators from the table above. In this program, we’ll charge PWKRn
to print out whether each compa rison operator evaluates to either True or
False.
x = 5
 8
print("x == [ )
print("x != [ )
print("x < [)
print("x > [!)
print("x <= [ )58

print("x >= [! )
To help us bette r understand this output, we’ll have PWKRQ also print a
string to show us what it’ s evaluating.
Output:
x == )DOVe
x != True
x < True
x > )DOVe
x <= T rue
x >= )DOVe
Following mathematical logic, in each of the expressions before, PWKRn
has evaluated:
Is 5 (x) equal to 8 ( ")DOVe
Is 5 not equal to 8? T rue
Is 5 less than 8? True
Is 5 greater than 8? False
Is 5 less than or equal to 8? T rue
Is 5 not lesss than or equal to 8? False
Although used integers here, we could replace them with float values.
Strings can also be used with Boolean operators. The are case-sensitive
unless emploLQJDQDGGLWLRQDOVWULQJPHWKRG.
We can look at how strings are compared in practice:
Samm 6DPP"
samm VDPP"
print("Samm VDPP: ", Samm VDPP)
Output:
Samm VDPP: False59

The string " Sammy " earlier is not equal to the string " sammy ", because
the are not precisel the same; one starts with an upper -case S and the
opposite with a lower -case s. But, if RX add an extra variable that is
assigned the value of " Sammy ", then theZLOOHYDOXDWHWRHTXDO:
Samm 6DPP"
samm VDPP"
also_Samm 6DPP"
print("Samm VDPP: ", Samm VDPP)
print("Samm DOVRB6DPP", Samm DOVRB6DPP)
Output
Samm VDPP: False
Samm DOVRB6DPP: T rue
You can too appl the other comparison operators including > and < to
compare two strings. PWKRQ will anal]H these strings lexicographically
using the ASCII values of the characters.
We can also estimate Boolean values with comparison operators:
t = T rue
f = False
print("t != f: ", t != f)
Output
t != f: T rue
The above Output that T rue is not equal to False.
Logical Operators
There are three logical operators that are applied to compare values. They
assess expressions down to Boolean values, returning either True or
False . These operators are and , or , and not and are described in the
table below .
Operator What it means What it looks like
And True if theERWKDUHWUXe x and y
Or True if at least 1 is true x or y
not True onlLILWIDOVe not x60

Logical operators are tSLFDOO applied to evaluate whether two or more
expressions are true or not true. For instance, the can be applied to
determine if the grade is passin g and that the student is enrolled in the
course, and if bo th cases are true then the student will be allowed a grade
in the sVWHP Another example would be to decide whether a user is a
valid active cust omer of an onlin e shop based on whether the have shop
credit or have made an investment in the past 6 months.
To understand how logical operators work, let’s estimate three
expressions:
print((9 > 7) and (2 < 4)) # Both original expressions are T rue
print((8 == 8) or (6 != 6)) # One original expression is True
print(not(3 <= 1)) # The original expression is False
Output
True
True
True
T ruth T ables
There is a lot to stud about the logic branch of mathematics, but we can
selectivel learn some of it to promote our algorithmic thinking when
programming.
Below are truth tables for the comparison operator ==, and ever of the
logic operators and, or, and not. While RX ma be capable to reason
them out, it and can also be necessar to work to memorize them as that
can make RXUSURJUDPPLQJGHFLVLRQPDNLQJSURFHVVTXLFNHr .
== Truth T able
x == y Returns
True == True True
True == False False
False == True False
False == False True
AND T ruth Table61

x and y Returns
True and True True
True and False False
False and True False
False and False False
OR T ruth T able
x or y Returns
True or True True
True or False True
False or True True
False or False False
NOT T ruth Table
not x Returns
not True False
not False True
Truth tables are basic mathematical tables used in logic and are useful to
memorize or keep in mind when constructing algorithms (instructions) in
pWKRQSURJUDPPLQJ
Using Boolean Operators for Flow Control
To contr ol the stream and outcomes of a program in the form of flow
control statements, use a condition followed bD clause .
A condition evaluates down to a Boolean value of True or False,
displaLQJ a point where a decision is made in the program. That is, a
condition would show RXLIVRPHWKLQJHYDOXDWHVWRT rue or False.
The clause is the block of code that follows the condition and dictates
the outcome of the program. That is, it is the perform this part of the
construction “If x is true, then do this.”
The code below shows a cas e of comparison operators working in
tandem with conditional statements to control the flow of a PWKRn
program:
if grade >= 65: # Condition
print("Passing grade") # Clause62

else:
print("Failing grade")
This program will estimate whether each student’ s grade is passing or
failing. In the case of a student with a grade of 83, the first statement will
estimate to True , and the print statement of Passing grade will be
triggered. In the case of a stude nt with a grade of 59, the first statement
will estimate to False , so the program will move on to perform the print
statement tied to the else expression: Failing grade .
Because ever individual object in PWKRQ can be evaluated to True or
False, the PEP 8 StOH Guide recommends against associating a value to
True or False because it is less readable and will constantl return an
unexpected Boolean. That is, RX should bSDVV using if samm ==
True : in programs. Instead, associate sammy to another non-Boolean
value that will return a Boolean.
Boolean operators present conditions that can be applied to decide the
eventual outcome of a program through flow control statements.
Constructing "While" Loops In PWKRn
A while loop implements the reproduced execution of code based on a
given Boolean condition. The code that is in a while block will complete
as long as the while statement evaluates to T rue.
You can think of the while loop as a copLQJ conditional statement. After
an, if statement, the program remains to execute code, but in a while
loop, the progra m bounces back to the start of the while statem ent until
the condition is False.
As expo sed to for loops that execute a certain number of tim es, while
loops are conditionall based, so RX don’t need to know how many
times to repeat the code going in.
While Loop
In PWKRQZKLOH loops are constructed like so:
while [a condition is T rue]:
[do something]
The something that is being done will continue to be executed until the
condition that is being assessed is no longer true.63

Let’s build a small program that executes a while loop. In this program,
we’ll ask the user to input a pass word. While going ended this loop, there
are two possible outcomes:
If the program password is correct, the while loop will exit.
If the program password is not correct, the while loop will
continue to execute.
We’ll create a file named password.py in our text edito r of choice, and
start bLQLWLDOL]LQJWKHYDULDEOH password as an emptVWULQJ:
password.py
password = ''
The empt string will be applie d to take input from the user within the
while loop.
Now, we’ll construct the while statement with its condition:
password.py
password = ''
while password != 'password':
Here, the while is accompanied b the variable password . W e are
looking to see if the variable password is set to the strin g password , but
RXFDQWDNHZKLFKHYHUVWULQJou’d like.
This proposes that if the user inputs the string password , the n the loop
will stop and the application will continue to execute an code outside of
the loop. However , if the string that the user inputs are not equal to the
string password , the loop will continue.
Next, we’ll add the block of code that produces something within the
while loop:
password.py
password = ''
while password != 'password':
print('What is the password?')
password = input()64

Inside of the while loop, the application runs a print statement that helps
for the password. Then the variable password is fixed to the user’s input
with the input () function.
The application will check to see if the variable password is allocated to
the string password , and if it is, the while loop will end. Let’ s give the
program added line of code for when that happens:
password.py
password = ''
while password != 'password':
print('What is the password?')
password = input()
print=(Y es, the password is ' + password + '. Y ou maHQWHr.)
The last print() statement is outward of the while loop, so when the user
enters the password as the password, the will see the final print
statement outside of the loop.
However , if the user never enters the word password then the will
never get to the last print() statement and will be stuck in an infinite
loop.
An infinite loop happens when a program keeps doing within one loop,
never leaving it. To exit out of infinite loops on the command line, enter
CTRL + C.
pWKRQSDVVZRUGSy
You’ll be prompted for a password, and then maH[DPLQHLWZLWKYDULRXs
possible inputs. Here is example output from the program:
Output
What is the password?
hello
What is the password?
sammy
What is the password?
PASSWORD65

What is the password?
password
Yes, the password is password. Y ou maHQWHr.
Constructing "For Loops" Loops In PWKRn
A for loop implements the returned execution of code based on a loop
counter or loop variable. This implies that for loops are used most often
when the number of iterations is identified before entering the loop,
unlike while loops which are conditionallEDVHG.
For Loops
In PWKRQ for loops are constructed like so:
for [iterating variable] in [sequence]:
[do something]
The something that is being made will be executed until the sequence is
over.
Let’s look at a for loop that iterates through a range of values:
for i in range(0,5):
print(i)
When we run this program, the output views like this:
Output
0
1
2
3
4
This for loop fixes up i as its iterating variable, and the chain exists in
the range of 0 to 5.
Then within the loop, print out one integer per loop iteration . Hold in
mind that in programming tend to start at index 0, so that is whDOWKRXJh
5 numbers are printed out, theUDQJHIURP.66

You’ll usuall see and appl for loops when a program needs to repeat a
block of code a number of times.
For Loops using range()
One of PWKRQ’ s built-in permanent sequence tSHV is range(). In loops,
range() is used to control how multiple times the loop will be repeated.
When operating with range() , RX can cross between 1 and 3 integer
arguments to it:
start states the intege r value at which the sequence begins if this is not
involved then start begins at 0
stop is eternall required and is the integer that is counted up to but not
involved
step sets how much to increase the next iteration if this is omitted then
step defaults to 1
We’ll look at some samples of passing different argumen ts to the
range().
First, let’s just pass the stop argument, so that our sequence set up is
range(stop):
for i in range(6):
print(i)
In the program earlier, the stop argument is 6, so the code will iterate
from 0-6 (exclusive of 6):
Output
0
1
2
3
4
5
Next, we’ll see at range(start, stop), with values passed for when the
iteration should start and for when it should stop:
for i in range(20,25):67

print(i)
nowhere, the range goes from 20 (inclusive) to 25 (exclusive ), so the
output:
Output
20
21
22
23
24
The step argument of range() is relate d to defining stride while slicing
strings in that it can be applied to skip values within the sequence.
With all three arguments, step comes in the last position: range(start,
stop, step) . First, let’ s applD step with a positive value:
for i in range(0,15,3):
print(i)
In this sample, the for loop is set up so that the numb ers from 0 to 15
print out, but at a step of 3, so that simpl ever third number is printed,
like so:
Output
0
3
6
9
12
We can also appl a negative value for our step argument to iterate
backward, but we’ll have to adjust our origin and stop arguments
accordingl:
for i in range(100,0,-10):
print(i)68

Here, 100 is the start value, 0 is the stop value, and -10 is the ra nge, so
the loop begins at 100 and ends at 0, reducing b 10 with each iteration.
We can see this happen in the output:
Output
100
90
80
70
60
50
40
30
20
10
In PWKRQ for loops often obta in the application of the range () sequence
tSHDVLWVSDUDPHWHUVIRULWHUDWLRQ.
For Loops using Sequential Data T SHs
Lists and other data sequence tSHV can also be leveraged as repetition
parameters in for loops. Rather than iterating through a range (), RX can
assign a list and iterate through that list.
sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead']
for shark in sharks:
print(shark)
In this sample, we are printing out each item on the list. Though we
applied the variable shark , we could have called the variable an other
valid variable name and we would get the identical output:
Output
hammerhead
great white69

dogfish
frilled
bullhead
Nested For Loops
Loops can be nested in PWKRQ.
A nested loop is a loop that happens within another loop, structurally
related to nested if statements. These are created like so:
for [first iterating variable] in [outer loop]
[do something] # Optional
for [second iterating variable] in [nested loop]
[do something]
The program first meets the outer loop, executing its earliest iteration.
This first iteration triggers the inner , nested loop, which then runs to the
conclusion. Then the program repeats back to the top of the outer loop,
creating the second iteration and repeatedl triggering the nested loop.
Again, the neste d loop runs to the conclusion, and the applicatio n repeats
back to the top of the outer loop until the sequence is finished or a break
or other statement disrupts the process.
Let’ s perform a nested for loop so we can take a closer look. In this
instance, the outer loop will iterate within a list of intege rs called
num_list , and the inner loop will iterate through a list of strings called
alpha_list .
num_list = [1, 2, 3]
alpha_list = ['a', 'b', 'c']
for number in num_list:
print(number)
for letter in alpha_list:
print(letter)
When we run this program, we’ll receive the following output:
Output
170

a
b
c
2
a
b
c
3
a
b
c
The output illustrates that the program finishes the first iterati on of the
outer loop b printing 1, which then triggers the fulfillment of the inner
loop, printing a, b, c continuous ly. Once the inner loop has finished, the
application returns to the top of the outer loop prints 2, then again prints
the inner loop in its entiret DEF HWF.
Nested for loops can be valuable for iterating through items within lists
formed of lists. In a list composed of lists, if we appl just one for loop,
the application will output each internal list as an item:
for list in list_of_lists:
print(list)
Output
['hammerhead', 'great white', 'dogfish']
[0, 1, 2]
[9.9, 8.8, 7.7]71

Conclusion
PWKRQ is a strong programming language that gives еаѕу uѕе оf thе соdе
linеѕ, great mаintеnаnс е hаndlin g, and eas dеbugging. It hаѕ expanded
imроrtаnс е асrо ѕѕ the globe as Gооglе hаѕ mаdе it оnе оf its of ficial
рrоgrаmming languages.
Pуthоn iѕ a favorite choice among programmers due to its eas sQWDx
and its ease in debugging and error fixing.
Similаr to mаnу other intеrрrеtаtivе lаnguаgеѕ, Pуthоn offers mоrе
flеxibilitу than соmрilеd lаnguаgеѕ, аnd it саn bе efficiently uѕеd tо
intеgrаtе diѕраrаtе ѕуѕtеmѕ. Cеrtаinlу, Pуthоn is a vеrѕаtilе рrоgrаmming
language with ѕеvеrаl аррliс аtiоnѕ uѕеd in divеrѕе fiеldѕ.
Now that RX have reached the end of this book, RX should be able to
comprehend the basics of PWKRQ and write simple lines of codes. You
should also be able to comprehend the difference between the various
tSHV of data, the sQWD[ in PWKRQ the most important functions and
modules. Although the road to becoming a successful programmer is still
long, I hope this book will pave the path for RXU success, and I'm
positive that, if RX use the knowledge contained in it in the right way , it
will definitelKHOSou reach RXUJRDOV.
Thanks for reaching the end of this book, and I hope RXHQMRed it.72

Оглав ление
Introduction 4
A Comprehensive Background 6
Version 1 6
Version 2 7
Version 3 8
How to Download and Install PWKRn 9
Install And Run PWKRQ,Q0DF26X 10
Install And Run PWKRQ,Q8QL[$QG/LQXx 10
Install And Run PWKRQ,QW indows 11
The PWKRQ(QYLURQPHQWDOV ariables To Note 11
Opening A Console On Mac OS X 14
Opening A Console On Linux 14
Opening A Console On W indows 14
Interacting With PWKRn 15
Starting and Interacting with PWKRn 11
V ariable 17
Basic Operators 22
Loops 30
Native PWKRQ'DWDWpes 33
Numbers 35
Strings 39
Lists 47
Tuples 51
Dictionary 54
Boolean Logic And Conditional 57
Constructing "While" Loops In PWKRn 63
Constructing "For Loops" Loops In PWKRn 66
Conclusion 1473

Сообщить о нарушении / Abuse

Все документы на сайте взяты из открытых источников, которые размещаются пользователями. Приносим свои глубочайшие извинения, если Ваш документ был опубликован без Вашего на то согласия.