0% found this document useful (0 votes)
3 views12 pages

python 1

The document provides an overview of various data types in Python, including complex numbers, strings, lists, and tuples. It explains how to manipulate these data types using different operations and methods, such as concatenation, slicing, and updating elements. Additionally, it covers string formatting, escape characters, and list functions, illustrating the concepts with examples.

Uploaded by

amiru2005212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

python 1

The document provides an overview of various data types in Python, including complex numbers, strings, lists, and tuples. It explains how to manipulate these data types using different operations and methods, such as concatenation, slicing, and updating elements. Additionally, it covers string formatting, escape characters, and list functions, illustrating the concepts with examples.

Uploaded by

amiru2005212
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Examples: Number

Numbers Standard
Types:
Data
MappingsheodSets Sequences Numbers
programming. complex
number,
represents fractional
(2.5e2 float int
Ox69-Ox260 -0490 080 -786 100 10 Complex Float Integral
(signed data (hargrd
Mutable
(orise MutableImmutable
int (floating Dictionary o List oTupleString
g+derd o o Integer o
= Boolean
and
(complex 2.parts.
5 types
the
70.2-E12 -90.
-32.54e100 32.3+e18 -21.9 15.20 0.0
b
integers):
x sequences
square
is
10point
Fioats
=
store sequences
float the
numbers): 250). numeric
root may positive
real
imaginary or
of values)aiso
(onrot Python
Types
Data
4.53e-7j3e+26)
-.6545+0J9.322e-36j
.876j 45.j 3.14j -1
(which are
be or
negative
values. be
complex part. in
of
scientific
the written Python
chongl be
is
Complex
form
an whole (hargrd
imaginary notation, with supports
a numbers
numbers + a
b], decimal
with following
number).where
are E
or
a point
not and e
a dividing numerical
indicating
used isare b
the
much realfloats the the types:
part and power
integer
in
Python of J of
(or
the and
10
i)
Strings betweer aucrae
as a onitiquouS Set of charActers in
identified
Stungs in Python are auotes.
marks, Python allows for either pairs of sigle or double

.abe "Pythofi an"


P'O!

String Operators:
Example
Operator Description a = 'Hello b= Python

Concatenation a +bwill give HelloPython


Repetition a*2will give HelloHello

Slice - Gives subset of strings(with indexes a[1] will give e


starting at 0 in the beginning of the string and a[1:4] will give ell
working their way from -1 at the end)
r/R Raw String - Suppress actual meaning of print r\n' prints \n and
Escape characters. print R'\n'prints \n
% Format

Example:
>>> txt = "Hello World!!
>>> txt
"Hello World!
>>> print (txt)
Hello World!
>>> print (txt [0]) # Prints first characte of the strinc

>>> print (txt [(2:5]) # Prints characters staring from 3rd to


1lo
>>> print (txt[2:]) # Prints characters starirg from 3:d ciar:
1lo World!
>>> print (txt [(:5]) # Prints characters up to 6th
Hello
>>> print (txt[-1] ) # Prints last character
!
>>> print (txt[-3:]) # Prirnts last 3 characters
ld!
>>> print (txt|:-5]) # Prints characters excert las
Hello W
>>> txt*2 # Prints string two times
Hello World!Hello iorld!
>>> len (txt) # Prints runber c
12
characers in te s r g
>>> txt + "Test" = Prints conzatenated string
Hello World!Test

2
Updating Strings:
>>> txt = " Hello
>> print World!!
(txt(:6]
Hello Python
+
'Python')

Escape Characters:
Following table is a list of
escape or
backslash notation. non-printable characters that can be represented with
Backslash
notation Hexadecimal
character Description
Ox08
|\e Backspace
Ox1b
Escape
Ox0c
Formfeed
\n Ox0a
Newline
\s Ox20
Space
\t Ox09
Horizontal tab
Ox0b
Vertical tab
Single quote ()
Double quote (")
Backslash

String Formatting Operator:


This operator is unique to strings.
Example:
>>> print ("My name is $s and weight is
%d kg!" S (Zara', 21))
My name is 2ara and weight is 21 kg!

Here is the set of symbols which can be used along with


%:
Format Symbol Conversion
character
string conversion via str() prior to formatting
signed decimal integer
od signed decimal integer
%f floating point real number
Cont

list
ite
Triple Quotes: A
multiple lines.
triple quotes come to the rescue by allowing strings to span
Python S quotes.
three consecutive single or double
The syntax for triple quotes consists of
this is a long string that is made up ol
Para_ str =
several 1ines and non-printable characters sUch aS
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the strina, whether explicitly given like
this WIthin the brackets | \n 1, or just a NEWLINE Within
the variable assignment will also show up.
Print (para str)

This will produce following result. Note how every single special character has been
Converted to its printed form, right down to the last NEWLINE at the end of the string
between the "up." and closing triple quotes. Also note that NEWLINES OCCur either with an
explicit carriage return at the end of a line or its escape code (\n):

this is a long string that is made up of


several lines and non-printable characters such as
TAB ( ) and they will show up that way when
displayed.
NEWLINES within the string, whether explicitly given like
this within the brackets [
1, or just a NEWLINE within
the variable assignment will also show
up.

String Methods
Amethod is called in the
following way.
object.method (arguments)
eg: text = new year 2020! !"

Python
Expression Output Description
text.strip() 'new year 2020!! strip() method removes leading and
ending white space characters or a
given character in a string. The default
strip character is white space (space,
tab, \n).
text.strip(!") new year 2020 Removes leading and ending !
characters
text.split() ['new', 'year', '2020!!] Splits (divides) a string using a given
character and creates a List. The
default split character is space.
text.split('e') ['n','w y', 'ar 2020!!] Splits the string using the character 'e'

4
A
You Lists:
the Updating >>> L2L1[:-2]
>>>[123, ['abcd', >>> Ll[-2]
[2.23, L1[1:31
(786,Ll >>>'abcd
>>> [2:]>>>2.23] >>>[0]L1
['abcd',
>>>L1>>> Example:
>>> The example:For
list2
list3listl= items
Python
list Lists
['physics',
1ist1
>>> >>> 2001listl>>>[2] >>> 1997listl>>>[2] >>> |'abcd', 786, 'john'
2.23]
values Contains
listi
assignment
1istl
can Ll L2 L1 belonging
listl = "a",
update 'john',+ = (1,
john',
70.2] stored
(123, physics''chenistry',
786, |'abcd'
[3] [2) = 786, L2 2
2, items
"b", to
'chemistry',
2001,
4000] operator,single 3,
= ['physics',
=
2.23, 123, 2.23,
'john']
in
a list
a
listi[3] 2001 , 4, separated
list "c"
or 786 5 can
'john'] 'john',
multiple
and 'john', can "d"]: ]: be
,
*2 2.23, be of by
'chemistry', you
70.2] accessed different
commas
elements
can 70.2,
'john 1997,
add
123, using data
', and
to of 2000]
1997,elements lists 70.2 the type.
enclosed
5 'john']
:
by ] slice
2000)
giving
in within
operator
a
list the
square
with slice
IJ(
the and brackets
on
append() the [
:
J):
left-hand J:
Al
method: tne
side
of
Inserting List Elements:

>>> Color
|'Red','Grecn'J VISIT USs!
Color + |'B! ue'})
>>> color

>> color
{'Red', 'Grecn', 'Blue']

Deleting List Elements: exactly whích


the del statement if you knoW
either
element, you can use not know.
To remove a list deleting or the remove() method if you do
element(s) you are
1997, 2000]
>>> listl |'physics , ' chemistry',
>>> del listi|2)
>>> listl
['physics', 'chemistry', 2000]

Membership Check
>>> color = ['Red', 'Green', 'Blue']
Blue! in color
True
>>> Yellow in color
False

Replacing Elements in a List


>>> LA= [10,20, 30,40,50]
>>> LA[l:4]= (2,3,4, 5]
>>> LA
{10, 2, 3, 4, 5, 50]

A nested list is created by replacing an elemnent with a list.


>>> num= (10,20,30, 40,50]
>>> num [1] = [1,2,3,4, 5)
>> num
(10, [1, 2, 3, 4, 5], 30, 40, 50]
>>> num [0]
10
>>> num [ 1)
[l, 2, 3, 4, 5]
>>> num [ 1] [2]
3
>>> L = ||1,2,3], (1.1,2.2,3.3], ('A', 'B', 'C'J}
>>> len (L1)
3
>>> len (L1 |1])
3
>>> LJ [2] |2]
C
SIN

List Functions:
Color |'Red','Green', ne'1
ma ks

Description
Python Expression Results

len(color) Lengthof the 'color' list in the 'color' list


elernent
Length of second
len(color[1)) 'rmarks' list
Minimum value in the
min(marks) 34
'marks'list
82
Maximum value in the
max(marks)
[L, 'a', 'n, 'k, 'a'] Convert astring to a list
list('Lanka')

List Methods

A method is called in the following way.


object.method(arquments)
Description
Results
Python Expression of a list
[34, 78, 63, 82, 73] Appends an element to the end
marks.append(73) 2)
Inserts an element into alist (index
color.insert(2,'Pink')['Red', 'Green', 'Pink','Blue']
Removes an element from a list
color.remove('Red')['Green', 'Pink', 'Blue']
[73,82, 63, 78, 34] Reverses elements of a list in place
marks.reverse()
Appends clements of another list to the
color.extend(marks) ['Green', "Pink', 'Blue', 73, list concern
82, 63, 78, 34]
Counts the occurrences of an element
[1,4,1,5,1].count(1) |3 in a list
Finds the index of the first occurrence
marks.index(63) 2
of an element

Python Tuples
enclosed within parentheses.
Atuple contains a number of values separated by commas and
in brackets ), and
The main differences between lists and tuples are: Lists are enclosed parentheses ( ) and
their elements and size can be changed, while tuples are enclosed in
cannot be updated. Tuples can be thought of as read-only lists.

For example:
|tup1 'physics', 'chemistry', 1997, 2000)
i tup2 (1, 2, 3, 4, 5)
tup3 "a", "b", "c", "d" #Ca oiL patentheses
tup4 ) #n etnpty t iple

fonfny
To write atuple containing a single value you have to include a comma, even
only one value:

>>> tup] = (50)


though h

>>> tup1
S0
>>> tupl - (50,)
>>> tup1
(50, )

Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on
Example:
>>> T1 = 'abcd', 786, 2.23, john', 70.2)
>>> T2 = (23,
john')
>>> T1
# Prints complete list
('abcd', 786, 2.23, 'john', 70.2)
>>> T1 [0]
# Prints first element of the list
'abcd
>>> T1 |1:4]
# Prints element s starting from 2nd to 3rd
(786, 2.23,john' )
>>> T1 (2:] # Prints clements starting from 3rd element
(2.23, 'john', 70.2)
>>> T1 [-2) # Prnts 2nd element from the right
'john
>>> T1|:-2] # Prints elenents up to the 2nd element from right
(" abcd', 786, 2.23)
>>> T2 2 # Prints 1ist two times
(123,john', 123, john')
>>> T1 + T2 # Prints concatenated lists
(' abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Accessing Values in Tuples:


>>> tupl = ('physics', chemistry', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5, 6, 7)
>>> print ("tupl [0): " tupl (0])
tupl [0): physics
>>> print ("tup2[1:5] : ". tup2 (1:5])
tup2[1:5]: (2, 3, 4, 5)

Tuples cannot be updated or changed values of tuple elements, But it is able to take portions
of an existing tuples to create a new tuples as follows:
Example:
>>> tupl = (12, 34.56)
>>> tup2 = ('abc''xyz')
>>> tup3 = tup1 + tup2
>>> tup3
(12, 34.56, 'abc', 'xyz')
just
tuple,
tuple
entire
the
an in
Description
element
tupletuple
remove tuple
a a a
explicitly tuple of of tO
second
valuevalue string
a Maximum
of of Minimum
To 2000) 'C')) Length
Length Coverts
p0ssible.
1997,
'B',
9
(1.1,2.2,3.3),("A', 'a')
not 'chemistry',
'Blue')
('Red','Green',
'Blue') Results 'k',
is
elements 'n',
'Green', 'a',
63,82) ('L',
Elements:
Tuple
peletingtuple 34 82
', color 3 5
statement:physics ('Red',
color (1,2,3), Expression
Python
individual Membership
Check (34,78,
in
)
Functions:
Tuple
in [1]
"Yellow' Nested
Tuples [2]
del
>>>
del
tup =
color
(T1)
len
>>> (T1
(2] len(color[1]) tuple('Lanka')
min(marks)
max(marks)
'Blue T1=
Removing tup = len(color)
the Example:
len T1
False marks
color
>>> >>>
>>>>>>True >>> >>> >>>'C!
use
3 3
modifying
val,aCCOSSedus

coTOSponding pair), 'First')

and key-value
unordered.
0ssigned 'Class':
'First'}
ther
a
are (i.e.,
below:
be 'Cewil':358 key onary Zara',
and They
can item 'Class':
keysvalues
'oe!
i values shown
dict keys clements. or
entry 'Name!:
of and for cOmplete as 7, 10
the the
one'} entry
items) vlue new 'Age':School"
} 910", all all among
bracos is a existing 'Age':
8,
s
Pints
Prints Prints adding
(called This Print This
one') order
is '2ara',
'Beth': on" "DPS
curly 37) by an ['School'])
# of
pairs wo" # # 'one': H deleting ('School':
DPS
School',
is concept dictionary =
8 ['School']
by 98.6: Name':
t
"This =
enclosed {'AliCo':341',
Python
Dictionary
of
is
Updating
Dictionary: 'Age']
['Age']
450}
123, ""his This
is
two no or {" >>>
len
(student)
cons1stsquare (student
brackets
). dl.values
() [This
is
two', have a entry, =
di|'one'|This
is
One' () update [
are 'ae':
{'abel: keys student
student
student
student >>>
student
[2,
'one')
Dictionaries
Dictionaries |2] Dictionaries existing
len
Exampiv: di
dl.
can Example:
- >>> >>> >>>
>>> >>>10
ielde:: >> >>> {2:>>> >>> You
de an 8 4
modifying
usin
val,.
accessed
corresponding pair), 'First')

and key-value
unordered.
assigned 'Class':
'First'}
their a
"3258) are (i.e.,
be below:
and key dictionary 'Nane':'Zara',
can They
item 'Class':
'one' values shown
keys
values 'Ceci1': elements.
keys or
entry
of and for complete as 7, 10
This
is the
one'} the
iterms) newentry
value among 'Age':School"
{} 9102, al] al1
8,
a existing
braces Prints
Prints Prints
Prints adding 'Age':
(called order 'Zara',
1This
is
orne']
Beth': "This
is
one" "DPS
curly ['School'])
37)
# 'one':
# #
of by an School',
pairs two" # concept deleting =
by 98.6: dictionary 8
{'Name':
"2341, = ['School']
Python
Dictionary
of
enclosed is
two', Updating
Dictionary: >>>
student
['Age']
['Age']
{'abc':
456)
123, "This no or
consist DPS >>>
len
(student)
(student
Square
brackets
]. () [This
>>> is
two',
d1.values have a entry, =
are {'Alice': >>>
d1 >>>
dl['one'3
{'one'] Thisis
one' is >>>
d1.keys
() update
('abc': = student
studentstudent>>>
student
{} (2,
'one'] {'School':
Dictionaries
Dictionaries (2) This Dictionaries existing
= len
Examp
le: dl d1 >>>
dl can Example:
>>> >>> {2: Youan >>> >>>>>> >>>
de dcldc2 8 4
a more.
of
contents
any
exist
entire
not
statement. 'Name' does
the stdt dictionary dictionary
clear '}
'Firstkey in
or del entries
with
elements
the 'Class': stdt,
entry entire
using all <module> del
dictionary
explicitly remove remove delete defined after
7,
'Age': :last)
in because
# # # 1, not
removed
Deletingindividual
Elements:
Dictionary 'First'}
'Name:Zara', line
call
is
"<pyshell#33>",
recent
is
'stdt'
this
be '] raised,
remove
can 'Class':
stdt'Name
diction3Iy stdt.clear()
>>> (most name exception
either { stdt
del
>>>
= 7, NameError:
Traceback
dictionary. dt deistdt
>>>{'Age':
stdt
>>> stdt
>>> stdt
File
can entire st
Exampie: an
>>> Note
Vau An S {

You might also like