Professional Documents
Culture Documents
-------------------------
in python the integer number data type having "int"class.
in python 2.x version, the integer number data type having 2 types they are
int
long
ex:
---
>>> x=10
>>> x
10
>>> type(x)
<class 'int'>
ex:
---
>>> p=0b1100 #binary
>>> type(p)
<class 'int'>
>>>
>>> r=39#decimal
>>> type(r)
<class 'int'>
wrong inputs:
-------------
>>> z=0b123
File "<stdin>", line 1
z=0b123
^
SyntaxError: invalid digit '2' in binary literal
>>> p=0o38
File "<stdin>", line 1
p=0o38
^
SyntaxError: invalid digit '8' in octal literal
Floating point number data type:
--------------------------------
in python the floating point number data type having "float" class
ex:
---
>>> x=2.3
>>> x
2.3
>>> type(x)
<class 'float'>
>>> y=2.3e2
>>> y
230.0
>>> type(y)
<class 'float'>
>>> z=0.23
>>> type(z)
<class 'float'>
>>> a=2.3e+2
>>> a
230.0
in python we can assign only decimal number system as a flotinng point object.
>>> x=0b101.01
File "<stdin>", line 1
x=0b101.01
^^^
SyntaxError: invalid syntax
>>> q=0o32.1
File "<stdin>", line 1
q=0o32.1
^^
SyntaxError: invalid syntax
>>> z=0x2c.7
File "<stdin>", line 1
z=0x2c.7
^^
SyntaxError: invalid syntax
>>> p=39.2
>>> type(p)
<class 'float'>
>>> x=2+3j
>>> x
(2+3j)
>>> type(x)
<class 'complex'>
>>> y=3J
>>> y
3j
>>> type(y)
<class 'complex'>
>>> z=2+3.2j
>>> type(z)
<class 'complex'>
>>>
>>> a=2+3k
File "<stdin>", line 1
a=2+3k
^
SyntaxError: invalid decimal literal
>>> i=1+3j
>>> i
(1+3j)
>>> a=3
>>> b=2j
>>> c=a+b
>>> c
(3+2j)
>>> type(c)
<class 'complex'>
>>> x=3
>>> y=2
>>> z=x+yj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'yj' is not defined. Did you mean: 'y'?
note:
-----
int() --> to convert any type of data to integer
--> by default return value is 0
>>> x=int()
>>>
>>> x
0
>>> y=2.3 #float
>>> int(y)
2
>>> z=2+3j #complex
>>> int(z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a real number,
not 'complex'
>>>
>>> x=float()
>>> x
0.0
>>>
>>> y=5 #int
>>> float(y)
5.0
>>>
>>> z=2+3j #complex
>>> float(z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float() argument must be a string or a real number, not 'complex'
>>>
complex()
--> to convert any type of data into complex type
--> by default return value is 0j
>>> x=complex()
>>> x
0j
>>> y=3 #int
>>> complex(y)
(3+0j)
>>> z=2.3 #float
>>> complex(z)
(2.3+0j)
what is comment:
----------------
a comment is unexecuted statement in our source code.
generally, the comments are used to write the user friendly messages to the
developpers/endusers/programers/testers.
note:
-----
bool()
>>> x=bool()
>>> x
False
>>> y=3#int
>>> bool(y)
True
>>> z=0#int
>>> bool(z)
False
False
>>> p=2+3j #complex
>>> q=0+3j #complex
>>> r=0+0j #complex
>>> s=0j #complex
>>> t=2+0.0j #complex
>>> bool(p)
True
>>> bool(q)
True
>>> bool(r)
False
>>> bool(s)
False
>>> bool(t)
True
>>> x=False
>>> int(x)
0
>>> float(x)
0.0
>>> complex(x)
0j
>>>
>>> y=True #bool
>>> int(y)
1
>>> float(y)
1.0
>>> complex(y)
(1+0j)
===================================================================================
======================================================
in python the string object is sequence object i.e, both input and output order
will be same.
>>> x="bala"
>>> x
'bala'
>>> type(x)
<class 'str'>
>>>
>>> y='krishna'
>>> y
'krishna'
>>> type(y)
<class 'str'>
>>>
immutable:
----------
>>> y
'krishna'
>>> id(y)
1958281295216
>>> y[2]
'i'
>>> y[2]='o'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
iterable:
---------
>>> for i in y:
... print("Hello")
...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
>>>
>>> y
'krishna'
>>> for i in y:
... print("Hello",i)
...
Hello k
Hello r
Hello i
Hello s
Hello h
Hello n
Hello a
>>>
List datatype:
==============
in python, the list datatype having 'list' class
we can create a list object by using [] or by using list() function or
list(iterable object)
in python, the list object is a mutable object i.e, we can modify the data.
in python, the list object is a sequence object i.e, both input order and output
order will be same.
in python the list object is a iterable object i.e, we can use repeated purpose or
we can apply the iterations.
>>> x=[5,6,7,9]
>>> x
[5, 6, 7, 9]
>>> type(x)
<class 'list'>
>>>
mutable:
---------
>>> id(x)
1958281028544
>>> x[1]
6
>>> x[1]=10
>>> x
[5, 10, 7, 9]
>>> id(x)
1958281028544
iterable:
---------
>>> id(x)
1958281028544
>>> for ele in x:
... print("Hai", ele)
...
Hai 5
Hai 10
Hai 7
Hai 9
>>>
>>> x=(4,5,9,10)
>>> x
(4, 5, 9, 10)
>>> type(x)
<class 'tuple'>
>>>
set datatype:
-------------
in python, the set datatype having 'set' class
we can create a set object by using { } or by calling set() or set(iterableobj)
in python the set object is a non-sequence object i.e, both input order and output
order will not be same.
>>> x={4,1,9,99}
>>> x
{1, 99, 4, 9}
>>> type(x)
<class 'set'>
>>> id(x)
1958281163520
>>> x.remove(99)
>>> x
{1, 4, 9}
>>>
>>> x
{1, 4, 9}
>>>
>>> for ele in x:
... print("Hello", ele)
...
Hello 1
Hello 4
Hello 9
frozenset datatype:
-------------------
in python the frozenset datatype having 'frozenset' class
we can create a frozenset object by using frozenset() or frozenset(iterableobj)
in python, the frozenset object is a non-sequence iterable and immutable object.
>>> x=frozenset([6,7,4,9])
>>> x
frozenset({9, 4, 6, 7})
>>> type(x)
<class 'frozenset'>
>>> for ele in x:
... print("Hai", ele)
...
Hai 9
Hai 4
Hai 6
Hai 7
>>>
note:
------
str()
---> to convert any type of data intostring
---> by default return value is empty string
>>> x=5
>>> y=2.3
>>> z=3+2j
>>> a=False
>>> b=[5,2,7,9]
>>> c=(4,3,7,1) #tuple
>>> d={9,3,5,6} #set
>>> e=frozenset([5,6,7,8])
>>>
>>> str(x)
'5'
>>> str(y)
'2.3'
>>> str(z)
'(3+2j)'
>>> str(a)
'False'
>>> str(b)
'[5, 2, 7, 9]'
>>> str(c)
'(4, 3, 7, 1)'
>>> str(d)
'{9, 3, 5, 6}'
>>> str(e)
'frozenset({8, 5, 6, 7})'
list()
---> to convert any type of iterable object into list
---> by default return value is empty list i.e, []
set()
---> to convert any type ofiterable object into set
---> by default return value is empty set i.e, set()
>>> x=345
>>> set(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> a=(4,5,6,7)
>>> set(a)
{4, 5, 6, 7}
>>>
frozenset()
---> to convert any type of iterable obj into frozenset
---> by default return value is empty frozenset i.e,
frozenset()
===================================================================================
=======================================================
dict datatype:
==============
in python, the dictionary data type having 'dict' class
we can create a dict object in python using {} or by calling dict()
the dict object contains group of key-value pairs, each key value pair as a one
item in our dict object
{key:value, key:value,...key:value}
the dict object is a mutable object but key's must be immutable and values are
either mutable or immutable objects.
from python 3.4+ versions on wards, the dict object act as a sequence object.
none datatype:
==============
in python, the none datatype having 'nonetype' class
in python, at the time of declaring the variables we have to assign the value
mandatory.
>>> x=y=z=None
>>> x
>>> y
>>> z
>>>
we can read the values from user input in c language by using input() ,raw_input()
ex1:
write c prog to read two input values from user.
in python 3.x we can read any type of value from the user input through input() by
default that value treated as string type.
if we want to required data as input , in that case we can apply the type
convertions.
4 types.
octal no system
----------------
the binary no system base value is 8
it contains 0-7
we can represent the octal no system in python that number system contains prefix
0o
ex: 0o37
decimal no system:
------------------
the binary no system base value is '10'
it contains 0-9
ther is no special char to represent the decimal no system.
039 #invalud
we can represent the hexadecimal no system in python that number system contains
prefix with '0x'
ex: 0x2c
>>>
>>> x=0b1010
>>> type(x)
<class 'int'>
>>> x
10
>>> y=0o37
>>> y
31
>>> type(y)
<class 'int'>
>>> z=39
>>> z
39
>>> p=0x2c
>>> p
44
>>> type(p)
<class 'int'>
>>>
note:
we can pass any number system as a input to the python interpreter by default the
python interpreter to convert that number systems into decimal number.
===================================================================================
========================
7:13 PM 3/10/2023
>>> x
13
>>> bin(x)
'0b1101'
>>>
2)13(
2)6(1
2)3(0
2)1(1
>>> x=0o37
>>> x
31
>>>
H --> D --> B
octal to hexadecimal
---------------------
>>> x=0o37
>>> hex(x)
'0x1f'
>>>
hexadecimal to octal
--------------------
>>> x=0x2d
>>> x
45
>>> oct(x)
'0o55'
===================================================================================
======================
7:09 PM 3/14/2023
string handling:
----------------
a string is a character / collection of characters / sequence of words.
in python, the string datatype having 'str' class.
in python, the string obj is a immutable, sequence and iterable obj
x='siva'
y="krishna"
z='''siva
krishna
new way
python'''
>>> x='bala'
>>> print(x)
bala
>>> print("+"*30)
++++++++++++++++++++++++++++++
>>>
note:
-----
a quote inside same quote is not possible but a quote inside different quote is
possible.
x='hai "bala" how are you'
y="Hello 'i am good' how are you"
z='''bala
"good"
'job'
"""hello"""
43443'''
===================================================================================
======================
x="bala krishna"
x[:4]
scenario-2:
----------
if we want to retreive last-N charecters from the string object, in that case we
are using folloiwng syntax
strobj[start: ]
here start index value is inclusive value
by default increment by '1'
>>>
>>> x[-7:]
'krishna'
>>> x[5:]
'krishna'
>>> x[-4:]
'shna'
>>> x[8:]
'shna'
>>>
scenario-3:
------------
if we want to retreive some middle charecters from the stirng object in that case
we are using following syntax.
strobj[start:stop]
here the start index is a inclusive
the stop index is a exclusive
by default increment by '1'
note:
-----
strobj[start:stop:step] we are not passing any start value, stop value , step
value in that case to return the our original string as a output.
>>> x="bala"
>>> x
'bala'
>>> x[::]
'bala'
>>> x[::1]
'bala'
>>> x[::-1]
'alab'
>>> x[:]
'bala'
>>>
strobj[start:stop,step] we are not passing any start value , stop value but we are
passing step value as negative, in that case our string printed from right to left.
>>> len(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>>
ord()
======
to return the ASCII value of the given character
ord(char)
note:
a - Z --> 97 - 122
A - Z --> 65 - 90
0 - 9 --> 48 - 57
>>>
>>> ord('a')
97
>>> ord('A')
65
>>> ord('9')
57
>>> ord('@')
64
>>> ord('/')
47
>>> ord('av')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
>>>
max()
-----
assign2:
---------
wap take the string as input from the user to print even indexing characters and
odd indexing characters seperated by ','?
input output
----- -------
siva sv,ia
siva krishna sv rsn,iakiha
assign3:
--------
wap take the string as input from the user to swap the first character and last
character in a string?
input output
----- -------
siva aivs
siva krishna aiva krishns
assign 2:
----------
x=input("enter the string")
print(x[::2],x[1::2],sep=",")
or
x=input("enter the string")
print(x[::2]+','+x[1::2])
>>> x='bala'
>>> x[0]
'b'
>>> x[-1]
'a'
>>> x[1:-1]
'al'
assign 3:
----------
>>> x[-1]+x[1:-1]+x[0]
'aalb'
>>> print(x[-1]+x[1:-1]+x[0])
aalb
>>>
7:28 PM 3/16/2023
=================
sorted()
to print the elements/characters in sorting order.
by default the sorted function return the ascending order.
>>> x='bala'
>>> y=[4,5,6,2]
>>> sorted(x)
['a', 'a', 'b', 'l']
>>> sorted(y)
[2, 4, 5, 6]
>>> z=563
>>> sorted(z)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
sorted(iterableobj,reverse=True)
>>> sorted(y,reverse=True)
[6, 5, 4, 2]
>>> sorted(x,reverse=True)
['l', 'b', 'a', 'a']
>>> sorted(z,reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
reversed()
===========
to return the reversed object, that object contains elements/characters in reverse
order.
reversed(iterableobj)
>>> x='bala'
>>> reversed(x)
<reversed object at 0x00000174E7769DB0>
>>> list(reversed(x))
['a', 'l', 'a', 'b']
>>>
Functions
----------
we can define any one logic to perform particular operation from outside of that
class, is known as a function.
the function is not executed automatically, whenever we are calling a funcion then
only function logic will be executed.
we can call the function directly by using function name.
we can define any one logic to perform a perticular operation within/inside the
class is known as a method.
the method is not executed automatically whenever we are calling a method then only
method logic will be executed.
note:
-----
if we want to display the all the variable methods with syntax and description of
any class in that case we are using help()
syntax:
-------
help(classname)
ex: help(str)
help(list)
7:13 PM 3/17/2023
=================
working with str class methods
==============================
in python every builtin class having two types of methods, they are
1. magic/dunder/special methods
2. normal methods
magic/dunder/special methods:
==============================
any method name which congtains both prefix and suffix double underscores(__) that
type of methods are called dunder methods.
these methods are executed automatically whenever we are performing that perticular
operation.
dir(str)
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize',
'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition',
'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>> x='bala'
>>> y='krishna'
>>> x+y
'balakrishna'
>>> x.__add__(y)
'balakrishna'
>>>
>>> x='bala'
>>> y=3
>>> x*y
'balabalabala'
>>>
>>> x.__mul__(y)
'balabalabala'
>>>
>>> a='bala'
>>> b='krishna'
>>> a==b
False
>>>
>>> a.__eq__(b)
False
>>> a!=b
True
>>> a.__ne__(b)
True
>>> a>b
False
>>> a.__gt__(b)
False
>>>
normal methods:
================
these methods dont contain both prefix and suffix "'__"" underscores.
these methods are not executed automatically, whenever we are calling a mehtod then
only these methods rae executed.
examples:
----------
capitalize()
to return the copy of the string with only first word first character in
upper/capital case.
strobj.capitalize()
>>>
>>> x='bala'
>>> y='GOOD Evening'
>>> z="Hello Bala"
>>> a='HAI RAMA'
>>> x.capitalize()
'Bala'
>>> y.capitalize()
'Good evening'
>>> z.capitalize()
'Hello bala'
>>> a.capitalize()
'Hai rama'
>>>
title()
-------
to return the copy of the string with only each and every word first alphabetin
upper/capital case.
strobj.title()
>>> y.title()
'Good Evening'
>>> z.title()
'Hello Bala'
>>> a.title()
'Hai Rama'
count()
>>> x='balakrishna'
>>> x.count('b')
1
>>> x.count('al')
1
>>> x.count('a')
3
>>>
center()
=========
to return the copy of the string at center position.
strobj.center(width,fillchar)
here width is a output string length by default fillchar is space character the
fillchar must be one character long only.
>>> x='bala'
>>> x.center()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: center expected at least 1 argument, got 0
>>> x.center(3)
'bala'
>>> x.center(13,'@')
'@@@@@bala@@@@'
>>> x.center(13,'@#')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>>
ljust()
========
ljust means left justification.
strobj.ljust(width,fillchar)
here width is a ouput string length by default fillchar is space character the
fillchar must be one character long only.
>>> x='bala'
>>> x.ljust(4)
'bala'
>>> x.ljust(13)
'bala '
>>> x.ljust(13,'a')
'balaaaaaaaaaa'
>>> x.ljust(13,'ab')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>>
rjust()
=======
rjust means right justification.
to return the copy of the stirng at the right side.
strobj.rjust(width,fillchar)
here width is a ouput string length by default fillchar is space character the
fillchar must be one character long only.
>>> x='bala'
>>> x.rjust(13)
' bala'
>>> x.rjust(13,'x')
'xxxxxxxxxbala'
>>> x.rjust(13,'xy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: The fill character must be exactly one character long
>>>
zfill()
=======
to return the copy of the string fill with zeros at left side.
strobj.zfill(width)
upper()
=======
to return the copy of the string in uppercase.
lower()
swapcase()
===================================================================================
=================
7:07 PM 3/20/2023
find()
------
to return the positive index of first occurencess of given character in a stirng
object from left to right
strobj.find(char/substring)
>>> x='bala krishna'
>>> x.find('a')
1
>>>
rfind()
=======
to return the positive index of first occurencess of given character in a string
object from right to left.
strobj.rfind(char/subtsr)
>>> x.rfind('b')
0
>>> x.rfind('a')
11
>>> x.rfind('i')
7
>>> x
'bala krishna'
>>>
index()
=======
to return the positive index of first occurencess of given character in a string
object from left to right.
strobj.rfind(char/subtsr)
>>> x.index('a')
1
>>> x.index('i')
7
>>> x
'bala krishna'
>>>
if char/substr is not find/match in that case only we are identify the difference
between find() and index()
>>> y="siva"
>>> y.find('b')
-1
>>> y[-1]
'a'
>>> y.index('b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
>>> x='hai bala krishna hai'
>>> x.index('a')
1
>>> x.index('a',2)
5
>>>
strip()
-------
to remove all the possible occurencess of given character in a string object at
begining or ending or both places.
strobj.strip(char/substring)
lstrip()
to remove all possible occurencess of given char in a string object at begining
position only.
strobj.lstrip(char's)
>>> y="madam"
>>> y
'madam'
>>> y.lstrip('m')
'adam'
>>> y.lstrip('a')
'madam'
>>> y.lstrip('dma')
''
rstrip()
--------
to remove all the possible occurencessof given characters in a string object at
ending position only.
strobj.rstrip(char's)
>>> y="madam"
>>> y
'madam'
>>> y.rstrip('m')
'mada'
>>> y
'madam'
>>> y.rstrip('dma')
''
>>>
strobj.split()
join()
------
to join the given iterable object elements with our string object.
startswitch()
-------------
to check whether the given string is starts with the input char.