R23 Python Unit-2
R23 Python Unit-2
CourseObjectives:
Themainobjectivesofthecourseareto
• IntroducecoreprogrammingconceptsofPythonprogramminglanguage.
• DemonstrateaboutPythondatastructureslikeLists,Tuples,Setsanddictionaries
• ImplementFunctions, ModulesandRegularExpressionsinPython Programming
andtocreatepracticalandcontemporaryapplicationsusingthese
UNTI-I:
HistoryofPythonProgrammingLanguage,ThrustAreasofPython,InstallingAnacondaPython
Distribution, Installing and Using Jupyter Notebook.
SampleExperiments:
1. WriteaprogramtofindthelargestelementamongthreeNumbers.
2. WriteaProgramtodisplayallprimenumberswithinaninterval
3. Writeaprogramtoswaptwonumberswithoutusingatemporaryvariable.
4. DemonstratethefollowingOperatorsinPythonwithsuitableexamples.
i)ArithmeticOperatorsii)RelationalOperatorsiii)AssignmentOperatorsiv)
LogicalOperatorsv) BitwiseOperatorsvi)TernaryOperatorvii) Membership
Operatorsviii)IdentityOperators
5. Writeaprogramtoaddandmultiplycomplexnumbers
6. Writeaprogramtoprintmultiplicationtableofagivennumber.
UNIT-II:
Functions:Built-InFunctions,CommonlyUsedModules,FunctionDefinitionandCalling the
function, return Statement and void Function, Scope and Lifetime of Variables, Default
Parameters, Keyword Arguments, *args and **kwargs, Command Line Arguments.
31
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In
FunctionsUsed on Lists, List Methods, del Statement.
SampleExperiments:
UNIT-III:
TuplesandSets:CreatingTuples,BasicTupleOperations,tuple()Function,Indexingand
SlicinginTuples,Built-InFunctionsUsedonTuples,RelationbetweenTuplesandLists,
RelationbetweenTuplesand Dictionaries,Usingzip()Function,Sets, SetMethods,
Frozenset.
SampleExperiments:
7.
Write a program to create tuples (name, age, address, college) for at least two members
and concatenate the tuples and print the concatenated tuples.
8. Writeaprogramtocountthenumberofvowelsinastring(Nocontrolflowallowed).
9. Writeaprogramtocheckifagivenkeyexistsinadictionaryornot.
10. Writeaprogramtoaddanewkey-valuepairtoanexistingdictionary.
11. Writeaprogramtosumalltheitemsinagivendictionary.
UNIT-IV:
Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write Data,
ReadingandWritingBinaryFiles,PickleModule,ReadingandWritingCSVFiles,Python os and
os.path Modules.
Object-OrientedProgramming:ClassesandObjects,CreatingClassesinPython,Creating
ObjectsinPython,ConstructorMethod,ClasseswithMultipleObjects,ClassAttributesVs Data
Attributes, Encapsulation, Inheritance,Polymorphism.
40
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
Introduction to Data Science: Functional Programming, JSON and XML in Python, NumPywith
Python, Pandas.
SampleExperiments:
1. PythonprogramtocheckwhetheraJSONstringcontainscomplexobjectornot.
2. PythonProgramtodemonstrateNumPyarrayscreationusingarray()function.
3. Pythonprogramtodemonstrateuseofndim,shape,size,dtype.
4. Pythonprogramtodemonstratebasicslicing,integerandBooleanindexing.
5. Pythonprogramtofindmin,max,sum,cumulativesumofarray
6. Create a dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame
and explore the data through the data frame as follows:
a) Applyhead()functiontothepandasdataframe
b) PerformvariousdataselectionoperationsonDataFrame
7. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib
ReferenceBooks:
1. GowrishankarS,VeenaA.,IntroductiontoPythonProgramming,CRCPress.
2. Python Programming,S Sridhar,J Indumathi,V M Hariharan,2nd Edition, Pearson, 2024
3. IntroductiontoProgrammingUsingPython,Y.DanielLiang,Pearson.
OnlineLearningResources/VirtualLabs:
1. https://www.coursera.org/learn/python-for-applied-data-science-
aihttps://www.coursera.org/learn/python?specialization=python#syllabus
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
n Python, you can define a function that returns multiple values by returning them as a tuple, list,
or other data structures. Here's an example of how you can define a function that returns multiple
values using a tuple:
Example:
def calculate_stats(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count if count != 0 else 0
return total, count, average
# Example usage:
numbers = [10, 20, 30, 40, 50]
total, count, average = calculate_stats(numbers)
print(f"Total: {total}")
print(f"Count: {count}")
print(f"Average: {average}")
Explanation:
makefile
Copy
Total: 150
Count: 5
Average: 30.0
In Python, you can define a function with default arguments by assigning default values to the
parameters in the function definition. If the caller does not provide a value for that parameter, the
default value will be used.
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
Example:
# Example usage:
greet() # Uses default values
greet("Alice") # Uses default message but provides a name
greet("Bob", "Good to see you!") # Provides both name and message
Explanation:
The function greet has two parameters: name and message, both of which have default
values.
o name="Guest": Default name is "Guest".
o message="Welcome to the program!": Default message is "Welcome to the
program!".
If you call greet() without any arguments, it will use the default values.
If you call greet("Alice"), it will use the default message, but the name will be overridden
with "Alice".
If you call greet("Bob", "Good to see you!"), both arguments are provided, so the
defaults are ignored.
Output:
css
Copy
Hello, Guest! Welcome to the program!
Hello, Alice! Welcome to the program!
Hello, Bob! Good to see you!
3. Write a program to find the length of the string without using any
library functions
To find the length of a string without using any library functions, you can iterate through each
character in the string and count the number of characters manually. Here's an example of how
you can do that:
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
Example:
def string_length(s):
length = 0
for char in s:
length += 1
return length
# Example usage:
string = "Hello, World!"
print(f"The length of the string is: {string_length(string)}")
Explanation:
Output:
csharp
Copy
The length of the string is: 13
This way, you manually count the number of characters in the string. Let me know if you need
any other details or examples!
You can check if a substring is present in a given string by manually iterating over the main
string and comparing slices of it with the substring. Here's an example of how you can do this:
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
Example:
# Example usage:
main_string = "Hello, welcome to the world of Python!"
substring = "welcome"
if is_substring_present(main_string, substring):
print(f"The substring '{substring}' is present in the string.")
else:
print(f"The substring '{substring}' is not present in the string.")
Explanation:
The function is_substring_present loops through the main_string from the beginning
up to the point where the remaining characters are enough to compare with the substring.
It compares slices of the main string with the substring.
If a match is found, it returns True. If no match is found after checking all possible slices, it
returns False.
Output:
csharp
Copy
The substring 'welcome' is present in the string.
This approach allows you to manually check for a substring's presence without using built-in
functions like in. Let me know if you'd like further clarification!
Here's a Python program that demonstrates how to perform addition, insertion, and slicing
operations on a list:
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
# Example usage:
# i. Addition
elements_to_add = [6, 7, 8]
print("List after addition:", add_elements(my_list, elements_to_add))
# ii. Insertion
position_to_insert = 2
element_to_insert = 9
print("List after insertion:", insert_element(my_list, position_to_insert,
element_to_insert))
# iii. Slicing
start_index = 1
end_index = 5
print("Sliced list:", slice_list(my_list, start_index, end_index))
Explanation:
3. Slicing:
o The slice_list function returns a slice of the list, starting from the start index and
ending at the end index (exclusive).
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA
Example Output:
Addition: The elements [6, 7, 8] are added to the end of the list.
Insertion: The element 9 is inserted at position 2, so the list becomes [1, 2, 3, 9, 4, 5,
6, 7, 8].
Slicing: The slice from index 1 to 5 gives [2, 3, 9, 4].
# Display results
print(f"Original List: {my_list}")
print(f"Length of the list: {length}")
print(f"Sorted List: {sorted_list}")
print(f"Sum of elements: {list_sum}")
print(f"Maximum value in the list: {max_value}")
print(f"Count of element '5' in the list: {count_of_fives}")
Example Output:
Summary:
41