0% found this document useful (0 votes)
115 views10 pages

R23 Python Unit-2

The document outlines the course structure and syllabus for a Python Programming Lab as part of the Electrical and Electronics Engineering curriculum at Jawaharlal Nehru Technological University Kakinada. It covers core programming concepts, data structures, functions, file handling, and object-oriented programming, along with practical experiments and sample programs. Additionally, it includes references and online resources for further learning.

Uploaded by

raam
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)
115 views10 pages

R23 Python Unit-2

The document outlines the course structure and syllabus for a Python Programming Lab as part of the Electrical and Electronics Engineering curriculum at Jawaharlal Nehru Technological University Kakinada. It covers core programming concepts, data structures, functions, file handling, and object-oriented programming, along with practical experiments and sample programs. Additionally, it includes references and online resources for further learning.

Uploaded by

raam
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/ 10

JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL ANDELECTRONICS ENGINEERING (R23-
IIndYEARCOURSESTRUCTURE&SYLLABU
SKILLENHANCEMENTCOURSE:PYTHONPROGRAMMINGLAB

CourseObjectives:

Themainobjectivesofthecourseareto

• IntroducecoreprogrammingconceptsofPythonprogramminglanguage.
• DemonstrateaboutPythondatastructureslikeLists,Tuples,Setsanddictionaries
• ImplementFunctions, ModulesandRegularExpressionsinPython Programming
andtocreatepracticalandcontemporaryapplicationsusingthese
UNTI-I:

HistoryofPythonProgrammingLanguage,ThrustAreasofPython,InstallingAnacondaPython
Distribution, Installing and Using Jupyter Notebook.

Parts of Python Programming Language: Identifiers, Keywords, Statements and


Expressions,Variables,Operators,PrecedenceandAssociativity,DataTypes,Indentation,Comments,
ReadingInput,PrintOutput, TypeConversions,thetype()Functionand IsOperator,
DynamicandStronglyTypedLanguage.

Control Flow Statements: if statement, if-else statement, if...elif…else, Nested if statement,


while Loop, for Loop, continue and break Statements, Catching Exceptions Using try andexcept
Statement.

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

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
Strings:CreatingandStoring YEARStrings,BasicStringOperations,Accessing
COURSE STRUCTURE & SYLLABUS) Charactersin
StringbyIndexNumber,StringSlicingandJoining,StringMethods,FormattingStrings.

Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In
FunctionsUsed on Lists, List Methods, del Statement.

SampleExperiments:

1. Write a program to define a function with multiple returnvalues.


2. Write a program to define afunction using defaultarguments.
3. Write a program to find the length of the string withoutusing any libraryfunctions.
4. Write a program to check if the substring is present ina given string or not.
5. Write a program to perform the given operations on a list:
i. addition ii.insertion iii.slicing
6. Write a program to perform any5built-infunctions bytaking any list.

UNIT-III:

Dictionaries:Creating Dictionary,Accessing andModifyingkey:valuePairsin Dictionaries, Built-


In Functions Used on Dictionaries, Dictionary Methods, del Statement.

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

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
SampleExperiments: YEAR COURSE STRUCTURE & SYLLABUS)

1. Writeaprogramtosortwordsinafileandputtheminanotherfile.Theoutputfile should have


only lower-case words, so any upper-case words from source must be lowered.
2. Pythonprogramtoprinteachlineofafileinreverseorder.
3. Pythonprogramtocomputethenumberofcharacters,wordsandlinesinafile.
4. Writeaprogramtocreate,display,append,insertandreversetheorderoftheitems in the array.
5. Writeaprogramtoadd,transposeandmultiplytwomatrices.
6. Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
UNIT-V:

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

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
YEAR COURSE STRUCTURE & SYLLABUS)

1. Write a program to define a function with multiple return values.

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:

 The function calculate_stats takes a list of numbers.


 It calculates the total sum of the numbers, the count of the numbers, and their average.
 These values are returned as a tuple (total, count, average).
 When calling the function, you can unpack the returned tuple into separate variables ( total,
count, average) for easy access.

Output for the provided example:

makefile
Copy
Total: 150
Count: 5
Average: 30.0

2. Write a program to define afunction using default arguments.

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

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
YEAR COURSE STRUCTURE & SYLLABUS)
Here’s an example of how you can define a function with default arguments:

Example:

def greet(name="Guest", message="Welcome to the program!"):


print(f"Hello, {name}! {message}")

# 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

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
YEAR COURSE STRUCTURE & SYLLABUS)

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:

 The string_length function initializes a variable length to 0.


 It then iterates over each character in the string s.
 For each character, it increments the length variable by 1.
 Finally, the function returns the total length.

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!

4. Write a program to check if the substring is present ina given string or


not.

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

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
YEAR COURSE STRUCTURE & SYLLABUS)

Example:

def is_substring_present(main_string, substring):


# Loop through the main string
for i in range(len(main_string) - len(substring) + 1):
# Check if the substring matches the current slice of the main string
if main_string[i:i+len(substring)] == substring:
return True
return False

# 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!

5. Write a program to perform the given operations on a list:


i. Addition ii.insertion iii.slicing

Here's a Python program that demonstrates how to perform addition, insertion, and slicing
operations on a list:

41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA

KAKINADA – 533 003, Andhra Pradesh, India


ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
Program: YEAR COURSE STRUCTURE & SYLLABUS)

# Initialize an empty list


my_list = [1, 2, 3, 4, 5]

# i. Addition - Add elements to the end of the list


def add_elements(lst, elements):
lst.extend(elements)
return lst

# ii. Insertion - Insert an element at a specific position in the list


def insert_element(lst, position, element):
lst.insert(position, element)
return lst

# iii. Slicing - Extract a slice from the list


def slice_list(lst, start, end):
return lst[start:end]

# 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:

1. Addition (using extend):


o The add_elements function uses extend() to add multiple elements to the list.
o lst.extend(elements) adds all elements of the elements list to the end of lst.

2. Insertion (using insert):


o The insert_element function uses insert(position, element) to insert an
element at a specific position in the list.
o The element is inserted before the given index position.

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

KAKINADA – 533 003, Andhra Pradesh, India


o In Python, list slicing is done using lst[start:end].
ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
YEAR COURSE STRUCTURE & SYLLABUS)

Example Output:

List after addition: [1, 2, 3, 4, 5, 6, 7, 8]


List after insertion: [1, 2, 3, 9, 4, 5, 6, 7, 8]
Sliced list: [2, 3, 9, 4]

 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].

6. Write a program to perform any 5built-infunctions by taking any list.


# Sample list
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# 1. `len()` - Get the length of the list


length = len(my_list)

# 2. `sorted()` - Sort the list in ascending order


sorted_list = sorted(my_list)

# 3. `sum()` - Find the sum of elements in the list


list_sum = sum(my_list)

# 4. `max()` - Find the maximum value in the list


max_value = max(my_list)

# 5. `count()` - Count occurrences of a specific element in the list


count_of_fives = my_list.count(5)

# 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}")

Explanation of Built-in Functions:

1. len(): Returns the number of elements in the list.


2. sorted(): Returns a new sorted list without modifying the original list. It sorts the list in
ascending order by default.
3. sum(): Adds all the elements of the list and returns the total sum.
41
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITYKAKINADA

KAKINADA – 533 003, Andhra Pradesh, India


4. max(): Returns the largest element in the list.
ELECTRICAL AND ELECTRONICS ENGINEERING (R23-IInd
5. count(): Counts how many times a specific element appears in the list.
YEAR COURSE STRUCTURE & SYLLABUS)

Example Output:

Original List: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]


Length of the list: 11
Sorted List: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Sum of elements: 43
Maximum value in the list: 9
Count of element '5' in the list: 3

Summary:

 The list's length is 11.


 The list is sorted in ascending order.
 The sum of all elements in the list is 43.
 The maximum value in the list is 9.
 The element 5 appears 3 times in the list.

41

You might also like