0 ratings0% found this document useful (0 votes) 344 views44 pagesComputer Programming PYTHON PDF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Python
Python is the name of a high-level, interpreted, general-purpose programming language. 1 4
sign philosophy str on code readability. Some of the common python GUI framewo, 7
PyQt, Tkinter and PyGtk. The chapter closely examines these key frameworks of Python as
its advantages to provide an extensive understanding of the subject.
Ks are
Wellas
Python is an interpreter, object-oriented programming language similar to PERL that has gaingy
popularity because of its clear syntax and readability. Python is said to be relatively easy to jean,
and portable, meaning its statements can be interpreted in a number of operating systems, inclu.
ing UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Microsoft Windows 98.
‘The source code is freely available and open for modification and reuse. Python has a significant
number of use
A notable feature of Python is its indenting of source statements to make the code easier to reaq.
Python offers dynamic data type, ready-made class, and interfaces to many system calls and librar.
ies. It can be extended, using the C or C++ language.
Python can be used as the script in Microsoft's Active Server Page (ASP) technology. The score.
board system for the Melbourne (Australia) Cricket Ground is written in Python. Z Object Publish
ing Environment, a popular web application server, is also written in the Python language.
Advantages of Python
Readable and Maintainable Code
While writing a software application, you must focus on the quality of its source code to simplify
maintenance and updates. The syntax rules of Python allow you to express concepts without writ-
ing additional code. At the same time, Python, unlike other programming languages, emphasizes
‘on code readability, and allows you to use English keywords instead of punctuations. Hence, you
can use Python to build custom applications without writing additional code. The readable and
clean code base will help you to maintain and update the software without putting extra time and
effort.
Multiple Programming Paradigms
Like other modern programming languages, Python also supports several programming paradig™
It supports object oriented and structured programming fully. Also, its language features support
various concepts in functional and aspect-oriented programming. At the same time, Python als0
features a dynamic type system and automatic memory management. The programming pa
digms and language features help you to use Python for developing large and complex softwar?
applications.th Major Platforms and System
“ye S
7 ynon is supports many operating systems
yen Fie on specific platforms ana tools. Also, You can even use Python interpreters
fos you to 300 f0 rm the some a eget eee programming, Fat
fe are not required to recompile the den multiple platforms without re ‘ompilation.
7 cation code without recompili Je after making any alteration. You can run the
i compiling and check thé
[Med APP feature makes it easier for yout the impact of changes made to the code
i 10 make changes to the code without increasing
ust standard Library
slate and robusta da makes Python score over other programming languages. The
gna Nbravy o a i 10 choose from a wide range of modules according to your Precis®
peed Bach mod! er jer enables you to add funetionality to the Python application without
iti additional oot For instance, while writing a web application in Python, you can use SPe-
ie modules t0 HD jement web services, perform string operations, manage ‘operating system
interface OF work with internet protocols. ss
any Open Souree Frameworks and Tools
jsan open source programming language, Python helps you to curtail software development cost
significantly. You can even use several open source Python frameworks, libraries and development
tools to curtail development time without increasing development cost. ‘You even have option to
choose from a wide range of open source Python frameworks and development tools according to
your precise needs. For instance, you can Simplify and speedup web application developmen’ by
vying robust Python web frameworks like Django, Flask, Pyramid, Bottle and Cherrypy. Likewis®,
you can accelerate desktop GUL application HTovelopment using Python GUI frameworks and tool-
tits like PyQT, PyJs, PyGUI, Kivy, PyGTK and WxPython,
Simplify Complex Software Development
Python is a general purpose programming language. Hence, you can use the programming lan-
guage for developing both desktop ‘and web applications. Also, you ean use python for developing
‘on is designed with features to facilitate data
complex scientific and numeric applications. Pythi
analysis and visualization. You can take advantage of the data ‘analysis features of Python to create
custom big data solutions wit ‘tra time and effort. At the same time, the data visu-
:thout putting ex!
alization libraries and APIs provided by Python help you to visualize and present data in a more
f appealing and effective way. Many python Python to accomplish artificial
developers even use
intelligence (AI) and natural Janguage proce:
sing tasks.
Adopt Test Driven Development
ftware application rapidly. Also, you can build the
You can use Python to create prototype of the sol 1
f software application directly from the prototype simply by. refactoring the Python code. Python
even makes it easier for you to perform ‘coding and testing ‘simultaneously by adopting test driven
development (TDD) ‘te the required tests before writing code and use
approach, You can eas) WH
[213Python GUI Frameworks |
Pithon is an interactive programming language and getting started with programmin
shical User Interface) framework is not much of a diffienlt task. Python has a
tions for GUT frameworks. Here are 4 Best Python GUT Frameworks:
a Gy
range ng
divers
Prot
PxQt tse python binding of the open-source widget-toolkit Qt. which also functions as a 788-Diiat
form application development framework. Qt is a popular C++ framework for writing GUT applica
trons for all major desktop, mobile, and embedded platforms (supports Linux. Windows, Macos
Android, iOS, Raspberry Pi, and more).
Features of PyQT
Here. are important features of PyQt. PyQt consists of more than six hundred classes covering y
range of features such as-
+ Graphical User Interfaces
+ SQL Databases
+ Web toolkits
+ XML processing
+ Networking.
‘These features can be combined to create advanced UIs as well as standalone applications. A lot of
major companies across all industries use Qt. Some examples are LG, Mercedes, AMD, Panasonic
Harman, ete
PyQt Versions
PyQt is available in hwo editions, PyQt4 and PyQts. PYQLy provides glue code for binding 4.x and
5% versions of the Qt framework while PyQt5 provides a binding for only the 5.x versions. As a
result, Py(Qts is not backward compatible with the deprecated modules of the older version.
Need of PyQt
+ PyQt brings together the Qt C++ cross-platform application framework and the cross-plat-
form interpreted language Python.
+ Qtismore than a GUI toolkit. It includes abstractions of network sockets, threads, Unicode,
regular expressions, SQL databases, SVG, OpenGL, XML, a fully functional web browse #
help system, a multimedia framework, as well as a rich collection of GUI widgets./ [+ |
Python
pam
employ a signal/slot meet
ely coupled making it ¢;
nism f i
san for communicating between objets that is tye
includes Qt Designer, ne usible software components,
includes Qt Designer, a gra :
ign code from Qt D ee al user interface designer. PyQt is able to generate
python Oe Designer. ‘© possible to add new GUT controls written in Py-
ae
+ eb"
100s
180
imple but powerful object-orie
Imifa, but its power means that lange
t reted nature means that Python pro;
to compile, link and run developmen
entated language Its simplicity makes it easy
ad complex applications can be created. Its in
derammers are very productive because there is no
cycle.
uch of Python he comes from its comprehensive set of extension modules providi
wide variety pend including HTTP servers, XML parsers, datab oes data
compression too eae of course, graphical user interfaces Extension modules gre usualy
mplemented in either Python, C or C+-+, Using tools such as SIP it is relatively straight
{onward to create an extension module that encapsulates an existing C or C++ library. Used
in this way, Python can then become the glue to create new applications from established
iibraries.
yt combines all the advantages of Qt
a is able to exploit it with the ie ee eth
thinter
skater is actually an inbuilt Python module used to create simple GUI apps. It is the most com-
nonly used module for GUI apps in the Python.
pron provides the standard library Tkinter for ereating the graphical user interface for desktop
used applications.
peveloping desktop based applications with python Tkinter is not a complex task. An empty
“hiner top-level window can be created by using the following steps-
+ Import the Tkinter module.
+ Create the main application window.
+ Add the widgets like labels, buttons, frames, etc. to the window.
ce on the user's computer screen.
+ Call the main event loop so that the actions can take pla
Example:
1. # !/usr/pin/python3
2. from tkinter import *
3. fereating the application main window~
4 top = TKO.
5. #Entering the event main loop
6
+ top.mainloop ()
ee
ETT‘comp
output:
‘
ii widgets
ae checkbutton, entry, etc. that are used to build the
‘There are various: widget
_
poetion GUL Applications
mon ion
ious Kinds of buttons £0 the python application.
a
‘used to add val
was on the window.
s like button, canvas,
eee
Sno. | Widget__—+
a st saat ‘The Button is
[1 aoe varieties 0.
[2__}een Tothe Cheekbutton is used £0 “japly the CheckBbatton on the windove——————_——
Text field to the user. It is commonly
— Greckbutton | The Check is b
Entry “The entry widget is used to display the single-line
: used to accept fi ae ited end i _| :
Standard Data Types
A variable can hold different types of values. For example, a person’s name must be stored as a
string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below:
‘Numbers
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a
variable. For example;
a= 3, b-=5 #a and b are number objects
Python supports 4 types of numeric data.
1. Int (signed integers like 10, 2, 29, ete.)
2. Long (long integers used for a higher range of values like 9080908001, -ox19292921, ete.)
226a /
(float is used to store floating point numbers lik
R pers like
a. Float ore
3 902, 15.2, ef¢
comple (complex numbers like 2.14), 9.0 + 2.9 ,
’ oe ai, ete.)
us to use a lower-case
_pallows us (0 US ower-case L to be used with Jong int
ie reese LO avoid confusion. g, integers. However, we must always use
"pp
al
per contains an ordered pair, i
ex nat ed pair, i.e, x + iy wh
hy here x and y denote the real and
om?! ave
co ee a respectively.
“can be defined as the sequence of characters represented in the quotation ar
in, we cart USE single, double, or triple quotes to define a string,
ng handling python is a straightforward task since there are various inbuilt functions a7 d
ors provided.
inte case of string handling, the operator + is used to concatenate two strings as the operation
‘pel python’ returns “hello python”.
he operator *
thon “+
the following, example illustrates the string handling in python.
vpello javatpoint’ #string strl
js known as repetition operator as the operation “python “ *2 return Python Py
a. strl
ste? =‘ how are you’ #string str?
3, print (stzi[0:2]) #printing first two character using 5
_ print (stri{4]) #printing 4th character of the string
5, print (stri*2) #printing the string tuice
g. print (stri + str2) printing the concatenation of
Output:
lo javatpointhello javatpoint
hello javatpoint how are you
List
Lists are similar to arrays in C. However; the
stored in the list are separated with a comma (
data of the list. The co}
he same way as they W'
data of different types. The items
list can contain
brackets []-
and enclosed within square
‘We can use slice [:] operators to access the mneatenation operator (+) and
ere working with the strings.
repetition operator (*) works with the list in @
[227
elConsider the following example-
1 = (1, “hi”, “python”,
rh
2
print
print
. print
. print
. print
Output:
(2)
i, ‘pind
1, ‘hit,
fl, ‘nity
La, ‘Bits
Tuple
A tuple is similar to the list in many ways. Like lists, tup]
of different data types. The items of the tuple are separate
rentheses ().
‘Atuple is a read-only data structure as we can’t modify the size an\
‘python’, 2,
‘python’, 2,
ee
Gomputer Programming Languages J
2) |
ais
cutor2)ye
ae
abe
ata
;
‘python’, 2]
1, ‘hit, ‘python’, 2]
Rn evenom et he, ones)
Jes also contain the collection of the items
.d with a comma (,) and enclosed in pa-
d value of the items of a tuple.
Let's see a simple example of the tuple.
whi”, “python”, 2)
leace
2. print (t(2:1)s
3. print (t[0:1])+
4. print (t);
5. print (t + 8);
6. print (t * 3);
7, print (type(t))
8. t[2] = “hi”;
Output:
(python’, 2)
Chi’,)
(*hi', ‘python’, 2)
Chit,
‘python’, 2, ‘hi’, ‘python’, 2)
228
rrr re
‘python’, 2, ‘hit
recent call last):
Line 8, in
+ opject does not support item as
pictionary
san ordered set of a k
res a specific value.
ions) i ey-value pair of items. It is like an associative array or a h
sable where each key sto! Key can hold any primitive data type aierean alias
a0
bitrary Pytion object.
in the dictionary are sep:
g example
‘alex’, 3:" john’,
he items arated with the comma and enclosed in the curly braces {}
|
|
| Consider the followin:
|
mike’ }s
Cogs (ait gimmy!s 2+
sist name is “+dl11)7
2. print (
3, print ("2nd name is “4 d141)7
4. print (di
print (d-keys0)#
6. print (d.values ())i
Me
Output:
ist name is Jimmy
na name is mike
fi: ‘oimmy’, 2: ‘ALEX, sjohn’, 4: ‘mike’}
i 2,3, 4
{‘simmy’, ‘Alex’, ‘john’, ‘mike’]
/ython Syntax
‘The syntax of the Python programming
language is the set of rules which defines how a Python
program will be written.
Python Line Structure
A Python program is divided into a number of logical lines and every logical line is terminated by
m one or more physical lines.
the token newline. A logical line is created frotComputer Programming Languages -——_
tabs, form feeds pos
A line contains only space
Python interpreter ignores it. i
A physical line is a sequence of characters terminated by an end-of-line sequence (in windows gj, rf
called CR LF or return followed by a linefeed and in Unix, it is called LF or linefeed). is
Noman phanmronrnerrmt oe a
A gam Optom Waows Help
J
Comments in Python
‘Acomment begins with a hash character (#) which is not a part of the string literal and ends at the
the # character up to the end of the line are part of the
end of the physical line. All characters after tl
comment and the Python interpreter ignores them. It should be noted that Python has no multi-
lines or block comments facility.
76 python-syntin-test-E/python-programs/python-syntar test ots
File fait Format Run Options Windows Help
ee a
me snitial value of x 25 1
[bt wo:
[PE Sprint ("These aze two coments") #Print @ string.
=
m3 COED
Joining Two Lines
When you want to write a long code in a single line you can break the logical line in two or more
physical lines using backslash character(\). Therefore when a physical line ends with a backslash
characters(\) and not a part of a string literal or comment then it can, join another physical line.
“7 pphon-sytatet E/pytnon programa/pthon-ryntxtet
File Fait Format Run Options Windows Help
° ai
4
Af uss0 and 30 \
fand wd and 22 \
land y>3 and 24:
print("Tais is an example of Line joxning.)
at
Lne|coks
faa]tiple Statements on a Single Line
yw
an write two separate statemey
cc
you
‘nts into
line.
wi
Indentation
dentation.
a single line
|
using a semicolon G) character between
C)
This is a program with single space indentation.
This itl i ation.
is is a program with single tab indentati
—
ee
fs,
231Computer Programming Languages |
Here is an another program with an indentation of a single space + a single tab
ey
Python Coding Style
+ Use 4 spaces per indentation and no tabs.
+ Donot mix tabs and spaces. Tabs create confusion and it is recommended to use only spac-
es.
+ Maximum line length: 79 characters which help users with a small display.
+ Use blank lines to separate top-level function and class definitions and single blank line to
| separate methods definitions inside a class and larger blocks of code inside functions.
+ When possible, put inline comments (should be complete sentences).
and statements.
+ Use spaces around expressioi
Python if-elif-else
The if-elif-else statement is used to conditionally execute a statement or a block of statements.
Conditions can be true or false, execute one thing when the condition is true, something else whe”
the condition is false.
The Python if Statement
‘The Python if statement is same as it is with other programming languages. It executes a set Of
statements conditionally, based on the value of a logical expression.
Here is the general form of a one way if statement.
232WV
a
Y
| at
apreasion
gratement_t
gratement_2
spove case, expression specifies the conditions whi
pate : fies the conditions which are based
fa Boolean expressions evaluated it produces either a value of aa
ea rue the same amount of indented statement() following if wil be Beet ee
ed. This group
cut gement(s) is called a block.
j
| python jf-else Statement
j
| jppython if-else statement, if has two blocks, i i
| : im tie , one following the expression and other following the
syntax
; expression =
j
statement_1
statement_2
i cle |
i
j
statement_3
statement_4
ates to true the same amount of indented statements(s)
n evaluates to false the same amount of indented
Inthe above case if the expression evalu
le. The program will print
‘ollowing if will be executed and if the expressio
Satements(s) following else will be executed. See the following example
the second print statement as the value of ais 10.
10
€4a19) :
Print (“value of a is greater than 10”)
Print (“Value of a is 10”)
gs”
Ve
“Ike of a is 10Computer Programming Languages eee |
Flowchart
Python if-elif-else Statement
Sometimes a situation arises when there are several conditions. To handle the situation Python
allows adding any number of elif clause after an if and before an else clause. Here is the syntax.
Syntax
if expression! =
statement_1
statement_2
£ expression? :
ement_3
statement_4
expression3 :
statement_5
statement _6
statement 7
statement_&
eee
eega 2)
ie eypetvarl) == int);
print (“Type of the variabig
aif (tyPe(varl) == floaty;
© print (“Type of the variable
gif (type(varl) == complex):
print (“Type of the variable
ef (type(varl) == bool):
print (“Type of the variable
elif (type(varl) == str);
print ("Type of the variable
elif (type (var) tuple):
print (“Type of the variable
elif (type (varl) dict):
print (“Type of the variable
lif (type (varl) list):
print ("Type of the variable
else:
print (“Type of the variable
Output:
Type of the variable is Complex
Flowchart
is
is
is
is
is
is
Integer)
Float”)
Complex”)
Bool”)
String”)
Tuple”)
Dictionaries”)
List”)
Unknown")Computer Programming Languages -——__
eee
Nested if-else Statement
° wa heck more than one cong;
In general nested if-else statement is used a ae pare a eee evalu om,
iti rn ttom and check e: d aluates to trug
Conditions are executed from top to bo! oe siatod with the con
ie not. Ifa true condition is found the statement(s) block associated dition executes
otherwise it goes to next condition.
Syntax
Here is the syntax:
ion]
if expre!
if expression? :
statement_3
statement_4
else :
statement_5
statement_6
else :
statement_7
statement_8
In the above syntax expressiont is checked first,
goes to next if - else part otherwise it oes to the
statement_8 etc. Within the if - else if expression
will execute otherwise statement_s,
if it evaluates to true then the program control
¢ last else statement and executes statement_7,
n2 evaluates true then statement_3, statement_4
statement_6 will execute. See the following example.
age = 38
if (age >= 11):
ee ”)
if (age <= 20 or age >= 60);
Print ("Ticket price is $12”)
else:
Print ("Tic kit price is $20)
else:
Print (“You're not eligible to buy a ticket.)
I Reena ct (iraPython,
utr
ye eligible to see the Fy
. cotball match
it price is $20
= 11) evaluates to True
we example age is set to 38, therefore
e above pI is set to 38, therefore the first expression (aj
‘ 3s ge
ml F '
ssociated print statems A
and the ent prints the string “
program control ene “You are eligible to s ‘ atch”.
sere after P oer ce goes 10 next ifstatement and the lib to see the Foothall match
wer js matched and prints “Tic kit prices $12" indition ( 38 is outside <=20 or
flowchart
pane CRE
Use the and Operator jn an if Statement
fereate two boolean objects
x= False
y = True
tthe validation will be THe OntY or a. ae
if x and y+
print (‘Both x and y are a
else:
print ve 49 Fase oF Y 3 pause or both « and ¥ G58 ralse’)
Output:
False
ee poth x and y are Fa
Use the in Operator in an jfStatement
fereate a stringa Computer Programming Languages _. . =
oe
‘jquery’
fereate a list
1 = [‘JavaSeript’, ‘jQuery’, ‘ZinoUI’]
# in operator is used to replace various expressions that use the or operator
print (s + ‘Tutorial’)
statement with or operator
s == ‘JavaScript’ or s == ‘jQuery’ or s == ‘ZinoUI’:
print(s + ‘Tutorial’)
Output:
jQuery Tutorial
jQuery Tutorial
Write an if-else in a Single Line of Code
create 2 integer
#if n is greater than 500, n is multiplied by 7, otherwise n is divided by 7
result =n* 7 if n > $00 elsen/7
print (result)
Output:
150
21.428571428571427
Define a Negative if
If a condition is true the not operator is us
Samael, ed to reverse the logical State, then logical not operator
#oreate a integerPython
a
x
int
uses tne ROE operator to reverse the result of th Toe
r result of the logical expres
-*
print ("the value of x different from 50”)
else
print (‘the value of x is equal to 50°)
output:
20
the value of x different from 50
python for Loop
Like most other languages,
python for loop js used to iterate over the items of any se
tuple ete. The for loop is also used to access elements fro1
tuple) using built-in funetion range().
Python has for loops, but it differs a bit from other like C or Paseal. In
quence including the Python list, string,
vn a container (for example list, string,
Syntax
for variable_name in sequence?
statement_1
statement_2
Parameter
a
Description ee _
Trindicates target variable which wil set ‘anew value for each iteration ofthe loop.
“A sequence of values that will be assigned to the target variable variable_name,
Jalnes are provided using a Hist oF & String O° from the built-in function range.
Block of program
a
statements.
statement_a, statement_2
Example: Python for loop-
indices start at 0 and end at 3
>>> the List has four elements,
Bs cl tase = famed’, lus green”, “Black”]
——————————‘Computer Programming Languages |
In the above example color_list is a sequence contains a list of various color names. When the for
loop executed the first item (i.e. Red) is assigned to the variable c. After this, the print statement
‘will execute and the process will continue until we reach the end of the list.
Python for Loop and Range() Function
The range() function returns a list of consecutive integers. The function has one, two or three pa-
rameters where last two parameters are optional. It is widely used in for loops. Here is the syntax.
range (a)
range (a,b)
range (a,b,c)
range(a) : Generates a sequence of numbers from 0 to a, excluding a, incrementing by 1.
Syntax
for in range () :
Example:
>>> for a in range(4):
int (a)
3
>>>
range(a,b): Generates a sequence of numbers from a to b excluding b, incrementing by 1
240oo
syntax
eyariable” in range (“st
gor
. art_number”, “end number”)
sample:
jor for a in range (2,7):
print (2)
>
range(a,b,c): Generates a sequence of numbers from a to b excluding b, incrementing by c.
Example:
>>> for a in range (2,19,5)+
print (a)
1
12
17
>»
Python for Loop: jterating OveT tuple, List and Dictionary
Example: Iterating over tuple. '
| ‘ : ts the number of even and odd numbers from a series of numbers-
sane 6, Te 81 9) 4 Declaring the tuple
Sree
numbers = (1, 2+ 3+
count_odd = 0
count_even = 0
for x in numbers?
if x 3 2:
[244Computer Programming Languages
count _oddt=1
else:
count_event=1
print (“Number of even numbers :", count even)
print (“Number of odd numbe:
:", count_odd)
Output:
Number of even numbers:4
Number of odd numbers: 5
in the above example a tuple named numbers is declared which holds the integers 1to 9, The best
way to check iffa given number is even or odd is to use the modulus operator (54). The operate
Fetvens the remainder when dividing two numbers. Modulus of 8 % 2 returns 0 as 8 is divided
2, therefore 8 is even and modulus of 5 % 2 returns 1 therefore 5 is odd.
The for loop iterates through the tuple and we test modulus of x % 2 is true or not, for every item
in the tuple and the process will continue until we rich the end of the tuple. When itis true count
even increase by one otherwise count_odd is increased by one.
Finally, we print the number of even and odd numbers through print statements.
Example: Iterating over list.
In the following example for loop iterates through the list “datalist” and prints each item and its
corresponding Python type.
datalist = (1452, 11.23, 1+2j, True, ‘w3resource’, (0, -1), [5, 12],
(*class”:'V", “section”:'A'}}
for item in datalist:
print (“Type of “,item, “ is , type(item))
Output:
Type of 1452 is
Type of 11.23 is
Type of (1+2j) is
Type of True is
Type of w3resource is
Type of (0, -1) is
type of {5, 12] is
type of {*section’: ‘A’, ‘class’: W') is
oan L__ ——#ix0 ample: Iterating over dictionary
yp the following example for
vi Hints each Key. loop iter
“5p color = {"C1": “Rego
! “Green
ssp for key in color:
print (key)
>»
Following for loop iterates through its values:
go> color = {"cl”: “Red”, %c2":
y> for value in color.values():
print (value)
creen
Red
orange
>»
You can attach an optional else clause with for
for variable_name in sequence *
statement_1
statement_2
else
statement_3
statement_4
after complet!
The else clause is only exee' ave ites the loop then U
program block and te!
the
s}—_————
‘ates th
hrough the dietiona
ry
“Green”,
‘ing the for
“color” through its keys and
", “e3": “Orange”}
statement, in this case, syntax will be —
Joop. Ifa break statement executes in first
else clause does not execute.—aa
Computer Programming Languages #_R-—.
Python While Loop
sed to repeatedly execute a block of program statements. The basic loop structure in,
while loop. Here is the syntax.
Loops are
Python i
Syntax
While (expression):
statement_1
statement_2
‘The while loop runs as long as the expression (condition) evaluates to true and execute the program
the beginning of the loop and the first time when the
block, The condition is checked every time at
expression evaluates to false, the loop stops without executing any remaining statement(s). The
following example prints the digits 0 to 4 as we set the condition x < 5.
x= 07
while (x < 5):
print (x)
xtel
Output:
°
1
2
3
4
One thing we should remember that a while | i
: loop tests its condition before the bi the loo}
block of program statements) is executed. If the initial test returns false, ite eae
|. For example the following code never pri ing si " i
pepenhooapesra er prints out anything since before executing the cond
x = 10;
while (x < 5):
print (x)
x t= 1
eo> -
vent
Nol ves) |
{ we)
ea fer
lowing while loop is an infinite loop, using True as the condition:
‘the fol
5 = 10;
le (True)?
print (x)
Python: While and Else Statement
statement(s)
There is a structural similarity between while and else statement. Both have a peace se ere
which is only executed when the condition is true, The difference is that bloc i Bs
ment executes once whereas block belongs to while statement executes repeatedly.
You can attach an optional else clause with while statement, in this case, syntax will be —
Das
While (expression) :
statement,| ‘Computer Programming Languages -—_——~_
statement_2
else :
statement_3
statement_4
n (condition) and, if it is true, executes the first block
of program statements. The else clause is only executed when the condition is false it may be the
first time it is tested and will not execute if the loop breaks, or if an exception is raised. If a break
statement executes in first program block and terminates the loop then the else clause does not
p calculates the sum of the integers from 0 to 9 and
‘The while loop repeatedly tests the expressiot
execute. In the following example, while loo)
after completing the loop, else statement executes.
x= 07
0:
while (x < 10):
s=st+x
x=xtl
else :
print (‘The sum of first 9 integers : ‘,s)
Output:
The sum of first 9 integers: 45
Flowchart
(The Sum af st
el
Example: while loop with if-else and break statement.
wale
aaa —€ (x == 508
break
_ (The sum of first 9 integers : ‘,s)
prin
the sum of ‘)X,’ numbers is :',5)
int (*The sul
Output:
the sum of 5 numbers is : 10
the above example the loop is terminated when x becomes 5. Here we use break statement to
Inthe
inate the while loop without completing it, therefore program control Boes to outside the
mini :
ai - else structure and execute the next print statement.
rie sim
enue a
fel
Python Break and Continue Statement
The break Statemey
© execution of th,
after the last state
the optional clan,
Syntax
st s statement is to end
‘nt is used to exit a for or a while loop. The purpose ey a eee
i i i ram CO} sto ae
: ile) immediately and the prog! gestotte statement
rg i reenter
se also. Here is the syntax.
while (expression1)
Statement 1statement?
if expression?
break
for variable name in sequence
tatement_1
statement_2
if expression3
break
Example: break in for loop.
In the following example for loop breaks when the count value is 5. The print statement after the
for loop displays the sum of first 5 elements of the tuple numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 5:
break
print ("Sum of first “,count,”integers is: “, num_sum)
Outp
sum of first 5 integers is: 15
Example: break in while loop.
In the following example while loop breaks when the i
u bs count is i
while loop displays the value of num_sum (i.e. 0414 a eee a
num_sum = 0
count = 0
while (count<10) :
num_sum = num_sum + count
©
‘Computer Programming Languages |__|Python
= count + 1
count
ye count== 5:
break
pint ("Sum Of first */count, "integers :
integers is: “, num_si
, sum)
output:
gn of first, 9 integers is : 10
continue Statement
‘he continue statement is used in a while or for loop to take the control to the top of the | if
e loop with-
qatexecuting the rest statements inside the loop. Here is a simple example.
gor x in range(7):
if (x == 3 or x==6):
continue
print (x)
Output:
Inthe above example, the forloop prints all the numbers from 0 to 6 except 3 and 6 as the continue
statement returns the control of the loop to the top.
Python String; |
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation
marks,
spello” +
‘hello’ is the same as
the print () function:
You can display a string Jiteral with
Example:
Print (“Hello”)
nt (‘Hello’) 3} <_<et Computer Programming Languages de
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the
string,
Example:
a = “Hello”
print (a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes.
Example:
You can use three double quotes-
a = ‘Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."””
print (a)
Or three single quotes:
Example:
a = ‘'/Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.’’*
print (a)
In the result, the line breaks are inserted at the same position as in the code.
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes represent-
ing unicode characters.
However, Python does not have a character data type, a single character is simply a string with 2
length of 1.
Square brackets can be used to access elements of the string,
Example:
Get the character at position 1 (remember that the first character has the position 0);
250
ee ee eePython Ce.
spello, World
..
petal)?
ei
slicins
can return a range of characters by using the slice syntax.
yo
specify the start index and the end index, separated by a colon, to return a part of the string,
sxample:
cette characters from position 2 to position 5 (not included):
syello, World!”
print (b{225])
Negative Indexing
se negative indexes to start the slice from the end of the string:
Example:
Get the characters from position 5 to position 1, starting the count from the end of the string:
b= “Hello, World!”
print (b[-5:-2))
String Length
Toget the length of a string, use the len () function.
Example:
The ien () function returns the length of a string:
@= “Hello, World!”
Print (len(a))
String Methods
Python has a set of built-in methods that you can use on strings.
Example:
The strip() method removes any whitespace from the beginning or the end:
—
Hello, World! *
Print(a.strip()) # returns “Hello, World!”
Example:
The Lower () method returns the string in lower case;
[251ee)
Computer Programming Languages -———_——_
a= “Hello, World!”
print (a. lower ())
ample:
‘The upper () method returns the string in upper ea
a = “Hello, World!”
print (a-upper(})
Example:
‘The replace () method replaces a string with another string:
a = “Hello, World!”
print (a.replace("H", “J"))
Example:
‘The sp1it () method splits the string into substrings if it finds instances of the separator:
a = “Hello, World!”
print(a.split(*,”)) # returns [‘Hello’, ‘ World!’]
Check String
‘To check if a certain phrase or character is pres
in,
ent in a string, we can use the keywords in or not
Example:
Check if the phrase “ain” is present in the following text:
txt - “The rain in Spain stays mainly in the plain”
x = “ain” in txt
print (x)
Example:
Check if the phrase “ain” is not present in the following text:
txt = “The rain in Spain stays mainly in the plain”
x = “ain” not in txt
print (x)
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
[252a ~~
Pron —
a
some:
yariable a with variable b into y,
yerse
‘aviable c:
spello”
eworld”
y
atb
print (c]
pxample:
qoadda space between them, add a»;
“Hello”
» = “World”
eat" +b
print (c)
String Format
Example:
age = 36
txt = "My name is John, I am ™ + age
print (txt)
But we can combine strings and numbers by using the format () method!
The format. () method takes the passed arguments, formats them, and places them in the string
where the placeholders { } are:
Example:
Usethe format () method to insert numbers into strings:
age = 36
‘xt = "My name is John, and I am {}"
Print (txt. format (age) )
The format() method takes unlimited number of arguments, and are placed into the respective
Placeholders:
Example:
Wantity = 3
temo = 567
253price = 49.95
myorder = “I want {} pieces of item {)
print (myorder.
You can use inde:
Example:
quantity = 3
itemno = 567
price = 49.95
myorder
print (myorder.
x numbers {0} to be sure the arguments are placed in tl
sr want to pay {2} dollars for {0} piece
for {} dollars.”
format (quantity, itemno, price))
s of item {1}.”
format (quantity, itemno, price))
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values.
‘They do not change the ori: inal string.
he correct placeholders;
Method Description
ceapitalizeO) Converts the first character to upper ease
casefold() Converts string into lower case
center() Returns a centered string
count) ‘Returns the number of times a specified value occurs in a string
encode) Returns an encoded version ofthe string
endswith Returns true ifthe string ends with the specified value
expandtabs()_ Sets the tab size of the string
‘find “Searches the string for a specified value and returns the position of where it was found
formatO Formats specified values in a string
Tormat_map0 | Formats specified values in a string
index) Searches the string for a specified value and returns the position of where it was found.
isalnum( Returns True if all characters inthe string are alphanumeric
isalphaQ Returns True if all characters inthe string are in the alphabet
isdecimal Returns True if all characters inthe string are decimals
isdigitO ‘Returns True ifall characters in the string are digits
isidentifier() | Returns True if the string is an identifier
[islowerO Returns True ifall characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintableO__| Returns True ifall characters inthe string are printable
isspace() ‘Returns True if all characters in the string are whitespaces
istitleO Returns True ifthe string follows the rules of a title
supper Returns True if all characters in the string are upper case
join Joins the elements of an iterable to the end of the string
ORA
A ae ERENCE SS SEPython
T converts a string into lower ease
‘Returns a left trim version of the string
[Returns a translation table to be used in tanstations
| Returns a tuple where the string is parted into three
arts
Returns a string where a specified value is replaced with a specified value
Searches the string for a specified value and returns the ls
ist position of where it was found
[searches the string fora specified value and returns ns the last po sition of where it was found
[ Returns a right justified version of the string = =
partition —_| { Returns a tuple where the string is parted into three parts = 7
raat ~ | Splits the string at the specified separator, and returns alist eae
Eanes Returns a right trim version of the string a
t split) jplits the string at the specified separator, and returns a list a
splines) Splits the string at line breaks and returns alist
“gartswith® __| Returns true if the string starts with the specified value =
[sip Returns a trimmed version of the string, a
[swapease() ‘Swaps cases, lower case becomes upper case and vice versa
[aie ‘Converts the first character of each word to upper case
(translate) Returns a translated string :
[upperd) Converts a string into upper case
[io Fills the string with a specified number of o values at the beginning.
References
+ Python: techtarget.com, Retrieved 3o August, 2019
Pygt-tutorial: gurug9.com, Retrieved 15 March, 2019
Intro, software: riverbankcomputing.com, Retrieved 18 May, 2019
Python-tkinter: javatpoint.com, Retrieved 28 January, 2019
Pygtk-introduction, pygtk: tutorialspoint.com, Retrieved 3 June, 2019
Variables-in-python: gurug9.com, Retrieved 23 May, 2019
Python-data-types: javatpoint.com, Retrieved 6 February, 2019
p Python-syntax, python: w3resource.com, Retrieved 11 June, 2019
Python-strings, python: wgschools.com, Retrieved 20 April
19
Python-file-handling, python: waschools.com, Retrieved 10 July,
he
Python-7-important-reasons-why-you-should-use-python-5801a98a0dob: medium.com, Retrieved 4 Apri
2019