0% found this document useful (0 votes)
5 views6 pages

Python Functions for Basic Operations

The document contains multiple Python code examples demonstrating various programming concepts. These include defining functions with multiple return values, using default arguments, calculating string length without library functions, checking for substrings, performing list operations (addition, insertion, slicing), and utilizing built-in list functions. Each example includes code snippets and descriptions of their functionality.

Uploaded by

vyshanavirayudu
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)
5 views6 pages

Python Functions for Basic Operations

The document contains multiple Python code examples demonstrating various programming concepts. These include defining functions with multiple return values, using default arguments, calculating string length without library functions, checking for substrings, performing list operations (addition, insertion, slicing), and utilizing built-in list functions. Each example includes code snippets and descriptions of their functionality.

Uploaded by

vyshanavirayudu
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

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

CODE :

def Basic_Calculator(x, y):


# Returns the sum, difference, and product of two numbers.
sum_result = x + y
difference_result = x - y
product_result = x * y
division_result=x/y
return sum_result, difference_result,
product_result,division_result
#Taking Numbers as Input
num1 = int(input("enter a num:"))
num2 = int(input("enter second num:"))
#Calling the function with multiple returnvalues
sum, difference, product,division = Basic_Calculator(num1, num2)
#printing the result
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Division:", division)

OUTPUT:

8. Write a program to define a function using default arguments.


CODE :

def greet(name, age=25, country='INDIA'):


print(f"Hello, {name}! You are {age} years old from {country}.")
# Calling the function with all arguments
greet("adithya", 30, "America")
# Calling the function with default age
greet("anurag", country="Canada")
# Calling the function with default age and country
greet("Bhargav")

OUTPUT:

9. Write a program to find the length of the string without using


any library functions.
CODE :

def length_of_string(s):
count = 0
for char in s:
if char == " ":
continue
else:
count += 1
return count
s = input("enter the string :")
print("Length of the string:",length_of_string(s))

Output:

10. Write a program to check if the substring is present in a given


string or not.
CODE :

#Function that checks for a given substring in a string


def find_substring(s, sub):
s_len = len(s)
sub_len = len(sub)
for i in range(s_len - sub_len + 1):
if s[i:i+sub_len] == sub:
return True
return False

#Taking the string and substring as inputs


s = input("enter a string ")
sub = input("enter a sub string ")
#Printing the Results
if find_substring(s, sub):

print(f"The substring '{sub}' is present in the string '{s}'.")


else:
print(f"The substring '{sub}' is not present in the string
'{s}'.")
Output :

[Link] a program to perform the given operations on a list:


i. Addition ii. Insertion iii. slicing
CODE :

# Define a list
my_list = [1, 2, 3, 4, 5]
print("Original List:", my_list)
# i. Addition: append an element to the end of the list
i=int(input("Enter element to be added in the list "))
my_list.append(i)
print("After addition:", my_list)
# ii. Insertion: insert an element at a specific position
j=int(input("Enter element to be inserted in the list "))
k=int(input("Enter the position of the element to be inserted in the
list "))
my_list.insert(k,j)
print("After insertion:", my_list)
# iii. Slicing: extract a subset of elements from the list
l=int(input("Enter starting index of slicing "))
m=int(input("Enter finishing index of slicing "))
sliced_list = my_list[l:m]
print("Sliced list:", sliced_list)

OUTPUT:

12. Write a program to perform any 5 built-in functions by taking


any list.
CODE :

# Define a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original List:", my_list)

# 1. len() function: returns the length of the list


print("Length of the list:", len(my_list))

# 2. max() function: returns the maximum value in the list


print("Maximum value in the list:", max(my_list))

# 3. min() function: returns the minimum value in the list


print("Minimum value in the list:", min(my_list))

# 4. sum() function: returns the sum of all values in the list


print("Sum of all values in the list:", __builtins__.sum(my_list))

# 5. sorted() function: returns a new sorted list


print("Sorted list:", sorted(my_list))

OUTPUT:

Common questions

Powered by AI

Built-in functions such as `len()`, `max()`, `min()`, `sum()`, and `sorted()` in Source 2 encapsulate complex operations in concise calls, improving code efficiency by avoiding manual implementations. They enhance readability by clearly conveying their intended functionality, making code easier to understand and maintain, while leveraging optimized implementations provided by Python's standard library .

The function in Source 1, `Basic_Calculator`, performs arithmetic operations (sum, difference, product, and division) on two input numbers and returns all these results as multiple outputs using a single return statement. This allows for efficient use of the function to compute and access multiple related results simultaneously, improving code modularity and reducing the need for multiple function calls to perform each operation separately .

Implementing a substring search through a custom function, as shown in Source 1, challenges developers to develop a deeper understanding of string manipulation while potentially leading to higher complexity and error rates. Built-in methods like `in` use optimized search algorithms, providing better performance and reliability without requiring deep algorithmic knowledge. Custom implementations provide learning opportunities but might not match the efficiency and reliability of built-in methods .

Using built-in functions `max()` and `min()` (as shown in Source 2) efficiently finds maximum and minimum values due to their optimized underlying algorithms. In contrast, manual searching requires iterating through each list element to compare values, resulting in more verbose code and potentially higher error rates. Built-in functions leverage Python's internal efficiencies, offering succinct syntax and often superior performance .

The substring search function in Source 1 iterates over the main string, checking each substring of equivalent length to the search string for equality. This method, while simple and instructive, has a time complexity of O(n*m), where n is the length of the main string and m is the length of the substring. This approach is straightforward but can be inefficient for large strings compared to more advanced algorithms like the KMP algorithm .

Programmatic determination of a string's length, as shown by the custom `length_of_string` function in Source 1, allows for a deeper understanding of string manipulation and avoids the dependency on library functions, which may be restricted or unavailable in certain environments. This method also illustrates fundamental programming skills, beneficial for educational purposes and low-level optimizations .

Source 1 demonstrates three operations on a list: addition (using `append`), which adds an element to the end of the list; insertion, which places an element at a specified position; and slicing, which extracts a subset from the list. These operations respectively expand, modify, and allow access to multiple elements in customized parts of the list, modifying its structure and content .

List slicing, as demonstrated in Source 1, is beneficial when a portion of the data needs to be extracted for analysis, such as partitioning data for batch processing or filtering specific records within dataset subsets. Slicing creates a new list, allowing manipulation of segments without altering the original list, which is essential in data processing scenarios where integrity of original data should be preserved .

Default arguments in function definitions enhance flexibility and provide default behavior when certain arguments are not supplied. Source 1 illustrates this with the `greet` function, where age defaults to 25 and country to 'INDIA.' This allows function calls without all parameters, as seen in calls like `greet("Bhargav")`, reducing complexity and making the function versatile for various use cases without overloading .

The function in Source 1 can be optimized to handle division by zero by checking if the divisor is zero before performing the division operation. A revised version of the function would include a conditional check that returns a specific value or error message when division by zero is detected. Example: ``` def Basic_Calculator(x, y): sum_result = x + y difference_result = x - y product_result = x * y division_result = 'undefined' if y == 0 else x / y return sum_result, difference_result, product_result, division_result ``` This prevents runtime errors and provides clearer feedback in case of invalid inputs .

You might also like