0% found this document useful (0 votes)
12 views8 pages

Python Applications and Data Types Guide

The document provides a comprehensive overview of Python applications, standard data types, functions, and key programming concepts such as exception handling, file operations, and data structures like lists, tuples, dictionaries, and sets. It also covers advanced topics like lambda functions, recursion, and modules, along with practical examples and explanations of various methods and operators. Additionally, it highlights Python's advantages and its use of regular expressions for string manipulation.

Uploaded by

Komal Pokale
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)
12 views8 pages

Python Applications and Data Types Guide

The document provides a comprehensive overview of Python applications, standard data types, functions, and key programming concepts such as exception handling, file operations, and data structures like lists, tuples, dictionaries, and sets. It also covers advanced topics like lambda functions, recursion, and modules, along with practical examples and explanations of various methods and operators. Additionally, it highlights Python's advantages and its use of regular expressions for string manipulation.

Uploaded by

Komal Pokale
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

**Applications of python :

Web Applications: We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML, XML and JSON, etc. GUI Based Desktop
Applications: Python has simple syntax, modular architecture, rich text processing tools and
the ability to work on multiple operating systems which make it a desirable choice for
developing desktop-based applications Scientific and Numeric Applications: Python is
popular and widely used in scientific and numeric computing. Software Development:
Python is helpful for software development process.
**Standard Data Types :
Numbers: Represents numeric data to perform mathematical operations. Numbers can be
integers (like 1 and 2), floats (like 1.1 and 1.2), fractions (like 1/2 and 2/3), or even complex
numbers. 2. String: Represents text characters, special symbols or alphanumeric data. String
is sequence of Unicode characters. 3. List: Represents sequential data that the programmer
wishes to sort, merge etc. 4. Tuple: Represents sequential data with a little difference from
list. 5. Dictionary: Represents a collection of data that associate a unique key with each
value. 6. Boolean: Represents truth values (true or false). 7. Set: Set is an unordered
collection of unique data items. 8. Dictionary: Dictionary is an unordered collection of key-
value pairs.
**Comments • Comment writing is a good programming practice. Comments are non-
executable chunks of line in a program. • Comments are meant for computer programmers
for better understanding a program. Python interpreter ignores the comment in the
program.
**Identifiers • A Python identifier is a name given to a function, class, variable, module or
other objects that is used in Python program.
**Dry Run • A dry run is the process of a programmer manually working through their
code to trace the value of variables. • Dry run is a manual way of testing for a process or
algorithms for its correctness and functionality.
**Type Conversion ;
-Implicit Type Conversion: • Implicit type conversion: In this Python automatically converts
one data type to another data type. This process doesn't need any user involvement.
-Explicit Type Conversion: • In explicit type conversion users convert the data type of an
object to required data type. • We use the predefined functions like int(), float(), str(), etc to
perform explicit type conversion.
**Operators Precedence and Associativity :
*Operator Precedence: • When an expression has two or more operators, we need to
identity the correct sequence to evaluate these operators. This is because the final answer
changes depending on the sequence thus chosen
*Associativity of Pythons Operators: • When two operators have the same precedence,
associativity helps to determine which the order of operations. • Associativity decides the
order in which the operators with same precedence are executed. • There are two types of
**LISTS
• A Python list is a mutable sequence of data values called items or elements. An item can
be of any type. • List is one of the most frequently used and very versatile data type used in
Python. The elements in the list are stored in a linear order one after other. • A list is a
collection of items or elements; the sequence of data in a list is ordered. • The elements or
items in a list can be accessed by their positions i.e. indices. The index in lists always starts
with 0 and ends with n-1, if the list contains n elements.
Slicing: • Slicing is an operation that allows us to extract elements from units. The slicing
feature used by Python to obtain a specific subset or element of the data structure using the
colon (:) operator.
**FUNCTIONS • A function is a block of organized, reusable code that is used to perform a
single, related action/operation. Python has excellent support for functions. • A function can
be defined as the organized block of reusable code which can be called whenever required.
A function is a piece of code that performs a particular task.
**Anonymous Functions
• Anonymous functions are the functions that are not bond to name. It means anonymous
function does not has a name. • While normal functions are defined using the def keyword,
in Python anonymous functions are defined using the lambda keyword. Hence, anonymous
functions are also called Lambda Functions.
Recursion
• Recursion is a way of programming or coding a problem, in which a function calls itself
one or more times in its body. • Recursion is a method of programming or coding a problem,
in which a function calls itself one or more times in its body. • Usually, it is returning the
return value of this function call. If a function definition satisfies the condition of recursion,
we call this function a recursive function.
**Lambda
• A lambda function is a small anonymous function. A lambda function can take any number
of arguments, but can only have one expression. • Python offers the lambda form as a way
to simplify using higher-order functions. A lambda form allows us to define a small,
anonymous function. The function's body is limited to a single expression.
**TUPLES :
• A tuple is a collection of objects which ordered and immutable. • A Python tuple is a
sequence of data values called as items or elements. • A tuple is a collection of items which
is ordered and unchangeable. • A tuple is a data structure that is an immutable or
unchangeable, ordered sequence of elements/items. Because tuples are immutable, their
values cannot be modified. • A tuple is a heterogeneous data structure and used for
grouping data. Each element or value that is inside of a tuple is called an item. • In Python
tuples are written with round brackets ( ) and values in tuples can also be accessed by their
index values, which are integers starting from 0.
**DIFFEENCE BETWEEN STRING, TOUPLE, LIST :
Immutable (Value cannot be modified) Mutable (values can be modified)
Strings str="hi" Tuples tuples=(5,4.0,'a') List list=[5,4.0','a']
Sequence Unicode character. Ordered sequence. Order sequence.
Values cannot be modified. Same as list but it is faster than Value can be changed
list because it is immutable. dynamically.
It is a sequence of character. Values stored in alpha numeric. Values stored in alpha numeric.
Access values from string. Access values from tuples. Access values from list.
Adding values in not possible. Adding values is not possible. Adding values is possible.
Removing values is not possible. Removing values is not possible. Removing values is possible.
*DICTIONARIES
• The dictionary data structure is used to store key value pairs indexed by keys. A dictionary
is an associative data structure, means that elements/items are stored in a non linear
fashion. • Python dictionary is an unordered collection of items or elements. Items stored in
a dictionary are not kept in any particular order. • The simplest method to create dictionary
is to simply assign the pair of key:values to the dictionary using operator (=).
**SETS
A set is an unordered collection of items. Every element is unique (no duplicates) and must
be immutable (which cannot be change. • A set data structure in python programming
includes an unordered collection of items without duplicates. Sets are unindexed that means
we cannot access set items by referring to an index.
*MODULES •
Modules are primarily the (.py) files which contain Python programming code defining
functions, class, variables, etc. with a suffix .py appended in its file name. A file containing
.py python code is called a module. • A module is a collection of Python objects such as
functions, classes, and so on. Python interpreter is bundled with a standard library
consisting of large number of built-in modules, • Built-in modules are generally written in C
and bundled with Python interpreter in precompiled form. A built-in module may be a
Python script (with .py extension) containing useful utilities. Following are the modules
which are classified as numeric and mathematical modules: numbers ,math, cmath ,
decimal, fractions ,random ,statistics .
**PACKAGES :
• A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and subsubpackages and so on. •
Packages allow for a hierarchical structuring of the module namespace using dot notation.
Packages are a way of structuring many packages and modules which help in a well-
organized hierarchy of data set, making the directories and modules easy to access. • A
package is a collection of Python modules, i.e., a package is a directory of Python modules
containing an additional _ _init_ _.py file (For example: Phone/_ _init_ _.py).
**FILES :
• File is a named location on disk to store related information. It is used to permanently
store data in a non-volatile memory (e.g. hard disk). • To read from or write to a file, we
must first open it when we are done with it, we should close it to free up the resources it
holds. • Python has several functions for file handling to perform operations like creating,
reading, updating, and deleting [Link] are divided into following two categories: 1. Text
Files: Text files are simple texts in human readable format. A text file is structured as
sequence of lines of text. 2. BinaryFiles: Binary files have binary data (0s and 1s) which is
understood by the computer.
*Write a short note on exception handling.
Exception handling in Python is done using the try, except, else, and finally blocks. It allows
programmers to handle errors gracefully and execute code under specific conditions. try:
result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") else:
print("Division successful.") finally:
print("Execution finished.")
*Which methods are used to read from a file?
The following methods can be used to read from a file:
read(): Reads the entire content of the file.
with open('[Link]', 'r') as file: content =
[Link]()
readline(): Reads a single line from the file. with
open('[Link]', 'r') as file:
line = [Link]() # Reads the first line
readlines(): Reads all the lines and returns them as a list.
with open('[Link]', 'r') as file:
lines = [Link]() # Reads all lines into a list
*dictionary methods copy(), gets(), items(), and keys()?
copy(): Creates a shallow copy of the dictionary.
dict1 = {'a': 1, 'b': 2} dict2 = [Link]()
get(key, default): Returns the value for key if it exists in the dictionary; otherwise, returns
default. value = [Link]('c', 'Not Found') # Returns 'Not Found'
items(): Returns a view object that displays a list of a dictionary's key-value tuple pairs.
items = [Link]() # Returns a view of (key, value) pairs
keys(): Returns a view object that displays a list of all the keys in the dictionary. keys =
[Link]() # Returns the keys of the dictionary.
* zip(), tuple(), count(), and index() functions?
zip(): Combines two or more iterables (like lists or tuples) into a tuple of tuples.
tuple(): Converts an iterable (like a list) into a tuple.
count(): Returns the number of times a specified value appears in the tuple.
index(): Returns the first index of a specified value. Raises ValueError if the value is not
found.
*Metacharacters in Regular Expressions:
. (Dot): Matches any single character except a newline.
* (Asterisk): Matches zero or more repetitions of the preceding element.
*Built-in List Functions:
len(list): Returns the number of elements in the list.
append(element): Adds an element to the end of the list.
*Backward Indexing in Strings:
Access characters in a string from the end using negative indices.
string[-1] refers to the last character, string[-2] to the second-to-last, and so on.

* Demonstrate list slicing :


my_list = [10, 20, 30, 40, 50]
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[:3])# Output: [10, 20, 30]
print(my_list[2:])# Output: [30, 40, 50]
print(my_list[-2:]) # Output: [40, 50]
*Explain union and intersection with example.
Union: Combines elements from both sets, removing duplicates.
set1 = {1, 2, 3} set2 = {3, 4, 5}
union_set = [Link](set2) # {1, 2, 3, 4, 5}
Intersection: Returns a set containing elements present in both sets.
set1 = {1, 2, 3} set2 = {2, 3, 4} intersection_set = [Link](set2) # {2, 3}.
*What is the use of seek() and tell() functions?
seek(offset, whence): Changes the file position to a specified byte. tell(): Returns the current
position of the file cursor.
*range() function and its parameters.:
The range() function generates a sequence of numbers. It can take one, two, or three
parameters: range(stop): Generates numbers from 0 to stop - 1. range(start, stop):
Generates numbers from start to stop - 1. range(start, stop, step): Generates numbers from
start to stop - 1, incrementing by step.
*void function in Python?
A void function is a function that does not return any value. It is defined using the def
keyword followed by the function name. You can use the return statement without a value
or omit it entirely def print_message(): print("This is a void function").
*between pop() and del in list?
pop(index) removes and returns the element at the specified index. If no index is specified, it
removes and returns the last element. del is used to delete an element at a specified index
but does not return it.
*syntax for handling exceptions ;
try: # Code that may raise an exception
except SomeException: # Code to handle the exception
else: # Code to execute if no exception occurs
finally: # Code that will always execute
*advantages of Python?
Easy to Learn and Use Extensive, Libraries and Frameworks ,Cross-Platform Compatibility
,Strong Community Support, Versatility.
*What is RegEx? Give an example
Regular Expressions (RegEx) are sequences of characters that form search patterns, used for
string searching and manipulation.
import re
pattern = r'\d+' # Matches one or more digits result = [Link](pattern, 'There are 2 cats
and 3 dogs.') print(result) # Output: ['2', '3']
*user-defined module?
● A user-defined module is a Python file (with a .py extension) that contains functions,
classes, or variables that can be imported and used in other Python files.
# my_module.py def greet(name):
return f"Hello, {name}!"
*What is dry run in Python?
A dry run is the manual process of stepping through the code to understand its logic
without executing it on a computer. This helps in identifying logical errors and
understanding flow.
*What is a lambda function? Give an example.
A lambda function is an anonymous function defined using the lambda keyword. It can take
any number of arguments but can only have one expression.
add = lambda x, y: x + y print(add(3, 5)) # Otput: 8.
*What is indentation?
Indentation in Python refers to the use of spaces or tabs to define the structure and flow of
the code. It indicates a block of code belonging to a specific control structure (like loops,
functions, classes). Proper indentation is crucial as it determines the grouping of statements.
*What is a slice operator?
The slice operator (:) is used to retrieve a subset of elements from a sequence (like lists,
tuples, or strings). It allows you to specify a start index, an end index, and an optional step.
*variable-length argument?
Variable-length arguments allow a function to accept an arbitrary number of arguments. In
Python, this can be done using *args (for positional arguments) and **kwargs (for keyword
arguments).
*What is wb mode in file?
the wb mode opens a file for writing in binary format. If the file does not exist, it creates a
new file. If the file exists, it truncates the file to zero length.
*append() Method: • The append() method adds an element to the end of a list. We
can insert a single item in the list data time with the append().
*extend() Method: • The extend() method extends a list by appending items. We can
add several items using extend() method.
*insert() Method: • We can insert one single item at a desired location by using the
method insert() or insert multiple items by squeezing it into an empty slice of a list.
*+ Operator: • The concatenation operation in Python programming is used to
combine the elements/items or two lists. We use + operator to combine two lists.
* Operator: • Sometimes, there is a need or requirement to repeat all the items of the
lists as specific number of times. The * operator repeats a list for the given number of
times.
*pop() Method: • The pop() method in Python is used to remove a particular
item/element from the given index in the list. • The pop() method removes and
returns the last item if index is not provided. This helps us implement lists as stack
data structure.
*remove() Method: • The remove() method in Python is used to remove a particular
element from the list. • We use the remove() method if we know the item that we
want to remove or delete from the list (but not the index).
*open() Function: • The open() function creates a file object which is called "handle".
This would be utilized to call other support methods associated with it. Syntax:
file_object = open(filename [, access_mode][, buffering])
*close() Function: • The close() function of a file object flushes any unwritten
information and closes the file object It is a good practice to use the close() function to
close a file. Syntax: [Link]().
*read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file. Syntax: File_object.read([n]).
*readline(): Reads a line of the file and returns in form of a string. For specified n,
reads at most n bytes.. Syntax: File_object.readline([n]).
*readlines(): Reads all the lines and return them as each line a string element in a list.
Syntax: file_object.readlines().
*[Link](path): Return True if path is an existing regular file.
*[Link](path): Returns True if path is an existing directory.
* [Link](path): Returns True if path refers to a directory entry that is a symbolic
link.
*popen() Method: • This method creates a pipe to or from the command. It returns an
open file object which connects to a pipe.
*system() Method: • It is the most common way of running any system command.
*copy() Method: • The copy() method is like the "cp" command in Unix. It means if the
target is a folder, then it’ll create a new file inside it with the same name (basename)
as the source file. Syntax: [Link](source, destination).
*Copyfileobj() Method: • This method copies the file to a target path or file object. If
the target is a file object, then you need to close it explicitly after the calling the
Copyfileobj().
*The index() method returns the lowest index of the substring if found in the string. If
the substring is not found, it raises a ValueError.
*The range() function generates a sequence of numbers. It can take one, two, or three
parameters:
*enumerate(). The enumerate() function adds a counter to an iterable and returns it as
an enumerate object, which can be converted into a list of tuples.

You might also like