0% found this document useful (0 votes)
0 views20 pages

Python Programming 4

The document provides an overview of Python programming concepts including variable creation, identifiers, data types, and their characteristics. It explains the rules for identifiers, the use of built-in functions like type() and bool(), and details on single and multiple value data types. Additionally, it covers mutable and immutable data types, lists, tuples, sets, and dictionaries, along with their syntax and methods for manipulation.

Uploaded by

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

Python Programming 4

The document provides an overview of Python programming concepts including variable creation, identifiers, data types, and their characteristics. It explains the rules for identifiers, the use of built-in functions like type() and bool(), and details on single and multiple value data types. Additionally, it covers mutable and immutable data types, lists, tuples, sets, and dictionaries, along with their syntax and methods for manipulation.

Uploaded by

pj5960759
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

Multiple Variable Creation:

 If the user wants to create multiple variable or store more than one variable with respective values in a
single line, it should MBC rule
 Rule state that number of variables should be always equal to no of values
 In other programming languages, one variable is always assigned with one value and next variable with
another value which means variables and values are return in the same line
 Syntax:
Var1, var2,…………….,varN =valu1, valu2,…………..valuN
 a, b, c= 1,2,3
 where first variable is assigned with first value, second variable with second value and so on.

Identifier:

 It is a naming word given for any variable or object or class or function or any thing which is developed
by the user
 Variable is used to store the values
 Object is a living or non-living thing which is exist in real world
 Class is the collection of similar objects
 Function is used to perform some specific tasks in a program

Rules of identifier:

 Keywords should not be used as an identifier We cannot assign the keyword as a variable
 Any special characters cannot be used as an identifier accept “_”
 Digits in the starting of an starting identifier is prohibited
 Blank space in the and middle of the variable is not used
 Any alphabet or alphanumeric number or _ can be used as an identifier
 if = 32 , ab=12, 302a=1 all the identifiers are wrong
 a=10, a12=3, a_b=10

Industrial standard rules:

 it state that in python programming the identifiers can contain maximum 65 characters

Type Function:

 it is an inbuilt function used for checking data type of any value


 a=10 b=10.12
 type(a) type(b)
 <class “int”> <class ‘float’>
 Class is a collection of similar objects which is predefined or defined by the user

Bool Function:
 Bool function is inbuilt function which checks given values are default value or non-default value
 It prints output as false, when the value is default value and print the output as true when the value is
non default value
 Default value means the starting or initial value for any data type and non default value means except
default values all the values are non-default value in a data type

Type of Datatype:

 It is the process of defining different type of values to be stored in memory


 In python datatypes are name classified into two types depending on the values to be stored in a
memory block
 Single value datatype (SVDT) or individual datatype
 When the memory block store exactly one data in the memory block, it is called SVDT
 Multiple values datatype (MVDT) or collection of datatypes
 When the values are to be stored in more than one memory block it is called multiple datatype
 When more than one value to be stored in only one memory block it is called as MVDT

Datatypes:

 SVDT
 Numeric DT: Int, float and complex
 Boolean DT: Default, non-default value
 MVDT
 String, list, dict, tuple and set

Integer datatype:

 It is a real number without decimal point


 It is represented as int
 Its starts range from zero to positive integer and minus infinity to zero
 Syntax:
 Var= valu
 The value should be only integer example: a=12 and m=0
 In integer -5 to 256 number stored in 32 bits operating system where reference address will be same for
heap space and stack space
 If the number is not in the range -5 to 256, the memory allocation will be occurred in 64 bits memory
configuration where reference address is not same but it is similar to stack and heap space. Ex: id(20),
140703643534856, id(290), 2299210927088
 Default value for any datatype
 syntax: [Link](), int()

Floating point:

 It is real number with decimal points


 In python, FP is represented as a float
 Its range is -infinity to 0.0 to + infinity
 Var = value where value should be float or decimal value
 Ex: a=8.49

Complex number:

 In python contains any number and imaginary part contains numbers with imaginary values
 Imaginary value in python is represented by either j or I but in the memory imaginary value with be
stored by only j
 A+bJ where a and b are the number and j is the imaginary values and its internal value is (-1)^1/2

Boolean:

 Boolean mean values


 In python the values are classified into two types one is default and another one is non default value
 Default values are represented by false which internal meaning is zero
 Non default values are represented by true which internal meaning is one

Length:

 Its only applicable only for multi value data type because its check more than one value only for memory
layer
 Ex: a=’python’ len(a) -> 6
 It is a datatype which store in a single memory block by generating memory layer in the memory block
 Syntax is len(variable)

String datatype:

 String is represented as str in python


 Sting is a collection of characters enclosed in quotes
 Character is a single value or any thing which is present in the keyboard
 Character can be any alphabets or any digits or any special symbols or combination of more than one
character
 Either single quotes or double quotes or triple quotes
 Any message in the string will be stored in the single quote
 If the message contains an apostrophe as a special symbol, it will be stored in double quotes
 If the user wants to pass a single message in more than one line, triple quotes are preferred but in the
memory it will stored in either single or double or triple quotes
 Syntax: var=”message” , a=’python’, b=”””sql”””

Indexing:

 Indexing is the process of providing a sub address for indexing number which is stored sequentially
 In python indexing can be done in two ways positive indexing and negative indexing
 Positive indexing:
o it is the process of providing sub address only in positive numbers
o it generally starts from left and moves to the right
o it starts from index number 0 and ends up to length(collection) -1=>[0-len(col)-1]
 Negative indexing:
o it is the process of providing the index number only on negative numbers
o it starts from the right goes up to left in the collection
o index number starts from -1 and hence by minus length of collection [-1 to -len(col)]
 example: a=’python is easy’

0 1 2 3 4 5 6 7 8 9 10 11 12 13
‘p’ ‘y’ ‘t’ ‘h’ ‘o’ ‘n’ ‘i’ ‘s’ ‘e’ ‘a’ ‘s’ ‘y’
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
 syntax: syntax for printing single character from a collection var[index]
 a[1]=’y’ or a[-13]=’y’
 Index Error: IndexError occurs when the character is exceeding the index number which is not present in
the collection.

Mutable:

 It is a datatype which allows modification of values in a same reference address in the heap space
 Ex: list, set and dictionary

Immutable datatype:

 It is a datatype which does not allow modification of values or changes the values in different reference
address
 Ex: all single value data type, string and tuple

List datatype:

 List is a collection of homogeneous and heterogeneous data elements are data values enclosed in [] and
the elements are separated by comma “,”
 Homogeneous list: it is a list containing all the data elements belonging to same datatype
 Ex: a=[1,2,3,4,5,6]
 Heterogeneous list: it a list where more than one datatype elements are present
 Ex: a=[1,2.4,5.2,3,5,”chilli”]

a= [1,2,3,4]

a[0]----->1

2) Adding
*methods to add values to the existing list

*it is inbuild function using for adding a single value to the last of a list

*append method one more block with at the end of in list in the same reference address

syntax :

[Link] (value)

1)append()

2)extend()

3)insert() -----------vip method

a=[1,2,3,4]

[Link](5)

a-------->[1,2,3,4,5]

a[0x32] 12345[0x32]

a=[1,2,3,4]

A. append([1,2,3])

0x33
1 2 3 4 0x38
a
0x33

Extend:
 extend() will create extra memory block depending on number of value present inside a collection
 SYNTAX:
[Link](collection)
Insert:

 It is an inbuild function which will create extra memory block to store value at any index position of
given list

 This function aspect two aurgument 1)index,2)values

 Its special function using for adding at particular index position as required by a user

Syntax:

[Link](index,value)

A=[1,2,3,4]

A. insert(1,15)

A--->[1,15,2,3,4]

1 2 0x58 3
a Ox42
Ox42

A=[1,2,,58,’hello’]
A. append(‘hi’)
A=[‘hi’,’hello’, [1,2,3],[4,5,6]]
A. insert(3,58)
A. extend([5,7,8])
A. append(57)
A. insert(5,500)
A. insert(5,700)

Deleting Elements from the list:


i. Pop()
ii. Remove()

Pop ()
 Its an inbuild function used for removing the value from the list
 Syntax---- [Link](index)
 A=[1,2,3,4,5]
[Link]()
Print(a)
Output:
5
[1,2,3,4]
Remove()
 Its an inbuild function which removes in particular if it is present in the list
 Its first value in list to remove only one value in list
 Syntax ----var. remove(value)
A=[1,2,3,4,5]
[Link](4)
Print(a)
Output:
[1,2,3,5]

Example:
a=[1,'hello','guido van rossum' ,5+6j ]
a
[1, 'hello', 'guido van rossum', (5+6j)]
[Link](['java','python','php'])
[Link](['a','b','c'])
a
[1, 'hello', 'guido van rossum', (5+6j), 'java', 'python', 'php', ['a', 'b', 'c']]
[Link](5,'python')
[Link]()
['a', 'b', 'c']
[Link](5)
'python'
[Link](7,'pysider')
a
[1, 'hello', 'guido van rossum', (5+6j), 'java', 'python', 'php', 'pysider']
[Link]('hello')
[Link](5)
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
[Link](5)
ValueError: [Link](x): x not in list

Tuble:
 Tuble is a collection of homojinious or hetrogenious enclosed in commun and seprated by ,
 Pracgets are option and ( , ) complusory to seprate the value
 Tuble is unmutetable ,only for use secured application
 Syntax: var=val1,val2……,valn
 Example:
A=(1,2,3)
B=(1,2+3j,’hello’)
 In tuble ‘ , ‘ is main to use and () are optional

Stack heap

1 2 3

0x43
0x43

a=(1,2,3,[1,2,3],5,6)

b=[1,5+2,8,12,[3+2j,5+2j,(1+3j,'python','py','btm')],52,70,57+85]

c=[(1+3j,'hi','hey','apple'),(2,58,'mango',72,59+172),(3+2j,1+2j,(2+3)),'peg parser']

Example of Set:

A=[1,2,3,(‘zero’,’INDIA’),(1+2J)]
Len(

Dictionary :
 Dictionary is a collection key and value enclosed in { }
 Dictionary is mutable data type but that keys inside dict are immutable
 Key should be unique
 Key and value pasce are separator by column
 Combination of one key and one value will make one key value pair
 Key pair are separator but ,
 In python dict represented by ‘dict’
 Default value for dict is empty { }
 Var={k1:v1,k2:v2,……..,kn:vn}
Example:
a={1:’one’,’two’:2}
Stack
Heap
0x71
a

1 0x23

For users only key pair is visible hence dict Is Consider as safe to use in project
untill X022 2 the user gets the key

A={1:[1,2,3],’bye’:’holiday’,’welcome’: ‘python’

To update the key value


Syntax:
Var[key]=new_value
A[1]=’one’
To add new key value pair in existing dictionary
Var[new_key]=value
a[2]=’two’
Example:
b={1:2,'one':'two','three:four':34}
b
{1: 2, 'one': 'two', 'three:four': 34}
b[5]='high-five'
b
{1: 2, 'one': 'two', 'three:four': 34, 5: 'high-five'}
b[1]='study python'
b
{1: 'study python', 'one': 'two', 'three:four': 34, 5: 'high-five'}
b['three']

Pop fuction
This method remove particular when key are passed as an argument
Syntax:
[Link](key)
[Link](1)
2
c
{3: 4}
[Link](1)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
[Link](1)
KeyError: 1
[Link](3)
4
c
{}

[Link] DATATYPE DEFAULT VALUE CHARACTERISTIC

1 INT 0 WITHOUT DECIMA POINT


2 FLOAT 0.0 WITH DECIMAL

3 COMPLEX 0j REAL NO. WITH IMAGINARY VALUES

4 BOOL FALSE VALUES(DEFAULT,NON-DEFAULT)

5 STR ‘‘ CHARACTERS INSIDE QUOTES

6 LIST [] MUTABLE,COMMA’S COMMONLY USED

7 TUBLE () IMMUTABLE,COMMA’S ,SECURED

8 SET SET() MUTABLE,UNODERED,FLOWER BRACKETS,

NON-DUBLICATE VALUES

9 DICT {} MUTABLE,UNODERED,KEY-VALUES PAIR

Syntax:
Dir(datatype)-in built function of datatypes
Funtion on string
Capitalize ():-Capitalize the first letter of string,only use str
a=”sTinG Of PyTHoN”
a. capitalize()
“String of python”

Case fold()-make it simple to human readable,only use str


a="STRING"
[Link]()
'string'
Center()-Centerlizing the string

[Link](10)

' STRING '

Count Funtion- Count the string only

[Link]('S')

Encode ()
A=’python is confusing us’

A. encode()

>>>b’python is confusing us’

Endswith()
A. endswith(‘s’)

>>True #One Tab space = 4 normal space

Expandtabs()
a=’python\tcode’

a. expandtabs(10)

>>> python code #empty space for expandtabs

Find()

a. find(‘p’)

>>>0 print the index of character

Format()
A=’my name is {}’.format(‘sanjai’)

>>>my name is sanjai


Isalnum()
a. isalnum() #either num or alphabet
>>>True
a
'python'
[Link]() #empty space also special character
>>>>False
b
'python\tis\tEasy'
c='python code' #empty space also special character

[Link]()
False

Isalpha()
a=’python’
[Link]() #only alpha values
True
‘hello world’.isalpha()

Isascii()
a. isascii () #is check string or not unicode (0 to 257)

text = "Hello123!"

print([Link]())

>>> True

Isdecimal()
text = "12345"
print([Link]()) # True

text = "123.45"
print([Link]()) #False

Isdigit()
text = "12345"

print([Link]()) # True

print("123abc".isdigit()) # False (Contains alphabets)

print("123.45".isdigit()) # False (Contains a decimal point)

print("123 456".isdigit()) # False (Contains space

Isidentifier()
print("hello".isidentifier()) # True

print("variable_name".isidentifier()) # True

print("myVar123".isidentifier()) # True

print("_private_var".isidentifier()) # True

print("123abc".isidentifier()) # False (Cannot start with a digit)

print("hello world".isidentifier()) # False (Contains space)

print("my-variable".isidentifier()) # False (Contains hyphen `-`)

print("class".isidentifier()) # True (But "class" is a Python keyword)

Islower()
text = "hello world"

print([Link]()) # True

Isnumeric()
text = "12345"

print([Link]()) # True

Isprintable()
text = "Hello, World!"
print([Link]()) # True

Isprintable()
text = "Hello, World!"
print([Link]()) # True
text = "Hello\nWorld" # Contains newline (\n)
print([Link]()) # False

text = "Hello\tWorld" # Contains tab (\t)


print([Link]()) # False

Isspace()
text = " "
print([Link]()) # True
text = "\t\n\r" # Contains tab (\t), newline (\n), and carriage return (\r)
print([Link]()) # True
print("hello world".isspace()) # False (Contains letters)
print(" 123 ".isspace()) # False (Contains a number)

Istitle()
text = "Hello World"
print([Link]()) # True
Each word starts with a capital letter, and the rest are lowercase.
print("hello world".istitle()) # False (All lowercase)

print("Hello world".istitle()) # False (Second word starts with lowercase)

print("HELLO WORLD".istitle()) # False (All uppercase)

print("Hello WORLD".istitle()) # False (Second word is all uppercase)

Isupper()
text = "HELLO WORLD"

print([Link]()) # True

print("Hello World".isupper()) # False (Contains lowercase letters)

print("HELLO world".isupper()) # False (Contains lowercase letters)

print("12345".isupper()) # False (No alphabetic characters)

print("HELLO123".isupper()) # True (Numbers are ignored)


print("HELLO!".isupper()) # True (Symbols are ignored)

Join()
words = ["Hello", "World", "Python"]

result = " ".join(words) # Joins with a space

print(result)

>>> Hello World Python

text = "PYTHON"

result = "-".join(text)

print(result)

>>>P-Y-T-H-O-N

Ljust()
text = "Hello"

result = [Link](10)

print(result) # "Hello "

Isstrip()
text = " Hello, World! "

print([Link]())

>>>"Hello, World!"

text = "---Hello---"

print([Link]("-"))

>>>"Hello"

text = "xyzPythonxyz"

print([Link]("xyz"))

maketrans()
table = [Link]("abc", "123")

text = "abcde"

print([Link](table))

123de
table = [Link]("aeiou", "12345", "!")

text = "Hello, World!"print([Link](table))

table = [Link]("", "", "aeiou") # Remove vowels

text = "Hello, World!"

print([Link](table))

removeprefix() & removesuffix()

text = "HelloWorld"

print([Link]("Hello"))

print([Link]("Python")) # No change

rpartition()
A tuple of three parts

No, always splits once

Splits at first occurrence of the separator

rsplit() & split()


 text = "apple banana mango banana"

 print([Link](" ", 2)) # Splits at the first two spaces

 >>>['apple', 'banana', 'mango banana']

 text = "apple banana mango banana"

 print([Link](" ", 2)) # Splits at the last two spaces

 >>>>['apple banana', 'mango', 'banana']

· Use split() when you need to split from the left (e.g., extracting first words in a sentence).

· Use rsplit() when you need to split from the right (e.g., extracting file extensions, getting last
elements).

Splitlines(“s”)
text = "Hello\rWorld\nPython"
print([Link]("\n")) # ['Hello\rWorld', 'Python']
print([Link]()) # ['Hello', 'World', 'Python']
List Function()
Check---dir(list)
Append()
A=[1,2,3,4]
[Link](2,3)

Traceback (most recent call last):


File "<pyshell#7>", line 1, in <module>
[Link](2,3)
TypeError: [Link]() takes exactly one argument (2 given)
[Link]((2,3))
A
[1, 2, 3, 4, (2, 3)]
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
[Link]()
TypeError: [Link]() takes exactly one argument (0 given)
[Link](1)
1
--------->Count passing only one argument required

Insert()
[Link](1,56)
A
[1, 56, 1, 2, 3, 4, (2, 3)]

Remove()
a=[1,2,3,4]

[Link](2)

>>>[1, 3, 4]

Pop()
 Pop is used to remove and display the value

 Only one argument get for index

 If you cannot give any argument remove the last value in list

a=[1, 3, 4, 6, 7, 9, 4]

[Link]()

[Link](2)

>>>[1, 3, 6, 7, 9]

Index() -pick value on index based


a=[1, 3, 6, 7, 9]

[Link](6)

 The process is converting onte type to another is called type converstion or type casting

 All the program lang type casting can classifed in two type

Implicit type casting


 Convert in the value from same data type to same value in the same memory block

Example

Int is converted into int

Explixit typecasting
 Converting the vvalue from one date type to other data type except its own data type

 Example

 Int ---> float

 In python single value data type cant be converted to mutli value data type and multi value data
type cant be converted to single data type because of memory layer

Syntax for 1 dt to another

Destination_dt(value)
int list
float tuble
complex set
list
str dict

String
 String can converted only if the values in the string or Real numbers without any alphabet or special

 String can be converted to float only if values in the string are real number with or without decimal
number

a='python'

b='10.0'

float(b)

>>>10.0

float(a)

Traceback (most recent call last):

File "<pyshell#3>", line 1, in <module>

float(a)

ValueError: could not convert string to float: 'python'

 String can be converted to complex data type only if the values in the string are integer values or
decimal value or imaginary values

complex(b)

(10+0j)

You might also like