Python 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Python Programming

• Python is a simple, general purpose, high level, and object-oriented


programming language.
• Python is an interpreted scripting language also. Guido Van
Rossum is known as the founder of Python programming.
• Python is easy to learn yet powerful and versatile scripting
language, which makes it attractive for Application Development.
• Python's syntax and dynamic typing with its interpreted nature
make it an ideal language for scripting and rapid application
development.
• Python supports multiple programming pattern, including object-
oriented, imperative, and functional or procedural programming
styles.
• Python is not intended to work in a particular area, such as web
programming. That is why it is known as multipurpose programming
language because it can be used with web, enterprise, 3D CAD, etc.
• Python makes the development and debugging fast because there
is no compilation step included in Python development, and edit-
test-debug cycle is very fast.
• A list of differences between Python 2 and Python 3 are given below:
• Python 2 uses print as a statement and used as print "something" to print
some string on the console. On the other hand, Python 3 uses print as a
function and used as print("something") to print something on the
console.
• Python 2 uses the function raw_input() to accept the user's input. It
returns the string representing the value, which is typed by the user. To
convert it into the integer, we need to use the int() function in Python. On
the other hand, Python 3 uses input() function which automatically
interpreted the type of input entered by the user. However, we can cast
this value to any type by using primitive functions (int(), str(), etc.).
• In Python 2, the implicit string type is ASCII, whereas, in Python 3, the
implicit string type is Unicode.
• Python 3 doesn't contain the xrange() function of Python 2. The xrange() is
the variant of range() function which returns a xrange object that works
similar to Java iterator. The range() returns a list for example the function
range(0,3) contains 0, 1, 2.
• There is also a small change made in Exception handling in Python 3. It
defines a keyword as which is necessary to be used.
• Why learn Python?
• Python provides many useful features to the programmer. These
features make it most popular and widely used language. We have
listed below few-essential feature of Python. Easy to use and Learn
• Expressive Language
• Interpreted Language
• Object-Oriented Language
• Open Source Language
• Extensible
• Learn Standard Library
• GUI Programming Support
• Integrated
• Embeddable
• Dynamic Memory Allocation
• Wide Range of Libraries and Frameworks
Where is Python used?
• Python is a general-purpose, popular programming language and it
is used in almost every technical field. The various areas of Python
use are given below.
• Data Science
• Date Mining
• Desktop Applications
• Console-based Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Enterprise Applications
• 3D CAD Applications
• Machine Learning
• Computer Vision or Image Processing Applications.
• Speech Recognitions
Python Libraries for General Artificial Intelligence
Python has taken a large lead in our quest to determine the best
programming language for AI or neural networks.
• AIMA - Python algorithm implementation comes directly from
Russell as well as Norvig's "Artificial intelligence: A Modern
Methodology. "
• pyDatalog - Logic Programming engine in Python
• SimpleAI - Its primary goal is to provide intuitive, well-documented,
and tested libraries.
• EasyAI - A simple Python engine that allows two players to play
games using AI (transposition tables for Game-solving).
Python for Machine Language (ML)
• Let's look at the reason Python is used in Machine Learning and the
various libraries it provides for this reason.
• PyBrain - is an easy yet flexible algorithm to perform Machine
Learning tasks. It also functions as an extensible Machine Learning
Library for Python that provides a range of predefined
environments for testing and evaluating algorithms.
• PyML - A bidirectional framework developed in Python
concentrates on SVMs and other kernel-based approaches. It's
accessible on Linux and Mac OS X.
• Scikit-learn - can be described as an effective instrument for data
analysis making use of Python. This is a completely free and open-
source library. It is the most widely used general-purpose machine
learning library.
• MDP - Toolkit A different Python Data Processing Framework that is
easily extended contains a variety of unsupervised and supervised
learning algorithms and other computing units for data analysis that
could be combined to create sequences of data processing and
more intricate feed-forward networks. Implementation of the new
algorithm is straightforward. The number of algorithms available is
constantly growing. It includes signal processing techniques
(Principal Component Analysis, Independent Component Analysis
as well as slow Feature Analysis), manifold methods of learning
([Hessian Locally Linear embedding) as well as a number of
classification methods, probabilistic techniques (Factor Analysis,
RBM), and data pre-processing techniques, and many more.
Data Science
• Some years ago, data was less and mostly available in a structured form,
which could be easily stored in excel sheets, and processed using BI tools.
• But in today's world, data is becoming so vast, i.e., approximately 2.5
quintals bytes of data is generating on every day, which led to data
explosion.
• Now, handling of such huge amount of data is a challenging task for every
organization. So to handle, process, and analysis of this, we required some
complex, powerful, and efficient algorithms and technology, and that
technology came into existence as data Science. Following are some main
reasons for using data science technology:
• With the help of data science technology, we can convert the massive
amount of raw and unstructured data into meaningful insights.
• Data science technology is opting by various companies, whether it is a big
brand or a startup. Google, Amazon, Netflix, etc, which handle the huge
amount of data, are using data science algorithms for better customer
experience.
• Data science is working for automating transportation such as creating a
self-driving car, which is the future of transportation.
• Data science can help in different predictions such as various survey,
elections, flight ticket confirmation, etc.
• One of the main reasons why Python is widely used in the scientific and
research communities is because of its ease of use and simple syntax
which makes it easy to adapt for people who do not have an engineering
background. It is also more suited for quick prototyping.
• Most Commonly used libraries for data science :
• Numpy: Numpy is Python library that provides mathematical function to
handle large dimension array. It provides various method/function for
Array, Metrics, and linear algebra.
NumPy stands for Numerical Python. It provides lots of useful features for
operations on n-arrays and matrices in Python. The library provides
vectorization of mathematical operations on the NumPy array type, which
enhance performance and speeds up the execution. It’s very easy to work
with large multidimensional arrays and matrices using NumPy.
• Pandas: Pandas is one of the most popular Python library for data
manipulation and analysis. Pandas provide useful functions to manipulate
large amount of structured data. Pandas provide easiest method to
perform analysis. It provide large data structures and manipulating
numerical tables and time series data. Pandas is a perfect tool for data
wrangling. Pandas is designed for quick and easy data manipulation,
aggregation, and visualization. There are two data structures in Pandas –
• Series – It Handle and store data in one-dimensional data.
DataFrame – It Handle and store Two dimensional data.
• Matplotlib: Matplotlib is another useful Python library for Data
Visualization. Descriptive analysis and visualizing data is very important for
any organization. Matplotlib provides various method to Visualize data in
more effective way. Matplotlib allows to quickly make line graphs, pie
charts, histograms, and other professional grade figures. Using Matplotlib,
one can customize every aspect of a figure. Matplotlib has interactive
features like zooming and planning and saving the Graph in graphics
format.
• Scipy: Scipy is another popular Python library for data science and
scientific computing. Scipy provides great functionality to scientific
mathematics and computing programming. SciPy contains sub-modules
for optimization, linear algebra, integration, interpolation, special
functions, FFT, signal and image processing, ODE solvers, Statmodel and
other tasks common in science and engineering.
• Scikit – learn: Sklearn is Python library for machine learning. Sklearn
provides various algorithms and functions that are used in machine
learning. Sklearn is built on NumPy, SciPy, and matplotlib. Sklearn provides
easy and simple tools for data mining and data analysis. It provides a set of
common machine learning algorithms to users through a consistent
interface. Scikit-Learn helps to quickly implement popular algorithms on
datasets and solve real-world problems.
• Python Variables
• Variable is a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.
• In Python, we don't need to specify the type of variable because
Python is a infer language and smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but
they have to begin with a letter or an underscore.
• It is recommended to use lowercase letters for the variable name.
Identifier Naming
• Variables are the example of identifiers. An Identifier is used to
identify the literals used in the program. The rules to name an
identifier are given below.
• The first character of the variable must be an alphabet or
underscore ( _ ).
• All the characters except the first character may be an alphabet of
lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9).
• Identifier name must not contain any white-space, or special
character (!, @, #, %, ^, &, *).
• Identifier name must not be similar to any keyword defined in the
language.
• Identifier names are case sensitive; for example, myname, and
MyName is not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
• Python Keywords
• Python Keywords are special reserved words that convey a special
meaning to the compiler/interpreter. Each keyword has a special
meaning and a specific operation. These keywords can't be used as
a variable. Following is the List of Python Keywords.
True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda


Python Comments
• Python Comment is an essential tool for the programmers. Comments are
generally used to explain the code. We can easily understand the code if it has a
proper explanation. A good programmer must use the comments because in the
future anyone wants to modify the code as well as implement the new module;
then, it can be done easily.
• Python provides the single-lined Python comment. To apply the comment in the
code we use the hash(#) at the beginning of the statement or code.
• Let's understand the following example.
• # This is the print statement
• print("Hello Python")
• Here we have written comment over the print statement using the hash(#). It will
not affect our print statement.
# Variable a holds value 5
# Variable b holds value 10
# Variable c holds sum of a and b
# Print the result
a=5
b = 10
c = a+b
print("The sum is:", c)
Docstrings Python Comment
• The docstring comment is mostly used in the module, function,
class or method. It is a documentation Python string. We will
explain the class/method in further tutorials.
• Example:
def intro():
"""
This function prints Hello Joseph
"""
print("Hi Joseph")
intro()
Python indentation
• Python indentation uses to define the block of the code. The other
programming languages such as C, C++, and Java use curly braces {},
whereas Python uses an indentation. Whitespaces are used as
indentation in Python.
• Indentation uses at the beginning of the code and ends with the
unintended line. That same line indentation defines the block of the
code (body of a function, loop, etc.)
• Generally, four whitespaces are used as the indentation. The
amount of indentation depends on user, but it must be consistent
throughout that block.
• Python Data Types
• Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are
given below.
• Python supports three types of numeric data.
• Int - Integer value can be any length such as integers 10, 2, 29, -20, -
150 etc. Python has no restriction on the length of an integer. Its
value belongs to int
• Float - Float is used to store floating-point numbers like 1.9, 9.902,
15.2, etc. It is accurate upto 15 decimal points.
• complex - A complex number contains an ordered pair, i.e., x + iy
where x and y denote the real and imaginary parts, respectively.
The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Numbers
• Number stores numeric values. The integer, float, and complex
values belong to a Python Numbers data-type. Python provides
the type() function to know the data-type of the variable.
• Python creates Number objects when a number is assigned to a
variable. For example;
• a=5
print("The type of a", type(a))
Output- The type of a <class 'int'>

• b = 40.5
print("The type of b", type(b))
Output- The type of b <class 'float'>

• c = 1+3j
print("The type of c", type(c))
Output- The type of c <class 'complex'>
• Sequence Type
String
• The string can be defined as the sequence of characters
represented in the quotation marks. In Python, we can use single,
double, or triple quotes to define a string.
str = "string using double quotes"
print(str)
Output- string using double quotes

As strings are immutable, it cannot be modified.


List
• Python Lists are similar to arrays in C. However, the list can contain
data of different types. The items stored in the list are separated
with a comma (,) and enclosed within square brackets [].
• Consider the following example.
• list1 = [1, "hi", "Python", 2]
print (list1)
Output- [1, 'hi', 'Python', 2]
• Tuple
• A tuple is similar to the list in many ways. Like lists, tuples also
contain the collection of the items of different data types. The
items of the tuple are separated with a comma (,) and enclosed in
parentheses ().
• A tuple is a read-only data structure as we can't modify the size and
value of the items of a tuple.
tup = ("hi", "Python", 2)
print (tup)
Output- ('hi', 'Python', 2)
• Dictionary
• Dictionary is an unordered set of a key-value pair of items. It is like
an associative array or a hash table where each key stores a specific
value. Key can hold any primitive data type, whereas value is an
arbitrary Python object.
• The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
• Consider the following example.
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
print (d)
Output- {1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
• Boolean
• Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false. It
denotes by the class bool. True can be represented by any non-zero
value or 'T' whereas false can be represented by the 0 or 'F'.
Consider the following example.
• # Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
• Set
• Python Set is the unordered collection of the data type. It is
iterable, mutable(can modify after creation), and has unique
elements. In set, the order of the elements is undefined; it may
return the changed sequence of the element. The set is created by
using a built-in function set(), or a sequence of elements is passed
in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.
set2 = {'James', 2, 3,'Python'}
print(set2)
Output- {3, 'Python', 'James', 2}
• File Handling
• The file handling plays an important role when the data needs to be
stored permanently into the file. A file is a named location on disk
to store related information. We can access the stored information
(non-volatile) after the program termination.
• The file-handling implementation is slightly lengthy or complicated
in the other programming language, but it is easier and shorter in
Python.
• In Python, files are treated in two modes as text or binary. The file
may be in the text or binary format, and each line of a file is ended
with the special character.
• Hence, a file operation can be done in the following order.
• Open a file
• Read or write - Performing operation
• Close the file
• Opening a file
• Python provides an open() function that accepts two arguments,
file name and access mode in which the file is accessed. The
function returns a file object which can be used to perform various
operations like reading, writing, etc.
• Syntax:
• file object = open(<file-name>, <access-mode>, <buffering>)
• The files can be accessed using various modes like read, write, or
append. The following are the details about the access mode to
open a file.
SN Access mode Description

1 r It opens the file to read-


only mode. The file
pointer exists at the
beginning. The file is by
default open in this
mode if no access mode
is passed.

2 rb It opens the file to read-


only in binary format.
The file pointer exists at
the beginning of the file.

3 r+ It opens the file to read


and write both. The file
pointer exists at the
beginning of the file.

4 rb+ It opens the file to read


and write both in binary
format. The file pointer
exists at the beginning
of the file.
• The close() method
• Once all the operations are done on the file, we must close it
through our Python script using the close() method. Any unwritten
information gets destroyed once the close() method is called on a
file object.
• We can perform any operation on the file externally using the file
system which is the currently opened in Python; hence it is good
practice to close the file once all the operations are done.
• The syntax to use the close() method is given below.
• Syntax
• fileobject.close()
• Writing the file
• To write some text to a file, we need to open the file using the open
method with one of the following access modes.
• w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.
• a: It will append the existing file. The file pointer is at the end of the
file. It creates a new file if no file exists.
fileptr = open("file2.txt", "w")
fileptr.write(''Python is the modern day language. It makes things so si
mple.’’)
fileptr.close()
Output- Python is the modern-day language. It makes things so
simple.
• Python Blocks
• A block is a piece of Python program text that is executed as a unit. The
following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block.
• Statement : Instructions that a Python interpreter can execute are called
statements.
• Example :
def add(a,b):
#Block
P=’c=a + b’ #statement
Block :
• A Python program is constructed from code blocks.
• A script file (a file given as standard input to the interpreter or specified
as a command line argument to the interpreter) is a code block.
• Statement :
• There are different types of statements in the Python programming
language like Assignment statement, Conditional statement, Looping
statements etc.
• Flow Control
• A program’s control flow is the order in which the program’s code
executes.
• The control flow of a Python program is regulated by conditional
statements, loops, and function calls.
• Python has three types of control structures:
• Sequential - default mode
• Selection - used for decisions and branching
• Repetition - used for looping, i.e., repeating a piece of code
multiple times.
• 1. Sequential
• Sequential statements are a set of statements whose execution
process happens in a sequence. The problem with sequential
statements is that if the logic has broken in any one of the lines,
then the complete source code execution will break.
• Example
a=20
b=10
c=a-b
print("Subtraction is : ",c)
Output- Substraction is 10
• 2. Selection/Decision control statements
• In Python, the selection statements are also known as Decision
control statements or branching statements.
• The selection statement allows a program to test several conditions
and execute instructions based on which condition is true.
• Some Decision Control Statements are:
• Simple if
• if-else
• nested if
• if-elif-else
• Simple if: If statements are control flow statements that help us to
run a particular code, but only when a certain condition is met or
satisfied. A simple if only has one condition to check.

n = 10
if n % 2 == 0:
print("n is an even number")

Output - n is an even number


• if-else: The if-else statement evaluates the condition and will
execute the body of if, if the test condition is True, but if the
condition is False, then the body of else is executed.

n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")

Output- n is odd
• nested if: Nested if statements are an if statement inside another if
statement.
a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")
• Output- c is big
• if-elif-else: The if-elif-else statement is used to conditionally
execute a statement or a block of statements.

x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than
y")

Output - x is greater than y


• 3. Repetition
• A repetition statement is used to repeat a group(block) of
programming instructions.
• In Python, we generally have two loops/repetitive statements:
• for loop
• while loop

• for loop: A for loop is used to iterate over a sequence that is either
a list, tuple, dictionary, or a set. We can execute a set of statements
once for each item in a list, tuple, or dictionary.
lst = [1, 2, 3, 4, 5]
for i in range(len (lst)):
print(lst [i], end = " ")

for j in range(0,10):
print(j, end = " ")

Output
123450123456789
• while loop: In Python, while loops are used to execute a block of
statements repeatedly until a given condition is satisfied. Then, the
expression is checked again and, if it is still true, the body is
executed again. This continues until the expression becomes false.

m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")

Output - 0 1 2 3 4 End
• for loop
• The for loop in Python is used to iterate the statements or a part of
the program several times. It is frequently used to traverse the data
structures like list, tuple, or dictionary.
• The syntax of for loop in python is given below.
• for iterating_var in sequence:
statement(s)
• For loop Using range() function
• The range() function
• The range() function is used to generate the sequence of the
numbers. If we pass the range(10), it will generate the numbers
from 0 to 9. The syntax of the range() function is given below.
• Syntax:
• range(start,stop,step size)
• The start represents the beginning of the iteration.
• The stop represents that the loop will iterate till stop-1.
The range(1,5) will generate numbers 1 to 4 iterations. It is
optional.
• The step size is used to skip the specific numbers from the iteration.
It is optional to use. By default, the step size is 1. It is optional.
• for i in range(10):
print(i,end = ' ')
• Output: - 0 1 2 3 4 5 6 7 8 9
Looping Through a String
• Since strings are arrays, we can loop through the characters in a
string, with a for loop.
• Example
• Loop through the letters in the word "banana":
• for x in "banana":
print(x)
• b
a
n
a
n
a
• Loop Through a List
• You can loop through the list items by using a for loop:
• Example
• Print all items in the list, one by one:
• thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Output-apple
banana
cherry
Loop Through a Dictionary
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of
the dictionary, but there are methods to return the values as well.
• Example
• Print all key names in the dictionary, one by one:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Output - brand
model
year
• Python Pass
• In Python, the pass keyword is used to execute nothing; it means,
when we don't want to execute code, the pass can be used to
execute empty. It is the same as the name refers to. It just makes
the control to pass by without executing any code. If we want to
bypass any code pass statement can be used.
• It is beneficial when a statement is required syntactically, but we
want we don't want to execute or execute it later. The difference
between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not
ignored.
• Suppose we have a loop, and we do not want to execute right this
moment, but we will execute in the future. Here we can use the
pass.
• Example - Pass statement
• # pass is just a placeholder for
for i in [1,2,3,4,5]:
if(i==4):
pass
print("This is pass block",i)
print(i)
• Output:
1
2
3
This is pass block 4
4
5
Python break statement
• The break is a keyword in python which is used to bring the
program control out of the loop. The break statement breaks the
loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. In other words,
we can say that break is used to abort the current execution of the
program and the control goes to the next line after the loop.
• The break is commonly used in the cases where we need to break
the loop for a given condition.
• The syntax of the break is given below.
• #loop statements
• break;
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");
Output- item matched
found at 2 location
continue Statement
• The continue statement in Python is used to bring the program
control to the beginning of the loop. The continue statement skips
the remaining lines of code inside the loop and start with the next
iteration. It is mainly used for a particular condition inside the loop
so that we can skip some specific code for a particular condition.The
continue statement in Python is used to bring the program control
to the beginning of the loop. The continue statement skips the
remaining lines of code inside the loop and start with the next
iteration. It is mainly used for a particular condition inside the loop
so that we can skip some specific code for a particular condition.
• Syntax
#loop statements
continue
#the code to be skipped
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)

Output- 1 2 3 4 6 7 8 9 10

the value 5 is skipped because we have provided the if condition using


with continue statement in while loop. When it matched with the
given condition then control transferred to the beginning of the while
loop and it skipped the value 5 from the code.
• List Operations
my_list = []
print(my_list)
my_list_2 = list()
print(my_list_2)

my_list=[1,2,3,'oops','python']
my_list_2=list([4,5,3.14,'fun', 'joy'])
#print(my_list)
#print(my_list_2)

#Accessing elements of list


my_list = [1, 2, 3, 'oops', 'python']
print(my_list[:])
print(my_list[3])
print((my_list[0:4]))
print(my_list[:: -1])
print(my_list[0:5:2])
print(my_list[3][2])
• #Add operation
my_list.append([555,12])
print(my_list)
print(len(my_list))

my_list_2.extend([555,12])
print(my_list_2)

print(len(my_list_2))
my_list.insert(1,'abc')
print(my_list)
print(my_list + ['just'])
print(my_list * 2)
print(my_list)
• #Delete Element
del my_list_2[3]
print(my_list_2)
my_list_2.remove('joy')
print((my_list_2))
a=my_list_2.pop(2)
print('popped element:', a ,'List Remaining :', my_list_2)
my_list_2.clear()
print(my_list_2)

my_list = [1, 2, 3, 'oops', 'python']


my_list_2 = list([4, 5, 3.14, 'fun', 'joy'])
new = [5, 4, 12, 45, 3]
print(my_list.index('python'))

print(my_list.count('Python'))

print(sorted(new))
print(new)

new.reverse()
print(new)

new_list = my_list.copy()
print(new_list)
• Set Operation
my_set={1, 2, 3, 4, 5, 5, 5,6}
print(my_set)
my_set.add(7)
print(my_set)
my_set1 = {1,2,3,4}
print(my_set1)

my_set2 = {3,4,5,6}
print(my_set2)

print(my_set1.union(my_set2),'------',my_set1 | my_set2)
print(my_set1.intersection(my_set2),'-----',my_set1 & my_set2)
print(my_set1.difference(my_set2),'-----',my_set1 - my_set2)
print(my_set1.symmetric_difference(my_set2),'-----',my_set1 ^ my_set2)

my_set1.clear()
print(my_set1)
Tuple Operation
my_tuple=()
my_tuple_2=tuple()
print(my_tuple)
print(my_tuple_2)
my_tuple=(1, 2, 3)
my_tuple_2 = tuple(('python','is','good'))
print(my_tuple)
print(my_tuple_2)
my_tuple = my_tuple + (4,5,6)
print(my_tuple)
my_tuple_3 = 'language',
print(my_tuple_3)
print(type(my_tuple_3))
#Accessing values
my_tuple=(1,2,3)
my_tuple_2 = ('python','is','good')
my_tuple_3 = (1,2, 3,['hi','Python'])
print(my_tuple[0])
print(my_tuple_2[:])
print(my_tuple_3[3][1])

my_tuple_3[3][0] = 'hello'
print(my_tuple_3)
print(my_tuple_3.count(2))
print(my_tuple_3.index(['hello','Python']))
• String Operation
my_str1 ='Python is oo language'
my_str2 ='python is easy'

print(my_str1)
print(my_str2)
print(my_str1[:])
print(my_str1[2:10])
print(my_str2[0:14:1])
print(my_str1[0:14:2])
print(my_str2[::-1])
print(my_str2[-7:-1])
my_str1 ='Python is oo language'
print(len(my_str1))
print(my_str1.count('t'))
print(my_str1.lower())
print(my_str1.upper())
print(my_str1.find('l'))
print(my_str1.partition('is'))
print(my_str1.split(' '))
print(my_str1.replace('oo','Object Oriented'))
• Dictionary Operation
my_dict = {}
my_dict_2 = dict()
print (my_dict)
print (my_dict_2)

my_dict = { 1:'Python', 2:'Java'}


my_dict_2 =dict({1:'c++',2:'Ruby'})
print(my_dict)
print(my_dict_2)

#Accessing
my_dict = {'First':'Python','Second':'Java'}
print(my_dict['First'])
print(my_dict.get('Second'))

my_dict['Third']='Ruby'
print(my_dict)
a=my_dict.pop('Third')
print("Value" , a)
print(my_dict)
b=my_dict.popitem()
print(("Key, Value pair:", b))
print(my_dict)
my_dict.clear()
print(my_dict)

my_dict = {'First':'Python','Second':'Java'}
print((my_dict.keys()))
print(my_dict.values())
print(my_dict.items())
print(my_dict.get('First'))

You might also like