0% found this document useful (0 votes)
44 views22 pages

CS Practical Shubhang Shrivats

The document discusses string data types and operations in Python. It provides examples of defining strings, using string operators like concatenation and membership, and built-in string functions like isalpha(), lower(), upper(), etc. It then summarizes lists, tuples, dictionaries and the bubble sort algorithm in Python.
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)
44 views22 pages

CS Practical Shubhang Shrivats

The document discusses string data types and operations in Python. It provides examples of defining strings, using string operators like concatenation and membership, and built-in string functions like isalpha(), lower(), upper(), etc. It then summarizes lists, tuples, dictionaries and the bubble sort algorithm in Python.
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
You are on page 1/ 22

1

Acknowledgement
Firstly, I would like to thank our computer science
teacher, because he always supported and guided us
while doing this project. He very well cleared all
the doubts I had regarding this project. Also, I
would like to especially thank my parents and
friends who helped me a lot to complete this
project.

The journey of making this project has been


beautiful, as well as knowledgeable for me and I
have learned a lot from it.
3
String In
Python

A string is generally considered as a data type and is often


implemented as an array data structure of bytes (or words) that
stores a sequence of elements, typically characters, using some
character encoding.For example, "hello" is a string containing a
sequence of characters 'h', 'e', 'l', 'l', and 'o'.
Example:-

Output:-

Introduction to String Operators in Python


• Concatenate operator: “+.” :- Two strings can be
concatenated or join using the “+” operator in python.
• String repetition operator: “*.” :- The same string can
be repeated in python by n times using string*n.
• Membership operator: “in” & “not in” :- Membership
operator is used to searching whether the specific character is
part/member of a given input python string.
• Escape sequence operator: “\.” :- To insert a non-allowed
character in the given input string, an escape character is used. An
escape character is a “\” or “backslash” operator followed by a
non-allowed character. An example of a non-allowed character in
python string is inserting double quotes in the string surrounded by
double-quotes.
4

Functions In
String

isalpha() :-Python String isalpha() function returns True if all the


characters in the string are alphabets, otherwise False.
isdigit() :- used to check if string is in
digit.
lower() :- always converts string to lower
case.
islower() :- check if the string is in lower
case.
upper() :- it converts all characters to
upper case.
isupper() :- check if all characters is in
uppercase.
l strip() :- remove extra gap from LHS.
r strip() :-remove extra gap from RHS.
istitle() :- converts every sentence 1st word letter in capital letter.
join() :- it returns a string in which the string element have joint
by string seperator.
swapcase :- it converts lower into uppercase and vice-versa.
partition() :- divide strings into
3 parts.
and():- it gives ASCII code for
string.
len() :- it checks characters in
string.
5

List In Python

A list is a data type that allows you to store various types data in
it. List is a compound data type which means you can have
different-2 data types under a list, for example we can have
integer, float and string items in a same list.

Create a List
We create a list by placing elements inside [], separated by

commas. For example,


Here, we have created a list named ages with 3 integer items.

Access List Elements


In Python, lists are ordered and each item in a list is associated
with a number. The number is known as a list index.
The index of the first element is 0, second element is 1 and so on.

For example,
In the above example, we have created a list named languages.

Here, we can see each list item is associated with the index
number. And we have used the index number to access the items.
6

Negative Indexing in Python


Python allows negative indexing for its sequences. The index of -1
refers to the last item, -2 to the second last item and so on.
7

Functions of List

cmp(list1, list 2) :- It compares two list.


len(list 1) :- No. of elements in list.
max(list1) :- it returns max. value in numeric
form.
min(list) :- it returns min. of all numeric
values.
sum(list) :- it returns the sum of all numeric
values.
append(item) :- add an item to the end of the
list.
insert(index item) :- it insert the item in given
index.
sort() :- it sorts in ascending order by default.
remove (item) :- removes item present at the given index
reverse() :- it reverse the list.
index(item) :- it returns the index of given element.
8
Tuple In Python

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Creating a Tuple
A tuple is created by placing all the items (elements) inside
parentheses (), separated by commas. The parentheses are
optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of

different types (integer, float, list, string, etc.).


Output:-

In the above example, we have created different types of tuples


and stored different data items inside them.
9

As mentioned earlier, we can also create tuples without using parentheses:


10
Functions of Tuple

len() :-This function returns the number of elements present in a


tuple. Moreover, it is necessary to provide a tuple to the len()
function.
count() :- This function will help us to fund the number of times
an element is present in the tuple. Furthermore, we have to
mention the element whose count we need to find, inside the count
function.
index() :- The tuple index() method helps us to find the index or
occurrence of an element in a tuple. This function basically
performs two functions:
• Giving the first occurrence of an element in the tuple.
• Raising an exception if the element mentioned is not found in
the tuple.
• sorted() :- This method takes a tuple as an input and returns a
sorted list as an output. Moreover, it does not make any changes
to the original tuple. min() :-gives the smallest element in the
tuple as an output.
max() :- gives the largest element in the tuple as an output.
sum() :- gives the sum of the elements present in the tuple as an output.

Advantages of Tuple over List in Python


Since tuples are quite similar to lists, both of them are used in
similar situations.
However, there are certain advantages of implementing a tuple over a list:

• We generally use tuples for heterogeneous (different) data types


and lists for homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than
with a list. So there is a slight performance boost.
• Tuples that contain immutable elements can be used as a
key for a dictionary. With lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will
guarantee that it remains write-protected.
11
Dictionary In Python

Dictionaries are used to store data values in key:value pairs.


A dictionary is a collection which is ordered*, changeable and do
not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6
and earlier, dictionaries are unordered.

Create a Dictionary
We create a dictionary by placing key-value pairs inside curly

brackets {}, separated by commas. For example,


Output:-

The country_capitals dictionary has three elements (key-value pairs).


12
Functions of Dictionary

pop() :- Remove the item with the


specified key.
update() :- Add or change dictionary
items. clear() :- Remove all the items from
the dictionary.
keys() :- Returns all the dictionary's keys.
values() :- Returns all the dictionary's
values.
get() :- Returns the value of the specified
key.
popitem():- Returns the last inserted key and value as a tuple.
copy() :- Returns a copy of the dictionary.
13
Bubble Sort

The bubble sort uses a straightforward logic that works by


repeating swapping the adjacent elements if they are not in the
right order. It compares one pair at a time and swaps if the first
element is greater than the second element; otherwise, move
further to the next pair of elements for comparison.

What Does a Bubble Sort Look Like?


If a programmer or analyst wanted to arrange a series of numbers
in ascending order, the bubble sort approach would look like the
example pictured here.
The algorithm would review two items at a time, rearrange those
not already in ascending order from left to right, and then

continue to cycle through the entire sequence until it completed a


pass without switching any numbers.

Implementation in Python Code


14
Program :-
15

Output:-
Explanation:
In the above code, we have defined a bubble_sort() function which
takes list1 as an argument.

• Insidethe function, we have defined two for loop - first for loop
iterates the complete list and the second for loop iterates the list
and the compare the two elements in every outer loop iterations.
• The for loop will be terminated when it reaches at the end.
• We have defined the condition in the inner for loop; if a first
index value is greater than the second index value, swap their
positions with each other.
• We called the function and passed a list; it iterated and returned
the sorted list.

Bubble Sort Applications


Bubble sort is used if
• complexity does not matter
• short and simple code is preferred
16
Functions In Python
Functions are the basic building block of any Python program,
defined as the organized block of reusable code, which can be
called whenever required.
A function is used to carry out a specific task. The function might
require multiple inputs. When the task is done executing, the
function can or can not return one or more values.

• User-Defined Functions - these types of functions are


defined by the user to perform any specific task
• Built-in Functions - These are pre-defined functions in python.

-Built-in Functions
Built-in functions are already defined in python. A user has to
remember the name and parameters of a particular function. Since
these functions are
pre-defined, there is no need to define them again.
Some of the widely used built-in functions are

given below: Example:-


Output:-

Some of the widely used python built-in functions are:

Functions Description

len() Returns the length of a python object.


max() Returns the largest item in a python iterable
min() Returns the largest item in a python iterable
17
sum() Sum() in Python returns the sum of all the items
in an iterator
type() The type() in Python returns the type of a
python object

format() Formats a specified value


input() Allows the user to give input

Types of Parameters used in Functions


• Default Arguments :- A default argument is a parameter that
assumes a default value if a value is not provided in the function
call for that argument.
• Positional Argument :- The argument passed to a
function in correct positional order.
• Keyword Argument :- The idea is to allow the caller to specify
the argument name with values so that the caller does not need to
remember the order of parameters.
• Variable Length Argument :- As the name suggests in certain
situations we can pass variable no. of argument in a function.
18
Exception Handling in Python

Exception handling allows you to separate error-handling code


from normal code. An exception is a Python object which
represents an error. As with code comments, exceptions helps you
to remind yourself of what the program expects. It clarifies the
code and enhances readability.

Different types of exceptions in python:


In Python, there are several built-in exceptions that can be
raised when an error occurs during the execution of a program.
Here are some of the most common types of exceptions in
Python:

• SyntaxError: This exception is raised when the interpreter


encounters a syntax error in the code, such as a misspelled
keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or
function is applied to an object of the wrong type, such as adding
a string to an integer.
• NameError: This exception is raised when a variable or function
name is not found in the current scope.
• IndexError: This exception is raised when an index is out of
range for a list, tuple, or other sequence types.
• KeyError: This exception is raised when a key is not found in a
dictionary.
• ValueError: This exception is raised when a function or
method is called with an invalid argument or input, such as
trying to convert a string to an integer when the string does not
represent a valid integer.
• AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a non-
existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as
reading or writing a file, fails due to an input/output error.
19
• ZeroDivisionError: This exception is raised when an
attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement
fails to find or load a module.
20

Advantages of Exception Handling:


• Improved program reliability: By handling exceptions
properly, you can prevent your program from crashing or
producing incorrect results due to unexpected errors or input.

• Simplifiederror handling: Exception handling allows you to


separate error handling code from the main program logic,
making it easier to read and maintain your code.

• Cleanercode: With exception handling, you can avoid using


complex conditional statements to check for errors, leading
to cleaner and more readable code.

• Easierdebugging: When an exception is raised, the Python


interpreter prints a traceback that shows the exact location where
the exception occurred, making it easier to debug your code.
21
File Handling In Python

File handling is an integral part of programming. File handling in


Python is simplified with built-in methods, which include creating,
opening, and closing files.

While files are open, Python additionally allows performing


various file operations, such as reading, writing, and appending
information.

Modes Behaviour
r, r+, w+, a+, x+ Read
r+, w, w+, a, a+, Write
x+
w, w+, a, a+, x, Create
x+
r, r+, w, w+, x, x+ Pointer Position Start
a, a+ Pointer Position End
w, w+ Truncate (clear contents)
r, r+ Must Exist
x, x+ Must Not Exist

Read from a file


1) read() :- it is used to read the entire data from file.
2) read(n) :- it is used to read n characters from the file.
3) read line() :- it is used to read one line from the fil.
4) read lines() :- it is used to real all lines from the file into a list.
22
Advantages of File Handling

• Versatility: File handling in Python allows you to perform a


wide range of operations, such as creating, reading, writing,
appending, renaming, and deleting files.
• Flexibility: File handling in Python is highly flexible, as it
allows you to work with different file types (e.g. text files, binary
files, CSV files, etc.), and to perform different operations on files
(e.g. read, write, append, etc.).
• User–friendly: Python provides a user-friendly interface for
file handling, making it easy to create, read, and manipulate
files.
• Cross-platform: Python file-handling functions work across
different platforms (e.g. Windows, Mac, Linux), allowing for
seamless integration and compatibility.

Disadvantages of File Handling


• Error-prone: File handling operations in Python can be prone
to errors, especially if the code is not carefully written or if there
are issues with the file system (e.g. file permissions, file locks,
etc.).
• Security risks: File handling in Python can also pose
security risks, especially if the program accepts user input that
can be used to access or modify sensitive files on the system.
• Complexity: File handling in Python can be complex, especially
when working with more advanced file formats or operations.
Careful attention must be paid to the code to ensure that files are
handled properly and securely.
• Performance: File handling operations in Python can be
slower than other programming languages, especially when
dealing with large files or performing complex operations.

You might also like