0% found this document useful (0 votes)
4 views15 pages

Python Notes - Unit 2

Python1

Uploaded by

Ajay Kanna
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)
4 views15 pages

Python Notes - Unit 2

Python1

Uploaded by

Ajay Kanna
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
You are on page 1/ 15

S11BLH22 PYTHON PROGRAMMING

UNIT 2
FUNCTIONS AND STRINGS

Function Calls, Conversion of functions, Arguments, Fruitful Functions, Boolean functions,


Strings, Looping and Counting, String Operations.

Practice Programs :

1. Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error message if
the condition for input value is not followed.
2. Analyze the string similarity between two given strings using Python program
Sample Output: Sample Output:
Original string: Original string:
Python Exercise Python Exercises
Python Exercises Python Exercises

Funtions and Strings:

In Python, function calls are a way to execute a block of code that is defined within a function.
Functions are reusable pieces of code that can be called with different arguments to perform
specific tasks. Here's a basic overview of function calls in Python:

1. Defining a Function:
You define a function using the `def` keyword, followed by the function name, parameters (if
any), and a colon. The function body is indented.

def my_function(parameter1, parameter2):


# Function body
result = parameter1 + parameter2
return result

2. Calling a Function:
You call a function by using its name followed by parentheses. If the function has parameters,
you pass the values for those parameters inside the parentheses.

# Calling the function with arguments


result_value = my_function(10, 20)
print(result_value) # Output: 30

3. Return Statement:
Functions can return a value using the `return` statement. The value returned by the function
can be assigned to a variable or used directly.
def add_numbers(a, b):
sum_result = a + b
return sum_result

result = add_numbers(5, 7)
print(result) # Output: 12

4. Default Parameters:
You can provide default values for parameters in a function. If a value is not provided when
calling the function, the default value is used.

def greet(name, greeting="Hello"):


print(greeting, name)

greet("Alice") # Output: Hello Alice


greet("Bob", "Hi") # Output: Hi Bob

5. Arbitrary Number of Arguments:


You can use `*args` to allow a function to accept any number of positional arguments, or
`**kwargs` for any number of keyword arguments.

def print_arguments(*args, **kwargs):


print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

print_arguments(1, 2, 3, name="Alice", age=25)

These are some fundamental aspects of function calls in Python. Understanding and using
functions effectively can help organize your code and make it more modular and readable.

Conversion of functions:

Python allows you to do that using built-in functions like `lambda`, `map`, `filter`, and others.
Here are a few examples:

1. Using `lambda` function:


You can create an anonymous function using `lambda` and assign it to a variable.

def square(x):
return x ** 2

square_lambda = lambda x: x ** 2
2. Using `map` and `filter`:
You can use `map` and `filter` functions to apply a function to each element of an iterable or
filter elements based on a condition.

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

# Convert each element to its square using map


squared_numbers = list(map(lambda x: x ** 2, numbers))

# Filter even numbers using filter


even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

3. Function Composition:
You can create a new function by combining existing functions.

def add_one(x):
return x + 1

def multiply_by_two(x):
return x * 2

composed_function = lambda x: multiply_by_two(add_one(x))

These examples showcase different ways you might "convert" or create new functions in
Python. If you have a specific scenario or type of conversion in mind, please provide more
details for a more accurate response.

Arguments in Python:

In Python, function arguments are the values that you pass to a function when calling it. There
are several types of arguments in Python:

1. Positional Arguments:
These are the most common type of arguments. The order in which you pass them matters,
and they are assigned to the corresponding parameters in the order they are passed.

def add_numbers(a, b):


return a + b

result = add_numbers(3, 5)

2. Keyword Arguments:
You can also pass arguments by explicitly naming the parameter and providing the value. This
allows you to pass arguments out of order.
def greet(name, greeting):
return f"{greeting}, {name}!"

message = greet(greeting="Hello", name="Alice")

3. Default Values:
You can set default values for parameters, making them optional. If the caller doesn't provide
a value, the default will be used.

def greet(name, greeting="Hello"):


return f"{greeting}, {name}!"

message = greet("Bob") # Uses default greeting

4. Arbitrary Arguments:
You can use `*args` to allow a variable number of non-keyword arguments.

def print_values(*args):
for value in args:
print(value)

print_values(1, 2, 3, "four")

5. Keyword Arguments with `**kwargs`:


You can use `**kwargs` to allow a variable number of keyword arguments.

def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alice", age=30, city="Wonderland")

6. Unpacking Arguments:
You can unpack values from lists or dictionaries into function arguments using `*` and `**`
operators.

def add_numbers(a, b, c):


return a + b + c

values = [1, 2, 3]
result = add_numbers(*values)
Understanding these different types of arguments allows you to create flexible and reusable
functions in Python.

Fruitful function:
In Python, a "fruitful" function refers to a function that returns a value. This is in contrast to a
"void" or "non-fruitful" function, which performs a task but does not return a value. Fruitful
functions are often used when you need to compute a result and pass it back to the caller.

Here's an example of a fruitful function:

def add_numbers(a, b):


result = a + b
return result

sum_result = add_numbers(3, 5)
print(sum_result) # Output: 8

In this example, the `add_numbers` function takes two parameters (`a` and `b`), adds them
together, stores the result in a variable called `result`, and then returns this result. The caller (in
this case, the `print` statement) can use the returned value.

Fruitful functions are useful for encapsulating logic, promoting code reusability, and allowing you
to compute values in one part of your code and use them elsewhere.

Boolean functions in Python:

In Python, a boolean function typically refers to a function that returns a boolean value (`True` or
`False`). These functions are often designed to perform a test or check a condition and return
the result as a boolean. Here's an example:

def is_even(number):
return number % 2 == 0

result = is_even(4)
print(result) # Output: True

result = is_even(7)
print(result) # Output: False

In this example, the `is_even` function checks whether a given number is even or not. The
function returns `True` if the number is even and `False` otherwise.

Boolean functions are commonly used in decision-making processes, conditional statements,


and various programming constructs where you need to evaluate conditions and take different
actions based on the result.
Here's another example using a boolean function within an `if` statement:

def is_adult(age):
return age >= 18

user_age = 25

if is_adult(user_age):
print("You are an adult.")
else:
print("You are not an adult yet.")

In this case, the `is_adult` function checks if the given age is 18 or older and returns `True` if it
is, indicating that the user is an adult. The program then prints an appropriate message based
on the result of the boolean function.

Strings in Python:
In Python, strings are sequences of characters, and they are represented using single quotes
(`'`) or double quotes (`"`). Here are some basic operations and features related to strings in
Python:

1. Creating Strings:
You can create strings by enclosing characters within single or double quotes.

single_quoted_string = 'Hello, World!'


double_quoted_string = "Hello, World!"

2. Multiline Strings:
Triple quotes (`'''` or `"""`) are used for multiline strings.

multiline_string = '''This is a
multiline
string.'''

3. String Concatenation:
You can concatenate strings using the `+` operator.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name

4. String Repetition:
You can repeat a string using the `*` operator.
repeated_string = "abc" * 3 # results in "abcabcabc"

5. String Indexing and Slicing:


Strings can be indexed and sliced to extract specific characters or substrings.

my_string = "Python"
first_character = my_string[0] # 'P'
substring = my_string[1:4] # 'yth'

6. String Length:
The `len()` function can be used to get the length of a string.

length_of_string = len("Hello") # 5

7. String Methods:
Python provides a variety of built-in string methods for various operations, such as `upper()`,
`lower()`, `replace()`, `find()`, `split()`, and many more.

my_string = "Hello, World!"


uppercase_string = my_string.upper()
replaced_string = my_string.replace("Hello", "Hi")

8. Formatted Strings:
You can create formatted strings using f-strings or the `format()` method.

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."

These are just some of the basics of working with strings in Python. Strings in Python are
versatile and support a wide range of operations and manipulations.

Looping and counting in Python:


Looping and counting are fundamental concepts in programming, and Python provides several
ways to implement them. Here are examples of how to use loops and counting in Python:

Looping with `for`:

1. Basic Loop:

for i in range(5):
print(i)

Output:

0
1
2
3
4

2. Looping through a List:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

Output:

apple
banana
cherry

Counting with `range()`:

1. Counting Up:

for i in range(1, 6): # start from 1, stop at 6 (exclusive)


print(i)

Output:

1
2
3
4
5

2. Counting Down:

for i in range(5, 0, -1): # start from 5, stop at 0 (exclusive), step -1


print(i)

Output:

5
4
3
2
1

Looping and Counting with `while`:

count = 0
while count < 5:
print(count)
count += 1

Output:

0
1
2
3
4

Counting with `enumerate()`:

fruits = ["apple", "banana", "cherry"]


for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")

Output:

Index 0: apple
Index 1: banana
Index 2: cherry

These examples illustrate various ways to use loops and counting in Python. The `for` loop is
often used for iterating over sequences, while the `while` loop is useful when you need to loop
until a certain condition is met. The `range()` function is commonly employed for generating a
sequence of numbers for counting.

If you want to loop through and count strings in Python, you can use loops along with various
methods available for strings. Here's an example that demonstrates looping through a list of
strings and counting characters:

string_list = ["apple", "banana", "cherry"]

# Loop through the list of strings


for word in string_list:
print(f"String: {word}")

# Count and print the length of each string


length = len(word)
print(f"Length: {length}")
# Count and print the occurrences of a specific character (e.g., 'a')
count_a = word.count('a')
print(f"Count of 'a': {count_a}")

print("------")

This example uses a list of strings (`string_list`). It loops through each string, prints the string
itself, its length, and the count of a specific character ('a' in this case). You can modify this
example based on your specific counting requirements.

Output:

String: apple
Length: 5
Count of 'a': 1
------
String: banana
Length: 6
Count of 'a': 3
------
String: cherry
Length: 6
Count of 'a': 0
------

Adjust the specific counting logic inside the loop according to your needs, such as counting
occurrences of other characters or substrings.

String operations in python:

Strings in Python support various operations and methods for manipulation. Here are some
common string operations:

1. Concatenation:
Joining two or more strings together.

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)

Output:

Hello World
2. Repetition:
Repeating a string multiple times.

repeated_str = "abc" * 3
print(repeated_str)

Output:

abcabcabc

3. Indexing and Slicing:


Accessing specific characters or substrings in a string.

my_string = "Python"
first_char = my_string[0]
substring = my_string[1:4]
print(first_char, substring)

Output:

P yth

4. Length:
Getting the length of a string using the `len()` function.

length_of_string = len("Hello, World!")


print(length_of_string)

Output:

13

5. Lowercase and Uppercase:


Converting a string to lowercase or uppercase.

my_string = "Hello, World!"


lower_case = my_string.lower()
upper_case = my_string.upper()
print(lower_case, upper_case)
Output:

hello, world! HELLO, WORLD!

6. Checking Substrings:
Checking if a substring is present in a string.

sentence = "Python is powerful"


is_present = "is" in sentence
print(is_present)

Output:

True

7. Replacing Substrings:
Replacing a substring with another substring.

sentence = "Python is easy"


new_sentence = sentence.replace("easy", "awesome")
print(new_sentence)

Output:

Python is awesome

8. Splitting Strings:
Splitting a string into a list of substrings based on a delimiter.

sentence = "Python is versatile"


words = sentence.split(" ")
print(words)

Output:

['Python', 'is', 'versatile']

9. Stripping Whitespace:
Removing leading and trailing whitespace.
padded_string = " Python "
stripped_string = padded_string.strip()
print(stripped_string)

Output:

Python

These are just a few examples of the many operations and methods available for working with
strings in Python. Strings in Python are versatile and offer a rich set of tools for manipulation
and processing.

Exercise Problems:
1. Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error message if
the condition for input value is not followed.
Program:
def fibonacci(n):
if n <= 0:
raise ValueError("N should be greater than 0")
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

try:
# Accept input for N
n_value = int(input("Enter a value for N (where N > 0): "))

# Calculate and display the Nth Fibonacci number


result = fibonacci(n_value)
print(f"The {n_value}th Fibonacci number is: {result}")

except ValueError as ve:


print(f"Error: {ve}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

2. Analyze the string similarity between two given strings using Python program
Sample Output: Python Exercises
Original string:
Python Exercise
Python Exercises

Sample Output:
Original string:
Python Exercises
To analyze string similarity between two given strings, you can use various metrics such as
Levenshtein distance, Jaccard similarity, or difflib. Here, I'll provide an example using the difflib
module to calculate the similarity ratio between two strings. Note that difflib is more focused on
comparing sequences of strings.

Program:

from difflib import SequenceMatcher

def calculate_similarity(str1, str2):


# Create a SequenceMatcher object
matcher = SequenceMatcher(None, str1, str2)

# Get the similarity ratio


similarity_ratio = matcher.ratio()

return similarity_ratio

# Given strings
string1 = "Python Exercises"
string2 = "Python Exercise"

# Calculate similarity
similarity_ratio = calculate_similarity(string1, string2)

# Display the results


print("Original string 1:", string1)
print("Original string 2:", string2)
print("Similarity Ratio:", similarity_ratio)

In this example, the `calculate_similarity` function takes two strings as input and uses the
`SequenceMatcher` class from difflib to compute the similarity ratio between them. The
similarity ratio is a float between 0 and 1, where 1 means the strings are identical.

Output:

Original string 1: Python Exercises


Original string 2: Python Exercise
Similarity Ratio: 0.975

You can experiment with other similarity metrics or libraries based on your specific requirements.
Keep in mind that the choice of the metric depends on the type of similarity you're interested in
(character-level, token-level, etc.).

You might also like