ees Programming For Problem Solving
Introduction to Python Language
Python Basics:
4 Python is a general-purpose interpreted,
programming language.
Python is programming language as well as scripting language.
Python is also called as Interpreted language
So it is an uncomplicated and robust.
complexity of traditional compiled languages along with the ease-of-use (and then some) of
simpler seripting and interpreted languages.
|, interactive, object-oriented, and high-level
Difference between Scripting Language and Programming Language
Programming Language
Type of
veage
Running
Conversion
Design
Comptation eves comp!
File ype creas 9 ere te
coaing type
Complexity Easy torte arause
Inerpretanon
Walla Reidy Golleveor Enuinestinzand Technoloey iu
(@ Scanned with OKEN Scanner‘Why Python?
ject-oriented serpin Ianyy,
# Python isa high-level, interpreted, interactive and object-oriented se41P4i04 lang.
»ython is a high-level, interpreted,
sey words frequently i,
* ation dine tb gly dal alco i
languages use punctuation and it has ewer syntactic eosin
4 Python is a MUST for students and working profenionals 1 Wee
Engineer especially when they are working, in Web Developr
HE a othey
lan
tapes
"
History of Python: , a
# Invented in the Netherlands, early 90s by Guido van Rossurn start6d tn Doce
, the late1980s and its implementation was started in December
Guido Van Rossum is fan of*Monty Python's Flying, Circus’, this i 9 famow
Netherlands
# Named after Monty Python
Open sourced from the beginning
‘Who uses python today...
# Python is being applied in real revenu
For instance:
'
erating, products by real companies.
Google makes extensive use of Python in its web search system, and employs Python's
creator.
Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and JBM use Python for hardware
testing.
‘The YouTube video sharing service is largely written in Python
Features of Python:
1. Easy
‘When we say the word ‘easy, we mean it in different contexts.
2. Easy to Code
4 Puthon is very easy t code as compared to other popular languages like Java and C++,
* Anyone can learn Basle Python syntax in just a few hours. Thus, itis programmer-
friendly,
, Easy to Read
# Being a high-level language, Python
what the code is supposed to do,
# Also,
Code is quite like English. Looking at it, you can tell
since it is dynamically-typed, it mandates indentation, This aids readability,
2. Expressive
© scanned with OKEN ScannerWhit iv expressiveness, Huppowe we have tae langunyes A and 14, 0nd all
Programs that can be made Hn A cnn tne snnde hn 18 using kcal transformation
However, there are rome poy tt can fe ns in 18, bt net nA, singe Wel
{ransformations, Then, 1 fs aiid to be more expressive thin A
Python provides ws with w myriad of constructs that Help ws fr
(han on the syntax,
' 100 hve solution rather
+ This is one of the outstanding python fests that tell you vey you should laen Python.
3. Free and Open-Source
+ Flesly, Python is freely avallabe, You cnn dovnload it fiom the Python Off
Secondly, iis open-souree, This mien that its source code q
can downloud i, change it, use it, and distribute i
‘This is called FLOSS(Free/LAbre and Open Source Software), 4
Community, we're all headed toward one youl: an ever-betering Pylon,
savailal
the Pypbon
High-Level
* Python is a high-level lngunge, ‘This means thal as programmers, we don't need 10
Femember the system architecture
Also, we need not manap
of the key python
memor
‘This makes it more programmer-frlendly and is one
ures,
5. Portable
# Let's assume you've written a P
‘ython code for your Windows machine, Now, if you want
to run it ona Mac,
you don’t need to make changes to it for the same,
{In other words, you ean take one code and run it on any machine. ‘This makes Python
4 portable language,
4 However, you must avoid any system-dependent features in this case,
6. Interpreted
# Ifyou're familiar with any lang. ages like C++ or Java, you must fir
run it. But in Python, there is no need to compile it
Internally, its source code is converted into an immediate form
So, all you need to do isto run your Python code without worrying about linking to
libraries, and a few other things,
4 By interpreted, we mean the source code is executed
Because of this, it is easier to debug your code.
4 Also, interpreting makes it just slight
to the benefits it offers,
# Ifyou have any doubt in DataFlair’s features o
‘@ comment below and we will get back to: you
irst compile it, and then
called bytecade.
line by line, and not all at once,
tly slower than Java, but that does not matter compared
python programming language article, drop
PRR ene TS 9
© scanned with OKEN Scannerone
amming For Problem Solving
ror F Pro
CURE
7. Object-Oriented i
{A prowranmning languaye that can model the rea
vs data and functions.
- revolves around
itis said to be object-oriented.
lis sa
Socues on abjects and combi
Contrary, a
an be reused eeoriented programming which js
4 Python supports bath procedure-orlented and objes
‘one ofthe key python features.
4 {1k supports multiple inheritance,
4 Aclass is blueprint for such an obje
functions, which are code tha,
provedure-oriented lang
unlike Java.
vt ivan abstract datatype and holds no values,
4, Extemsible
4 Ifreeded, you can write some of your Python ae
§ ‘This makes Python an extensible language, mea
languages
in other languages like C++.
1 that it ean be extended to other
9. Embeddable :
: ir ur Python source
4) We just saw that we can put code in other languages in 0 source
‘ Howe, it abso possible to put our Python code in a source code in a different language
like C+,
4 This allows us to integrate scripting capabilities into our program of the other language,
code.
10, Large Standard Library 4 5
# Python downloads with a large library that you can use so you don’t have to write your
‘own code for every single thing,
‘There are libraries for regular expressions, documentation-generation, unit-testing, web
rovers, threading, databases, CGI, email, image manipulation, and a lot of other
functionality.
,
11,GUI Programming
Vor this, you can use Tkinter, wx
fast development of GUL,
12. Dynamically Typed
(@ Scanned with OKEN ScannerNae
Python Applications
Python is
known for its yeneral-purpose nature that mak
Software development. Python makes its presence in ev
Programming lang
¢ and can develop any application.
Application arcas where Python can be applied
Python
Applications
GETTING STARTED
Python Versions
4 There are two major Python versions- Python 2 and Python 3.
4 On16 October 2000, Python 2.0 was released with many new features.
4 On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
Finding an Interpreter for Python Programming
‘Windows: There are many interpreters available freely to run Python scripts like
IDLE (Integrated Development Environment) which is installed when you install the
python software from http://python.org/downloads!
(@ Scanned with OKEN ScannerFoun cranes ti
Python Installation
1s like IDLE (Integrated
thon software from
interpreters available freely to run Python scrip
nt Environment) which is installed when you install the pyt
rg/downloads!
There are m
Developm
hips/pyth
‘Steps to be followed and remembered:
# Step I: Select Version of Python to Install.
# Step 2: Download Python Executable Installer.
# Step 3: Run Executable Installer.
4 Step 4: Verify Python was Installed On Windows.
’
’
Step 5: Verify Pip Was Installed, ‘
Step 6: Add Python Path to Environment Variables (Optional)
[2 Fithon 30 6.6 Sew
Install Python 3.8.0 (64-bit)
Select instal Now to netal Python with cetaut
fenale or eaable ature.
ge. er coos
Customise
python
Dirrstatiaunener fora users ecommerce)
cance!
windows
Python Code Execution:
ing For Problem Solving
* Python's traditional runtime execution model: source code you type is translated to byte
code, which is then run by the Python Virtual Machine.
* Your code is automatically compiled, but then it is interpreted.
Runtime
PYM,
Malla Reddy College ofEngineeringand Os
i ad
12
© scanned with OKEN ScannerSource code ext
Byte code extension is .pye
ion is py
(Compiled python code)
Modes for using Python interpreter:
There are two modes for usin
4 Interactive Mode
"Script Mode
i the Python interpreter:
1. Running Python in interactive mode
"Without passing python seri
Pt file to the interpreter, directly execute code to Python
Prompt. Once you're inside .
the python interpreter, then you ean star.
>>> print(*hello world")
hello world
# Relevant output is display
>>> N=[0,1.2] :
# Quantities stored in memory are not displayed by default.
>>>x
red on subsequent lines without the >>> symbol
Fifa quantity is stored in memory, typing its name will display i (0, 1,2 |
Pea Le CE OE CTE RTE ears eer
ei raise incrrae eaece Amare toe
Seager)
cen
‘+ The chevron at the beginning of the Ist line,
interpreter uses to indicate that itis ready.
* Ifthe programmer types 2+6, the interpreter replies 8,
ice, the symbol >>> is a prompt the python
2, Running Python in script mode:
* Alternatively, programmers can store Python script source code in a file with the py
extension, and use the interpreter to execute the contents ofthe file
+ To execute the script by the interpreter, you have to tell the interpreter the name of the file.
Working with the interactive mode is better when Python programmers deal with small
pieces of code as you can type and execute the immediately, but when the code is more
‘than 2-4 lines, using the script for coding can help to modify and use the code in future.
Te a 13
(@ scanned with OKEN ScannerPython input) Function
: user input and reads
Python input() function is used to get input from the user. It prompts for os m ae pee
line. After reading data, it converts it into a string and returns that. It throw:
EOF is read,
Signature
var = input ({prompt])
Parameters
prompt: It isa string message w!
Return
It returns user input afier converting into a string.
h prompts forthe user input.
Python input() Funetion Example 1
Here. we are using this function get user input and display to the user as well.
1. # Python input() function example
2. # Calling funetion
3. val= input("Enter a value: ")
4. # Displaying result
5. print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
(@ Scanned with OKEN ScannerPython input() Function Example 2
The input() method retums string value, So, ifwe want o perform arithmetic operations, we need
to cast the value first, See the example below,
1. # Python input) fanetion example
2, # Calling fianetion
3. val= input("Enter an integer: ")
4. # Displaying result
val
mn(val) # casting into sti
(val val) # getting squa
print("Square of the value:",sqr)
5.
6. sat
1
Output:
Enter an integer: 12
Square of the value: 144
Python print) Funetion
Python printQ function prints the given object onthe
Signature
print(object(s), sep=separator, en
.en or other standard output devices.
nnd, filefile, flush=fush)
Parameters
object(s
object.
is an object to be printed. The Symbol * indicates that there may be more than one
sep='separator’ (optional): The objects are separated by sep. The default value of sep is"
end="end! (optional: it determines which object should be print at last
file (optional): ~The file must be an object with wrie(string) method. It is omitted, sys.stdout
will be used which prints objects on the screen.
flush (optional): IF True, the steam is forcibly Nushed. The default value of fash is False
Return
Tedoes not return any value. Python
print) Function Example 1
1. print(*Python is programming lIanguage.")2.
3.x=7
# Two object
sp
print('x=", %)
yex
4 Thwee objects passed
print(x=5 34°59)
RRC PR EC eI
15
© scanned with OKEN Scannernig For Probie Solving ~~ ing
jing For Prol
Programm!
TYeary GN
Python is programm
\
Output:
ng language,
X=7=y
Python print() Function Example 2
ameter.
The below example use pr int() with separator and end parame'
", % Sep='00000;, end="nintn)3,
% sep=0), end=")
a=000007
a=07
Comments;
* Comments bog
ns with a hash(#) symbol and is usefa in mentioy
Should be consi
It
ning that the whole line
ered as a comment untilthe end of ine,
'S used to basically provide the descript
So it will ignore from execution by Pythoy
ion of particular line of code,
Interpreter,
Example:
#To print Hello World (It comment)
°°? print (“Hello World”)
* So it executes only one fine of code,
Python Identifiers
* A Python identifier i
object. An identifier starts with a letter
OF an underscore () followed by
7 S, and % Within identifiers,
8 language, Thus, Manpower and ‘manpower are two
16 \
© scanned with OKEN Scanner
SePython Keywords:
The fitlowing list shows the Python keywords, These are reserved words and you cannot use them
as constant or variable or any other identifier names
letters only,
meee
a
continue
‘det
ei
Lines and Indentation:
# Python provides no braces to
flow control,
ndicate bloc!
of code for class and function definitions or
* Blocks of code are denoted by line indentation, which is rigidly enforced.
‘The number of spaces in the indentation is var
indented the same amount
ble, but all statements within the blockmust be
For example—
aslo
be20
ita>b):
print”
else:
print("a is less than b")
is greater than b"
However, the following block generates an error —
a=10
b=20
ita):
print("a is greater than b")
els
print("a is tess than
‘Thus, in Pythonall the continuous lines indented with same number of spaces would forma block.
Meer a7
© scanned with OKEN ScannerProgramming ———
Lee
is ins that whey
. This mea n
Variables in Pyt to store values.
‘ariables in Python: ns
tio!
mory locat .
* Variables are nothing but reserved some space in memory: emory and decides what ca
Bees ee Ia ia rie interpreter allocates ™
iable, :
* Based on the data type ofa varial integers; decimal
tore integers,
be stored in the reserved Hamat tatypes to variables, you can s
eae lata type:
* Therefore, by assigning different
or characters in these variables.
Rules for Python variables: derscore character
* A’variable name must start with a letter or the un
* A variable name cannot start with a number : and underscores (A-z, 0-9, and
* A Variable name ean only contain alpha-numeric characters
ifferent variables)
* Variable names are case-sensitive (age, Age and AGE are three dil
Assigning Values to Variables:
* Python variables do not need explicit declaration to reserve memory space.
+ The declaration happens automaticaly when you assign a value to a variable,
* The equal sign (=) is used to assign values to variables.
The operand tothe let ofthe = operator is the name of
{he operator is the value stored inthe variable
For example —
= 50 An integer assignmentb
= 7000.0 # A floating point ¢ =
“John" # A string
‘he variable and the operand to theright of
print (a)
prin (by
print (c)
This produces the following result —
50
7000.0
John
Multiple Assignment;
* Python allows
* For example
© scanned with OKEN ScannerCEN
nntiyy Vor
Hav ovnnpte
AE Le atv"
© Hon sine intoger objects wvith valtow 1 and 2 ate assigned to variables a and b resp
aint one slving abioot wvith the value "
jl fs assigned fo the variable
OwMNAE Vardadto,
# Vie Python print statement is often used fo output variables,
# Variales say nat need to be doctared with any’ particular type andl ean ev
ater they have boett set
mnge type
Branypte
Ne S# x isotype int
Se python # x is now of type ste
print)
Onatnats python
Vo oombine Dou text and a variable, Python uses the" eharact
Peamnple
X= Savesone”
printy"Python is" »
‘Output
Dthon is awesome
You can also use the + acter to add a able to another variable:
Faamnple
xe nbytton is
awesome
y print)
x
Output:
Python is awesome
Python Wdentifiers:
mothods(finetions) ete. For example,
are the name given {0 Va
i identifier) whic! re value "Python
Pea variable (an identifier) which hots the va Hi
aan is they are reserved names that are built-in to Python.
Here, 7
{We cannot use Keywords as varable names
For example,
© scanned with OKEN ScannereRe deen Oslo
jable name.
asa varia
ntinue
sed cor
The above code is wrong because we have ne
To learn more about variables, visit Python
Rules for Naming an Identifier
+ Identifiers cannot be a keyword.
+ Identifiers are case-sensitive.
in witha letter or _. The
+ Itcan have a sequence of letters and digits. However, it must begin with
first letter of an identifier cannot be a di \
+ Itsa convention to start an identifier with a letter rather i
* Whitespaces are not allowed.
+ We cannot use sp.
symbols like !, @, #, $, and so on.
Some Valid and Invalid Identifiers in Python
Valid Identifiers Invalid Identifiers
score @core
return_value return
highest_score highest score
name] Iname
convert to_string convert to_strin
string
Things to Remember
Python is a case-sensitive la
guage. This means, ya
Always give the identifiers a n
Numbers
> Strings
List
Tuples
Sets
Dictionary
vvVVY
NUMBERS
Number data types:
© Number data types store numeric values.
« Theyare immutable datatypes, means that changing the value ofa number data type results
in anewly allocated object.
+ Number objects are created when you assign a value to them
+ Python has three built-in numeric data types: integers, floating-point numbers, and
complex numbers.
Integers:
y Aminteger is a whole number with no decimal places. For example, | is an integer,
but 1.0 isn’t.
«So in Python, integers are 2er0, positive or negative whole numbers without a fractional
part and having unlimited precision, e.g. 0, 100, -10.
‘The followings are valid integer literals in Python.
>>>0
0
>>> 100
100
>>> -10
-10
>>> 1234567890
1234567890
>> "~=5000000000000000000000000000000000000000000000000000000
>
000000000000000000000000000000000000000000000000000000
a
fers
© scanned with OKEN Scanner7 Problem Solving
Programming Fo
.cimal values.
+ Integers can be binary, octal, and hexade
>>> 0b1 1011000 # binary
216
>>> 0012 # octal
10
>>> 0x12 # hexadecimal
1s
i int class. Use the type() method to get
Al integer literals or variables are objects of the int
* the class name, as shown below.
>>>type(100)
>> x=1234567890
>>> type(x)
>> type(y) # type of y is int
* Leading zeros in non-zero integers are not allowed e. 000123 is invalid number, 0000
is0.
>>> x= 01234567890
SyntaxError: invalid token
Float:
>>> fl.2
Dor
12
>>> type(f)
* Floats has the maximum size depends on Eee eee Ue eat ese
iaximum size
referred as "int", "Ing, INFINITY", of ning pn
infinity for most system, * OF “infinity”. Float 26400 win be considered as
>>> 20400
22
© scanned with OKEN ScannerNSN Cria soon
Programming For Problem Solving
Scientific notation
fs used as a short re i
For example: 345.56789 i presentation to express floats havi it
= 345. is represent ng, many digits.
Sous presented as 3,4556789e2 or 3.4556789E2
pot
1000.0
>o> feles
at
100000.0
>>> £3.4556789¢2
poof
345.56789
STRINGS
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes ‘the same as double quotes. ‘This contrasts with
‘most other seripting languages, which use single quotes for Titeral strings and doublequotes to allow
escaping of characters.
Python uses the "raw string” operator t0 create fiteral quotes, so no differentiation isnecessary-
Other languages suchas C use single quotes for charac ‘and double quotes for strings.
Python does not have a character types his is probably another reason why single and double
quotes are the same.
Nearly every Python application uses strings in one form or another. Strings are immutable,
meaning that changing an element of @ string requies creating a new string, Stings sr made up
df individual characters, and such elements tetrings may be accessed sequentially via slicing
How to Create and Assign Strings
Creating strings is as simple as assigning a value to a variable:
‘Hello World!
Python is cool!”
>>> aString
So> anotherString =
>>> print (aString)
Hello World!
>> print (anotherString)
Python is cool!
35> aBlankString ="
S>> print (@BlankString)"
pstrings) in Strings
How to Access Values(Character and Sul ; i
'» Python does not SuPPOFt & shharacter types these are eeated strings of Fength one, thus
also considered a substring.
“5 To access substrings, use the
obtain your substring:
index or indices 10
square brackets for slicing along with the
© scanned with OKEN ScannerGUSTO Oy oul
dt
rd Indexing
>>> aString = "Hello Wor
>>> aString[0] _ # Forwat
W
>>> aString[-1] # Backw:
‘’ :
>>> aString[:5] #Slicing
‘ello’
>>> aString[6:]
"World!"
ard Indexing
le to another string,
it it iable
oe (rasining 2 a ompketely different string
* You can "update" an existing string by ( pit
* The new ae can be related to its previous value or f0 a comp!
altogether.
>>> aString = 'Hello World!"
>>> aString = aString[:6] + Python!”
>>> aString
‘Hello Python!"
>>> aString = ‘different string altogether’
>>> aString
‘different string altogether!
Like numbers, strings are not mutable, so you cannot change an existing string without
creating a new one from seratch
{That means that you cannot update individual characters or substrings ina string,
* However, as you can se above, there is nothing wrong with piecing together part of ‘your
old string and assigning it to a new string,
How to Remove Characters and Strings
o repeat what we just sai, strings are immutable, so you cannot Temove individual characters
fiom an existing string, What you can do, however, is to empty the str
mr 2 » rs ‘ing, or to tc
string which drops the pieces you were not interested in, eters
{et us say you want fo remove one letter from "Hello. Workd?™
= World"... the (lowercase) letter "|" for
>>> aString = ‘Hello World!"
>>> aString = aStringf:3] dsl
>>> aString
‘Helo World!"
ing from the start + aString|4:]¢slicing to the end
© scanned with OKEN ScannerLW Oa ESS
ze nese
el Programming For Problem Solving
Membership Operator(in, not in)
‘© The membership question asks w
ae q asks whether a character (string of length one) appears ina
: ees ae ifthat character appears in the string and False otherwise
few more exar ings i
ele te imples of strings and the membership operators.
True
>>>'n' in ‘abed!"
False
>>> 'n! not in ‘abed!
True
Multi Line Strings
‘You can assign a multiline string to a variable by using three quotes:
>>>a="" This is Python Programming,
Python Language is awesome,
It is very easy to understand and
Easy to implement code”
>>>print(a)
‘This is Python Programming,
Python Language is awesome, It
ig very easy to understand and
Easy to implement code
Escape Character
TTo insert characters that are illegal in & string, use an escape character. An escape character @
backslash \ followed by the character you want to insert.
‘An example ofan illegal character is a double quote inside a string that is surrounded by double
quotes:
Example:
“The escape character allows You 10 USS double quotes when you normally would not be allowed:
spoint ="Python is an easy and \"interesting” language.”
>>>print(tst)
python is an easy and interesting” language.
Concatenation of Two or More Strings :
» Joining of two or more strings into & single one is called concatenation: re
The + (concatenation) operator does this in Python. Simply writing (2 string literals
together also concatenates them. ; =
«The * (repetition) operator can be used to repeat the string for 2 given number of times.
alla Reddy Coll
_
© scanned with OKEN Scanner™N
eee For Problem Solving
ming
| ANSTO On ery svenuelcrico
using +
print(‘strl + str2 =", strl + str2)
# using *
print('strl * 3 =!, str] * 3)
+ When we run the above progra
im, we get the following output:
str] + str = HelloWorld!
str] * 3 = HelloHelloHello
String Length : faa
To get the length of a string, use the len() function. The len() function returns the length of the
stri
>>>a= "Hello, World!"
>>> print(len(a))
12
Upper Case
The upper() method returns the string in upper case:
>>>a= "Hello, World!"
>>> print(a.upper())
HELLO, WORLD!
Lower Case
The lower() method returns the string in lower case:
>>>a= "Hello, World!"
>>>print(a.lower())
hello, world!
Remove Whitespace
id very often you is
space, The strip() method removes any whitespace fror inning ot Want to remove this
>>>a="Hello, World!" ace fom the beginning or the end:
°>>print(a.strip() # returns "Hello, World!"
Hello, World!
Replace String
‘Thereplce() method replaces a string with another string:
© scanned with OKEN ScannerJello, World!
Split String
The split i
ltd) method returns a lst where the text between the specified separator becomes the Ist
items.
a= "Hello, World!"
print(a.split(",")) # returns ('Hello’,' World
[Hello', ' Worldt"]
String Format
We cea combine strings and numbers by using the format() method. The format method takes the
passed arguments, formats them, and places them in the string w
nore the placeholders {} are: Use
the format() method to insert numbers into strings:
>>>age = 36
>>>txt = "My name is John, and 1 am (}"
>>>print(txt.format(age))
My name is John, and I am36
String Methods
Method Description
capitalize()
Converts the first character fo upper case
casefold() Converts string into lower ease
Returns a centered string
times a specified value occurs ina string
ith the specified value
n of where it
e and returns the positio
center()
count) Returns the number of
encode() Returns an encoded version ofthe string
endswith Returns true ifthe string ends wi
expandtabs() Sets the tab size ofthe string
find) Searches the string for a specified valu
was found
format() Formats specified values in a string
format_map() Formats specifi
(esa Tes
Ten mey
ied values ina string
© scanned with OKEN ScannerFor Problem Solving
Programming
Dea TW rT Sree
turns the position of where jt
ified value and re
Searches the string for a specified
index)
was found sig xt shteomoes
inthe strit
isalnum() Returns True ifall characters in the aeae
i in ing are in
isalpha() Returns True ifall characters in the string is habe
. ing are decimals
isdecimal() Returns True ifall characters in the string
isd i ing are digits
isdigit() Returns True ifall characters in the string are digi
‘sidentifier() Returns True ifthe string is an identifier
it it case
islower() Returns True ifall characters in the string are lower
P 7 ry
iSmumeric) Returns True ifall characters inthe string are numer
‘sprintable() Returns True ifall characters in the string are printable
isspace() Returns True ifall characters in the string are whitespaces
isttleg, Retuins True ifthe string follows the rues ofa ttle
isupper() Returns True ifll characters inthe string are upper case
Joing ‘ins the elements ofan erable to the end ofthe string
Justo Returns a let justified version ofthe string
lower) Converts. a string into lower case
‘strip Returns a left trim version of the string
Partition) Returns a tuple where the string is
Teplee) Returns. string where ‘specified Value is replaced With a specified val
ified value
find) Searches the string for a speci
specified val
it was found He and retumns the last Position of where
rindex() Searches the strin, it
ring for a Specified
cone “alle and retums the lage Position of where
sjust Returns aright justified Version ofthe stin
a
‘artition) Returns a (ple where the str
pli Splits the string
"trip()
Returns a right trim *esIOn ofthe string
© scanned with OKEN ScannerProgramming For Problem Solving
split it ‘i
split) Splits the string at the specified separator, and returns a list
startswith() Returns true ifthe string starts with the specified value
strip() Returns a
ined version of the string
swapease() Swaps cases, lower case becomes upper case and vice versa
titled) Converts the first character of each word to upper case
translate) _Returns.a translated string
upper() Converts a string into upper case
zfill) Fills the string with a specified number of values at the beginning
LIST
«The list is a most versatile Data type available in Python in which objects are mutable in
type and can be written as a list of comma-separated values (items) between square
brackets.
Important thing about a list is that items ina list need not be ofthe same type.
Strings consist only of characters and are immutable (cannot change individual elements)
hile ists are flexible container objects which hold an arbitrary number of Python objects.
+ Creating lists is simple adding to list i easy, too, as we seein the following examples.
Example:
list = [[physies’, ‘chemistry’, 1997, 2000];
list2=[1, 2.3.4.5
mylist=[*apple’, "banana", “eherty"}
List
Lists are used to store multiple items ina single variable.
Lists are one of built-in data types in Python used to store collections of dats, the other 3are
Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
_
AIRE eee Manne!
© scanned with OKEN Scanner“cherry"]
‘apple’, "bananas
print(thislist)
List Items
and allow duplicate values.
it in 1] ete.
as index [0], the second fem has index [1]
List items are ordered, changeable,
List items are indexed, the first item
re that the items have @ defined order, and that order will
‘When we say that lists are ordered, it means
not change.
he end of the list.
Ifyou add new items to a list, the new items will be placed at t
general: the order ofthe items
Note: There are some lst methods that will change the order, but in
will not change.
Changeable
‘The list is changeable, meaning that we can change, add, and remove items ina list after it has
been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
‘Example
Lists allow duplicate values:
thislist=["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist=["apple", "banana", "cherry"]
print(len(thislist))
UOTE ee ae ee mY
30
ee
© scanned with OKEN ScannerOXTOM rie istouroncon
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
fist2=[1, 5. 7,93]
list3 = [True, False, False}
‘A list can contain different datatypes:
Example
‘A list with strings, integers and boolean values:
fist! =
be", 34, True, 40.
type()
From Python's perspective, lists are defined as bless ‘with the datatype "list:
Example
What is the data type of list?
pple", “banana”, "erry
mylis
print(type(mylist))
How to Create and Assign Lists
ye creating lists i a simple as assigning 8 value to avariable.
© You handeraft a ist (empty oF tlements) and perform the assignment
«Lists are delimited by surrounding savare brackets ({1)-
p> aList = (123, ‘abe’ 4.56, inner, list), 7-99)
REE ee mecringand Technol
© scanned with OKEN ScannerSe
inn ere!
>>> anotherL ist = [None, ‘something to see here!)
>>> print (anotherList) [None,
something to see here’)
>>> aList’ ThatStartedEmpty
>>> print (aL istThatStartedEmpty)
U
How to Access Values in Lists
* Slicing wort similar to strit
index or indices,
>>> aList[0]
1233
use the square bracket slice operator ( [ ] ) along with the
>>> aList{Is4
abe’, 4.56, [
ner’, list]
>>> aList[:3]
(123, ‘abe’, 4.56]
>>> aList(3][1]
"list"
How to Update Lists
* You can update single or multiple el
ofthe assignment operator and you eat add to elements ina list with the append() method:
>>> aList
{123, ‘abe’ 4.56, [inner "st, (7-9))
>>> aList[2]
4.56
>>> aList{2;
>>> aList
float replacer*
£123, ‘abe’, ‘float replacer’, inner’ “list, (7-99)
>>>
>>> anotherList.append(*hi,
>>> print (another!
LE
'm new here’
COI q
© scanned with OKEN ScannerSES
Programming For Problem Solving
[None, ‘something to see here’, “hi, mm new here")
>>> aListThatStartedEm
is ipty.append(not e ‘more!
>>> print (aLstThatStartedEmpty) nidnantd
[not empty anymore’)
How to insert item in List
© To insert a new list wit y values, w e
T ist item, without replacing existi
: an ‘eplacing any of the existing values, we can use the
‘The insert() method inserts an item at the specified index:
>>>str_list = jack’, jumped’, ‘over, ‘candlestick’]
>>>str_list.insert(2, 'park’)
>>>print(str_list)
[jack’, jumped, ‘park’, ‘over, ‘candlestick’]
How to Remove List Elements and Lists
To remove a list element, you can use either the del statement ifyou know exactly which
element(s) you are deleting or the removeQ) method if you do not know.
>>> aList
[123, ‘abe’, ‘float replacer’, inner’ ist], (7-99)
>>> del aList{!]
>>> aList
[123, "float replacer’ (inner list (7
i]
>>> aList.remove(123)
>>> aList
[float replacer inner’ ist 1-99]
«You can also use the pop() method fo remove and return a specific object froma list
>>> aList.popO
(7-9)
‘The list still remains, but
+ Toclear the list, clear() method will be used to empties the lis
a
Tne eeu Pirie
© scanned with OKEN ScannerProgramming For Problem Solving
TC
it has no content.
>> aList.clear()
Print(aL ist)
0
is not something application programmers do,
{ Normally, removing an entire list pe (Le. program termination, tinction ea
* Rather, they tend to let it go out of som ctly remove an
enn tion, et.) and be garbage-collected, but if they do want to explicitly
Entire list, use the del statements
>>Ddel aList
Membership (in, not in)
With strings, the ‘membership operator determined whether a single character is a member
ofa string.
With lists (and tuples, we can heck whether an object ia member of a lst (or tuple),
>> mixup_list = (40, (1, 'N], fruit
>>>mixup_tist
14.0, (1,7, suits, C1946)
>>> fruits’ in mixup list
True
>>>
>>>'x'in mixup _list
False
>>> in mixup _list(1)
True
Coneatenation(+) Operator
. ion operator allows us to join ‘multiple lists together.
rl ; candlestick’)
22> mixup list = (40,1, ‘fruits, 1.946%)
>>
>>> num list + mixup_list
[3,-1.23, 2, 619000.6, 40, (1, ‘x1, fruits, (1.9469)
D>
>>> str_list + num list
Clack; jumped’, over', “candlestick, 43, 1.23, 64 9000.0)
* We can use the extend() method in place of the concatenation ©Perator to append the
© scanned with OKEN Scannerin
contents of. list to another,
Using extend() is advantay
elements of the new list to
does
ion (*)
igeoUS over concatenation because it actually appends the
the original, rather than creating a new list from soratch like +
Use of the repetition operator may make more sense with strings, but as a sequence type,
lists and tuples can also benefit from this operation, if needed:
>>> num_List * 2
(43, -1.23, 2, 619000.0, 43, -1.23, -2, 619000.0)
Ten)
For strings, len() gives the total ength ofthe string, as in the number of characters.
For lists (and tuples), it will not surprise you that len() returns the number of elements in
the list (or tuple),
* Container objects found within count asa single item,
Our examples below use some ofthe lists already defined above in previous secti
>>> len(num_fist)4
Copy a List
‘+ You cannot copy a list simply by typing list2 = list, because: list2 will only be a reference
to listl, and changes made in list! will automatically also be made in list2.
There are ways to make a copy, one way isto use the built-in List method copy().
>>>str_list = [jack jumped, ‘over, candlestick’)
list.copy()
>>>print(mylist)
{ack,, jumped’, over’ ‘eandleste
© Another way to make a copy is to use the built-in method list(),
>>>str_list= (Jack, umpedt, ‘over ‘candlestick’]
>>>mylist = listste_list)
>>>print(mylist)
(ack, jumped, ‘over’, candlestick’)
List Methods ae
Ree eT 35
{
© scanned with OKEN ScannerMethod
TUPLES
Tuples:
Tuple Items
ae
* Python has a set of built-in methods that you can use on list.
1 Tuples are another container type extremely similar in nature to lists,
* The only visible difference be
Use square brackets,
* Functionally there is a more significant difference, and that 's the fact that tuples are
immutable.
£ Tuples are used to store multiple items ina single variable,
* Tuple is one of 4 built-in datatypes in Python used to store collections of da
are List, Set, and Dictionary, all with different qualities and usage,
* Atuple is a collection which
* Tuple items are ordered, unchangeable, and allow duplicate values,
* Tuple items are indexed, the frst item has index (0, the second item has index [1] ete,
1. Ordered: When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change,
Solving
ramming For Problem
fees Prog!
Description
‘Adds an element at the end of the list
Removes all the elements from the list
Returns a copy of the list
Returns the number of elements with the specified value
‘Add the elements ofa list (or any iterabe), to the end ofthe current list
Returns the index ofthe first element with the specified value
‘Adds an element atthe specified position
Removes the element at the specified position
Removes the item with the specified value
Reverses the order ofthe list
Sorts the list
‘tween tuples and lists is that tuples use Parentheses and lists
ta, the other 3
ordered and unchangeable,
|
© scanned with OKEN Scanneraoe Cea piss
Pi
'rogramming For Problem Solving
2, Unchan,
geable : Tuples are
unchangeable
remove fems afer the tole a ae eatin tat we cama change add or
3. Allow Duplicates : Since les can have items with the same value
+ Since tuple are indexed, tuples can have items wit i
it
How to Create and Assign Tuples
Creating and assigning li i
ating and signing lists are practically identical to lists, withthe exception of emptytuples.
-quire a trailing comma ( ,) enclosed in the tuple delimiting parentheses (())-
2 aTuple = (123, ‘abe’, 4.56, ['inner’, tuple’), 7-9)
>> anotherTuple = (None, 'something to see here’)
>>> print aTuple
(123, ‘abe’, 4.56, inner’, tuple}, (7-9)))
>>> print anotherTuple
(None, ‘something to see here’)
>>> emptyTuple = 0
>>> print emptyTuple
90
How to Access Values in Tuples
» Slicing works similar to lists: Use the square bracket slice operstor (C1) along with the
index or indices.
o> aTuple =(123, ‘abe’ 4.56, (inner, tuple, 7-9))
>>> aTuple(1:4]
(abe!, 4.56, inner’, tuple)
>>
>>> aTuple[:3]
(123, tabe!, 4.56)
>>> aTuple(3)(1]
‘tuple
How to Update Tuples
‘Like numbers and strings,
change values of tuple elements:
tuples are immutable which means you ‘cannot update them or
portions of an existing sting to eal 82°" string. The
gs, we were able to take
Lins
same applies for tuples.
>>> aTuple = aTuple[0], aTuple(t), aTuplel-1]
37
meee!
Mrlemenaerst
aii ne
/
© scanned with OKEN Scannerg For Problem Solving
>>> tup3
(12, 34.56, ‘abe’, 'y
2. Change Tuple Values: Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called. .
* But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
>>>aTuple = (123, ‘abe’, 4.56, [‘inner, tuple’), 7-9)
>>>aList
>>>aList{l] ="xyz"
>>>aTuple = tuple(aList)
>>>print(aTuple)
(123, ‘xyz’, 4.56, (inner, tuple’), (7-9)))
How to Remove Tuple Elements and Tuples
* Removing individual tuple elements is not possible.
* There is, of course,
nothing wrong with putting together another tuple with the undesired
elements discarded,
* To explicitly remove an entire list just use the del statement:
>>> delaTuple
Single Element Tuples
+ Ifwe take a single element in tuple it will not considered as a
as either int, float or strings based on the type of value whic
element.
* But there will not be any problem in list for single element in it,
>>> ['abe']
Pabe']
>>> type(('abe') # a list
>>>
>>> [123]
[123]
>>> type({123]) # also a list
>>>
SHIRE ea oe
38
tuple but it will considered
fh we have taken as a single
EEE eee |
© scanned with OKEN ScannerProgramming For Problem Solving
>>> type((‘xyz’)) #a string, not atuple
>>
>>> (456)
456
>>> type((456)) # an int, not atuple
. It
probably does not help your case that the parentheses are also overloaded as the
expression grouping operator.
‘© Parentheses around a single element take on that
tuples.
+ The workaround isto place ataing comme () after the first element to indicate that this
is a tuple and not a grouping.
>>> (xyz)
(xyz!)
>>> (456,)
(456)
Unpacking a Tuple
‘© When we create a tuple, we normally
(ing role rather than as a delimiter for
assign values to it. Ths is called "packing" a tuple.
Packing a Tuple:
>>> aTupl
>>>aTuple
(123, abe’, 4.56, inner’ ‘tuple, 7-93)
«But, in Python, we are also allowed to extract the values back into variables. Th
"unpacking"
Unpacking a tuple:
>>> (a,b,c,d,e)=aTuple
pea
123
>o>b
‘abe?
pre
4.56
peed
[‘inner, ‘tuple']
>>> (7-99)
Note: The number of variables must ‘match the number of values i
ect the remaining values 2s list
asterisk to col
39
iin em
Tonner mee
(123, ‘abe’, 4.56, [inner’ tuple, 7-93)
nthe tuple, ifnot, you must usean
© scanned with OKEN ScannerProgramming For Problem Solving :
Using Asterisk: sxe
* Ifthe number of variables is less than the number ofvalues, you canadd an * to the variable
‘name and the values will be assigned to the variable as a list:
>>> (ab,e)=aTuple
>>a
123
>> b
‘abe!
>>>
{4.56, [inner ‘tuple'), (7-9)
No Enclosing Delimite
Any set of multiple objects,
brackets for lists,
examples:
>>> abe’
comma-separated, written without identifying symbols, ie.,
Parentheses for tuples, etc., default to tuples, as indicated in these short
4.24093, 18+6.6), ‘xyz!
Cabe', -4.24¢+093, (1846.6), 'xyz!)
>>>
>>>x, y= 1,2
>>> xy
a, 2)
Any function returning multiple objets (also no enclosing symbols) is a tuple.
Join Two Tuples (+)
* To join two or more tuples you can use the concatenation (+) operator:
>>>aTuple=("a", "b", "c")
>>>anotherTuple = (1, 2,3)
>>>joinTuple = aTuple + anotherTuple
>>>print(joinTuple)
a’, 'b’, ‘c’, 1, 2, 3)
Multiply Tuples(*)
‘© If you want to multiply the content of a tuple a given number of times, you can use the
repetition (*) operator:
So>a=("a", "b", "e")
>>> b=at3
© scanned with OKEN ScannerUSSR ees
Programming For Problem Solving
Tuple Methods:
count: The count() method returns the number of
Example:
>>>atuple = (1. 3, 7, 8, 7,
>>>x = atuple.count(S
>>>print(x)2
times a specified value appears in the tuple.
indexQ:The index() method finds the first
0 . i occurrence of the speci is method rai
exception ifthe value is not found. a
Example:
Search for the first occurrence of the value 8, and retum its position:
>>paTupke = (1. 3. 7.8, 7,5, 4.6.8.5)
>>>x = aTuple.index(8)
>>>print(x)3
SETS
Sets:
€ Sets are used to store multiple items ina single variable.
‘Asset is a collection which is both unordered and un indexed.
Sets are written with curly brackets.
'As Sets are unordered, so you cannot be sure in which order the items will appear.
‘Asset as a whole can be changed, but the elements present in the set are unchangeable.
Every element in the set must be unique (no duplicate values) and must be immutable
(unchangeable).
‘These elements can be of the data type.
However, sets are in itself data structure, which is unordered and mutable (changeable),
These are used for performing mathematical operations such as union, intersection, ete.
Creating Sets:
+ You can create set either by placing all the items in the curly braces or by using the set ()
function. The elements can be of integer, string, float, etc).
Examplel: Using curly braces
>>>My_Print= (10, "Hi, (7)}
>>>print (My_Print)
{10, "Hi, 7}
Example2: Using Set () function
>>>a= set ({10, 9.0, "bye"})
>>>print (a)
{9.0, 10, 'bye"}
APL Sea eee ee ee a
OO eF=7e
© scanned with OKEN Scannerjing For Problem solving
PRU NGET Roncion Programme )
Example 3: Empty set
>rrarset()
>>Sprina)
set()
Example 4:
S>>aSet = {jack’, jumped’, over, ‘candlestick')
>>=print(aSet) #print: ing for first time
candlestick’, ack’, ‘jumped’, ‘over’}
>>print(aSet) #printing for second time
{jumped’, ‘over’, ‘candlestick’, jack}
Example 5:
>>> aSet = {jack’, jumped’, ‘over! ;
; umped’, over’, * ‘over’
ooo aset 4 ‘candlestick* , over’)
Set # ‘n't print duplicate values
Gack: over, jumped! candlestick’)
Modifying a Set:
* Ifyou want to add only
one element, then use add method, and for adding multiple-
element you need to use 7 id if
the update() method.
Examplel: For adding single clement
>>>a={10,3)
>>>print(a)
{10,3}
>>>a.add(2)
>>>print(a)
{10,3,2}
Example2: Using update() method
>>>a= {10,3}
>>>print(a)
{10,3}
>>> a.update({2,3,4])
>>>print(a)
{10,2,3,4}
Removing elements from a set:
4 To remove particular elements you can use discard() and remove (),
¢ The remove() method removes the specified element from the set,
4 The remove() method takes a single element as an argument and removes it from the set.
.
The remove() removes the specified element from the set and updates the set. It doesn't
return any value.
Malla'Reddy Gollege of Engineering and Technology| 42
© scanned with OKEN Scannerchil YeanT Semester
blem Solving
© eth :
the clement passed to remove() doesn't exist, KeyError exception is thrown.
Example 1: Remove an Element From The Set
>>>language = {'English’, 'French’, ‘German'}
>>> language.remove(‘German')
>>>print(Updated language set:’, language)
Updated language set: {'English’, 'French’}
Example 2: Deleting Element That Doesn't Exist
>>>animal= {'cat', 'dog’, 'rabbit'}
>>>animal.remove( fish’)
>>>print('Updated animal set, animal)
It generates Key Error
# You can use the set discard() method if you do not want this error.
4 The discard() method removes the specified element from the set.
¢ However, ifthe element doesn't exist, the set remains unchanged; you will not get an error.
>>>animal = {‘cat’, ‘dog’, ‘rabbit’}
>>>animal.discard(‘fish’)
>>>print(Updated animal set:', animal)
Updated animal set: {‘rabbit’, ‘dog’, 'cat’}
‘Accessing items in a set: =
Asset element cannot be referenced by an index number since it is unordered.
4 However, the items in a set can be looped through by using a for a loop.
4 You can also choose to access a particular item in a set by using the “in” keyword.
However, note that it is case sensitive.
Using for loo;
>>>fruits_set = {"mango", “banana”, “orange"}
>>> for x in fruits_set:
print(x)
mango
banana
orange
Using membership “in” keyword:
>>>fruits_set = "mango", "banana’, “orange"}
>>>print(“orange" in fruits_set)
True
>>> print("Orange" in fruits_set)
False
rE
(TERE kaa see Cn RO 43
© scanned with OKEN Scannerst.
Programming For Problem Solving
‘Clearing all items in a set:
# You can remove al items in a set by using the clear() method.
Copying a set
* Anexisting set can be copied to a new set by using the copy() method.
> fruit "mango", "banana", “orange"}
fruits_set.copy()
‘new set: ", new_fruits_ set)
now set: {"mango", "banana", “ora
', orange")
Sorting a set:
The values in a set can be sorted in ascending or descending order using the sorted()
method,
* By passing the set variable inside the sorted) parameter, the items in a set will be printed
in ascending order by defauit. The sorted() method takes in three parameter-iterable, Key
and reverse,
* The iterable parameter is required in which you need to specify the variable name of the
set,
* The key and reverse parameter is optional.
* You can use the reverse parameter to sort the items in ascending order (reverse
descending order (reverse = True).
Example:
>>>vowel_ set = ("e", "a" "a", %
"i"
>>>print("Default sort: ", sorted(vowel_set))
Default sort: [a 'e,
Ascending order: ['a','e,
>>>print( "Descending orde
", sorted(vowel_set, reverse=True))
Descending order: {'u',
ve, 'a}]
Python Set Operations:
4 Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
¢ Let us consider the following two sets for the following operations,
>>> A= {1,2,3,4,5}
>>> B= (4, 5, 6, 7, 8}
TRIE ens 4
em
© scanned with OKEN Scanner2)Using | operator:
>>>print(A | By
{1, 2,3, 4, 5, 6, 7, 8
b)Use Union method:
# use union function
>>> A.union(B)
(1,2,3,4,5, 6,7, 8)
# use union function on B
>>> B.union(A)
{1, 2,3, 4, 5, 6, 7, 8)
Set Intersect
‘
Intersection of A and B is a set ofelements that are common in both the sets.
* Intersection is performed using & operator. Same can be accomplished using
the intersection() method.
a)Using & operator:
{I, 2,3, 4, 5}
B= {4, 5, 6, 7,8}
>>>print(A & B)
{4, 5}
b)Use Intersection metho
# use intersection function on A
>>> A.intersection(B)
1 erection frtonenB
>>> B.intersection(A)
{4, 5}
© scanned with OKEN Scanner7 Solving
LOO Ca Rees Programming For Problem
Set Methods:
|
PYTHON DICTIONARIES
Dictionary:
' Te last standard type to add to our repertoire isthe dictionary, the sole mapping type in
ion,
'
A dictionary is mutable and is another cor
Objects, including other container types,
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
So they are implemented as resizeable hash tables,
Dictionaries are used to store data values in key-value pairs
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
ntainer type that can store any number of Python
Dictionaries are written with curly brackets, and have keys and values
Creating a dictionary is as simple as placing items inside curly braces {) separated by
commas.
* An item has a key and a corresponding value that is expressed as a pair (Key: value).
4 While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
# We can also create a dictionary using the built-in dict() function,
# empty dictionary
>>> my_diet = {}
# dictionary with integer keys
"ball’}
# dictionary with mixed keys
{(name': John’, 1: (2, 4, 3])
| iMalla Reddy College of Engineering and ‘Technolog 46
© scanned with OKEN Scanner# using dict)
>>omy_dict = dict(¢12
apple’, 2"ball’})
A
cessing values in Dictionary:
While indexing is used wi
>>> print(my_dict['address)
Traceback (most recent call ast:
File "", line 1, in
print(my_dict{'address'))
KeyError: ‘address!
b) Accessing values using get() method:
>>> my_dict = {‘name': ‘Jack’, ‘age’: 26}
>>>print(my_diet.get(age))
26
>>>print(my_dict get(address))
None
>>
Get Values:
The values() method will return a list of
>>> xemy_dict.valuesO
pox
dict_values({‘Jack’, 26])
>>
(Changing and adding dietionary elements)
Updating Dictionaries
able, We can add new items or change t
# Dictionaries are mut:
‘an assignment operator.
4 Ifthe key is already present,
4 Incase the key is not present,
then the existing value gets updated.
‘a new (key: value) pair is added to the
‘name’; ‘Jack, ‘age’: 26)
updating value in dictionary
>>> my_dict =
>>> my_dict{'age'] = 27
ain eum
© scanned with OKEN Scanner
II the values in the dictionary.
he value of exis
"Ke: with other d
toe ys can be used either inside lata types to access values, a dictionar
Fwe use the squa square brackets {] or witht ry uses keys.
dictionary. re brackets [], KeyError is raised i et
* Onthe ot in case a key is not found in the
ther hand, th
a) , the get( 7
) Accessing Values using catade returns None ifthe key is not found.
>>> imy.dict = (/ame' ‘Yack, ‘age’ 26)
print(my dicttname')
Jack '(my_dict['name'])
ing items using,
dictionary.DEI
>>> print(my_dicty
(name: ack’, ‘age’: 2)
* Adding Item in dictionary
2? my_diet{'address] = "Downtown!
>>> print(my_dict)
name’: Jack, ‘age’.
27, ‘address’: ‘Downtown'}
Update Method:
"The update) method Will update the dictionary with the items from a given argument. If
the item does not exist, the item will be added.
"The arg a dictionary,
'Y, OF an iterable object with key:value pairs.
‘address’: Downtown’)
ack’, ‘age’: 27, ‘address': ‘Downtown’, ‘Gender’: Male’}
The popitem( method can be used to emove and return an arbitrary (key, value) item pair
from the dictionary
Allthe items can be removed at once, using the clear) method,
We can also use the del keyword to remove individual items or the entire dictionary itself
Pop) method:
2 squares = (1:1, 2:4, 3:9, 4:16, 5:25)
>>> print(squares.pop(4))
16
>>> print(squares)
{Ir 1,2:4, 3:9, 5:25)
Popitem() method:
>>> print(squares)
{1:1 2:4, 3:9, 5: 25)
>>> print(squares.popitem())
(5, 25)
>>> print(squares)
{1:1,.2: 4, 3:9}
clear () method:
SEE ens
48
© scanned with OKEN ScannerD> squares
{Usd 3: OY
>>> squares.cloarg)
>>> print(squanes)
uy
del keywords
4 The det keyword removes the item with the specified key nme or i ean also de
dictionary completely,
>> del squares
>>> prian(squares)
‘this will cause an error becatise “sqnares" no longer ests.
Copy 4 Dictionary:
© You cannot copy a dictionary simply by typing diet2 © diet, because diet2 will only bea
reference to diet and changes made in dit will automaticaly also be made in diet2,
# There are ways to make a enpy, one way i fo use the built-in etionary method copy:
Example:
ny_my_diet)
me's
ack’ ‘age 26)
# Another way to make a copy is 0 use the bu
Example:
Make a copy of a dictionary with the diet() funetion:
et(my_aliet
Dictionary Membership Test
+ Wecantest ia key is ina dietionnry or not
{est is only for the Keys ane not for the values
the keyword in, Notice that the memb
4# Membership Test for Dictionary Keys
151, 3:9, 5:25, 7:49, 9: 81)
>>>prin(l in squares)
we
>5>print(2 no
True
squares)
TEE ne
EMMETT
_
© scanned with OKEN ScannerFro CET Byes
el
# membership tests for key only not valu
Output: False
>>>print(49 in squares)
False
Dictionary Methods
Method Description
least) Removes ail the elements from the detians!
cony() ——_Returne a copy of the aierionary
tromkeys() Ret
Returns the value of the specified hey
ont)
ems) Returns 9 lit containing a tule for ench key v2lue pair
koyst) Returns a list cantninina the aictionary's Heys
opt) Removes the element with the specitied key
uotein() — Removes the last inserted key-value pal?
stdafault() Returns the value of the spactied hey. Ifthe key exes nit erist: weert the Hey, «ah
updatet) Updates the ditionary watt ale pairs
waluss() Returns a list of all Use values in the dictionery
Number Type Conversion:
Python converts numbers internally in an expression containing mixed types to 2 o0
type for evaluation.
But sometimes, you need to coerce a number explicitly from one type to another to set
the requirements of an operator or function parameter.
+ Type int(x) to convert xto a integer.
* Type float(x) to convert xto a floating-point number.
Type complex(x) to convert x to a complex number with real part x and imaginary part
zero.
Type complex(x, y) to convert x and yto a complex number with real part x and imaginary
part y. x and y are numeric expressions
Note: long (long int) will be used in Python 2.x but not in Python 3.x.
som dos ‘ype conversion functions to directly convert one data type to another which is
ti . fae 7 .
seful in day. to-day and competitive programming. This article is aimed at providing information
about certain conversion functions,
FUER y College of Enginesriny ELT Meee nd
© scanned with OKEN ScannerWe eral pisueeea
her
There i i types of Type. Conversion in Python:
: ‘vthon Implicit Type Conversion
Python Explicit Type Conversion
‘Type Conversion in Python
The act of changing an object's data t
automatically performs Implicit
losing data.
data type is known as type conversion. The Python interpreter
Type Conversion. Python prevents Implicit Type Conversion from
‘The user converts the data types of objects using specified funetions in explicit type conversion,
sometimes referred to as type casting. When type casting, data loss could happen if the object is
forced (0 conform to a particular data type.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter automatically converts
one data type to another without any user involvement. To get a more clear view of the topic see
the below examples.
print(2)
print("z is of type:".type(2))
Output :
x is of type: = Greater than oF equal to way
<= Less than oF equalto xy
Logical operators
Operator © [PSone
and Returns True ifboth Ix<5 and x< 10
statements are true
or Returns True ifone ofthe x Signed right shift |Shift right by pushing copies ofthe leftmost bit in from
the lef, and let the rightmost bits fall off
Precedence of Operators:
Operator precedence affects how an expression is evaluated.
For example, x= 7+3 *2;here, x is assigned 13, not 20 because operator * has higher precedence
than +, soit first multiplies 3*2 and then adds into 7.
Example 1:
pee 3t4n2
i
Muttplication getseval
>>> (10+ 10) *2
uated before the addition operation
40
Parentheses (overriding the precedence ofthe arithmetic operators
Example 2:
=20
=10
15
eaoce
=0
excatbyte/d
4(30* 15)/5
prin("Value of(2+8) “6! ais", ¢)
© scanned with OKEN ScannerTech 1 Year 1 Semester
e=((a+b)*%c)/d
2 (30° 15)/5
print("Value of((a+b)* ¢)/dis", ©)
(a~b) *(c/d);
(30) * (15/5)
print("Value of(a+b)* (c/d) is", e)
+(b* 0)/d;
10 + (1505)
print("Value ofa + (b *c)/dis",e)
Output:
Value of (a +b) * ¢/ dis 90.0
Value of (a+b) * c) /d is 90.0
Value of (a+ b) * (c/d) is 90.0
Value ofa+(b *c)/d is 50.0
Expressions: a
An expression is a combination of values, variables, and operators. An expression is
evaluated using assignment operator.
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is an
SO SSSSSSSSSsSSSSSSSSSSeseF
Malla Reddy College of Engineering and Technolog 56
© scanned with OKEN ScannerLAN KO De aisouenn
Programming For Problem Sol
Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals,
floating point literals, and imaginary literals.
Some of the python expressions are
Generator expression:
Syntax:( compute(var) for var in iterable )
>>> x:
>>>x
ifor
in‘abe) #tuple comprehension
at 0x033EEC30>
>>> print(x)
at 0x033EEC30>
‘ ot cuetengie!
You might expect this to print as (a, ‘p, 'c) but it prints as The result of a tuple comprehension is not a tuple: it Be eee
generator. The only thing that you need to know now about a generator no
can iterate over it, but ONLY ONCE.
Conditional expression:
Syntax: true, value if condition else false_value
>>> x= 1” if True else “2”
>>>
ped
© scanned with OKEN Scanner