0% found this document useful (0 votes)
10 views

Python Day- 6

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Day- 6

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Python Day- 6

(RECAP OF PREVIOUS DAY)

Introduction to functions and function calls, Function arguments (positional, default, keyword,
arbitrary arguments), Mutability and immutability, Built-in functions. Problems on above
concepts.

Introduction to Functions and Function Calls

Function

A function is a block of reusable code that performs a specific task. Functions help in
modularizing code, making it more readable, reusable, and easier to debug.

● A function is a block of organized, reusable code that is used to perform a single, related
action.
● Functions provide better modularity for your application and a high degree of code reusing.
● There are two types of functions in Python: Built-in functions and User defined functions
● Python gives many built in functions like print(), len() etc. But we can also create our own
functions. These functions are called user defined functions.

Why Use Functions?

● Code Reusability: Write once, use multiple times.


● Modularity: Break down complex problems into smaller, manageable parts.
● Improved Readability: Clear structure makes the code easier to understand.
● Ease of Debugging: Isolate issues within smaller blocks of code.

Syntax of a Function in Python:

# Function definition
def function_name(parameters):
"""Optional docstring to describe the function."""
# Function body
return value # Optional

# Function call
function_name(arguments)

Creating a Function
Function for addition of two numbers:

Note: a,b are called formal arguments while x, y are called actual arguments.

Return Multiple Values


You can also return multiple values from a function. Use the return statement by separating
each expression by a comma.
Arguments(or Parameters) in Function
There are the following types of arguments in Python.
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable-length positional arguments
5. Variable-length keyword arguments

Positional Arguments
● During function call, values passed through arguments should be in the order of
parameters in the function definition. This is called positional arguments.
● By default, a function must be called with the correct number of arguments.
● Meaning that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
keyword arguments

● We can also send arguments with the key = value syntax.


● This way the order of the arguments does not matter.
● Keyword arguments are related to the function calls
● The caller identifies the arguments by the parameter name.
● This allows to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters.

Default Arguments

● Default arguments are values that are provided while defining functions.
● The assignment operator = is used to assign a default value to the argument.
● Default arguments become optional during the function calls.
● If we provide value to the default arguments during function calls, it overrides the default
value.
● Default arguments should follow non-default arguments.
● If we call the function without argument, it uses the default value.
Variable-length positional arguments
● Variable-length arguments are also known as Arbitrary arguments.
● If we don’t know the number of arguments needed for the function in advance, we can
use arbitrary arguments
● For arbitrary positional argument, an asterisk (*) is placed before a parameter in function
definition which can hold non-keyword variable-length arguments.
● These arguments will be wrapped up in a tuple. Before the variable number of
arguments, zero or more normal arguments may occur.
Syntax:
def functionname(*var_args_tuple ):
function_statements
return [expression]
Variable length Keyword Arguments

● If you do not know how many keyword arguments that will be passed into your function,
add two asterisk (**) before the parameter name in the function definition.
● This way the function will receive a dictionary of arguments, and can access the items
accordingly.

Mutability and Immutability

What is Mutability?

● Mutable Objects: Objects that can be changed after creation.


○ Examples: Lists, Dictionaries, Sets
● Immutable Objects: Objects that cannot be changed after creation.
○ Examples: Strings, Tuples, Integers, Floats

Examples:

Mutable Example (List):

my_list = [1, 2, 3]
my_list[0] = 10
print(my_list) # Output: [10, 2, 3]

Immutable Example (String):

my_string = "hello"
# my_string[0] = "H" # Error: Strings are immutable

my_string = "Hello" # Reassignment creates a new object

print(my_string) # Output: Hello

Functions and Mutability:

● Mutable objects can be modified within functions.


● Immutable objects cannot be modified but can be reassigned.

Example:

def modify_list(lst):
lst.append(4) # Modifies the original list

my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]

Built-in Functions
Python provides a wide range of built-in functions that are ready to use. Some commonly used
ones include:

Examples:

6. Mathematical Functions:

a. abs(x): Absolute value of x.


b. max(iterable): Largest item.
c. min(iterable): Smallest item.
d. sum(iterable): Sum of all items.
# Example usage of abs()
number = -10
absolute_value = abs(number)
print(f"The absolute value of {number} is {absolute_value}")

# Example usage of max()


numbers_list = [4, 7, 1, 9, 3]
largest_number = max(numbers_list)
print(f"The largest number in the list {numbers_list} is {largest_number}")

# Example usage of min()


smallest_number = min(numbers_list)
print(f"The smallest number in the list {numbers_list} is {smallest_number}")

# Example usage of sum()


total = sum(numbers_list)
print(f"The sum of all numbers in the list {numbers_list} is {total}")

7. Type Conversion Functions:

a. int(x): Converts x to an integer.


b. float(x): Converts x to a float.
c. str(x): Converts x to a string.

# Example usage of int()


string_number = "42"
integer_value = int(string_number)
print(f"The string '{string_number}' converted to an integer is {integer_value}")

# Example usage of float()


integer_number = 10
float_value = float(integer_number)
print(f"The integer {integer_number} converted to a float is {float_value}")

# Example usage of str()


number = 3.14
string_value = str(number)
print(f"The float {number} converted to a string is '{string_value}'")

# Combining conversions
mixed_string = "123.45"
converted_float = float(mixed_string)
converted_int = int(float(mixed_string)) # Converts to float first, then to int
print(f"The string '{mixed_string}' converted to a float is {converted_float}, and to an
integer is {converted_int}")

8. Input/Output Functions:

a. input(prompt): Takes input from the user.


b. print(value): Prints to the console.

# Taking input from the user


name = input("Enter your name: ")
age = input("Enter your age: ")

# Printing the input values


print(f"Hello, {name}! You are {age} years old.")

9. Iterables and Collections:

a. len(x): Returns the number of items.


b. sorted(iterable): Returns a sorted list.
c. range(start, stop, step): Generates a sequence of numbers.

# Example usage of len()


fruits = ["apple", "banana", "cherry", "date"]
length = len(fruits)
print(f"The list of fruits is {fruits}, and it contains {length} items.")

# Example usage of sorted()


unsorted_numbers = [5, 3, 8, 1, 2]
sorted_numbers = sorted(unsorted_numbers)
print(f"The unsorted list is {unsorted_numbers}. The sorted list is
{sorted_numbers}.")

# Example usage of range()


start = 1
stop = 10
step = 2
number_sequence = list(range(start, stop, step))
print(f"The range from {start} to {stop} with a step of {step} is: {number_sequence}")

10. Other Useful Functions:

a. type(x): Returns the type of x.


b. id(x): Returns the memory address of x.
c. help(obj): Displays documentation for obj.

# Example usage of type()


number = 42
text = "Hello, World!"
print(f"The type of {number} is {type(number)}")
print(f"The type of '{text}' is {type(text)}")

# Example usage of id()


x = 10
y = 10
print(f"The memory address of x (value {x}) is {id(x)}")
print(f"The memory address of y (value {y}) is {id(y)}")

# Example usage of help()


print("\nDocumentation for the built-in len() function:")
help(len)

Problems on Functions
1. Write a function to find the factorial of a number.

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

num = 5
result = factorial(num)
print(f"Factorial of {num} is {result}")

2. Write a function to check if a number is prime.

def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

print(is_prime(7)) # Output: True

3. Write a function to calculate the nth Fibonacci number using


recursion.

def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6)) # Output: 8

4. Find sum of digits.

def sum_of_digits(n):
"""Calculate the sum of the digits of a number."""
return sum(int(digit) for digit in str(n))

# Test the function


print(sum_of_digits(1234)) # Output: 10 (1 + 2 + 3 + 4)
Explanation: sum(int(digit) for digit in str(n)), here each digit in str(n) is type casted in int
and then being summed up.

5. Check Palindrome.

def is_palindrome(s):
return s == s[::-1]

# Test the function


print(is_palindrome("radar")) # Output: True
print(is_palindrome("hello")) # Output: False
6. Write a function to Find GCD of Two Numbers.

def gcd(a, b):


while b:
a, b = b, a % b # a=b and b = a%b
return a

# Test the function


print(gcd(12, 18)) # Output: 6

7. Count Vowels in a String.

def count_vowels(s):
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels)

# Test the function


print(count_vowels("hello world")) # Output: 3

8. Check Armstrong Number.

def is_armstrong(n):
num_str = str(n)
num_digits = len(num_str)
return sum(int(digit) ** num_digits for digit in num_str) == n

# Test the function


print(is_armstrong(153)) # Output: True
print(is_armstrong(123)) # Output: False

List of programs to practice (Home work)

9. Generate a List of Prime Numbers Write a function generate_primes(n)


that returns a list of all prime numbers less than or equal to n.
10. Check Armstrong Number Write a function is_armstrong(num) that checks
if a number is an Armstrong number. (An Armstrong number of 3 digits is a
number such that the sum of its digits raised to the power of 3 equals the number
itself, e.g., 153.)
11. Write a function convert_temperature(temp, to_scale) that converts a
temperature from Celsius to Fahrenheit or Fahrenheit to Celsius based on the
value of to_scale. Use the formulas:
12. Write a function find_divisors(num) that returns a list of all divisors of a
given number num.
13. Write a function is_perfect(num) to check whether a number is a perfect
number. (A perfect number is a positive integer that is equal to the sum of its
proper divisors, e.g., 6 = 1 + 2 + 3.)
14. Check if Two Strings are Anagrams: Write a function are_anagrams(s1,
s2) to check if two strings are anagrams of each other.
(Two strings are anagrams if they contain the same characters in different orders,
e.g., "listen" and "silent".)
15. Find the Longest Word in a Sentence: Write a function
longest_word(sentence) that takes a sentence as input and returns the
longest word in the sentence.
16. Check for Strong Number: Write a function is_strong(num) to check if a
number is a strong number.
(A strong number is a number such that the sum of the factorials of its digits
equals the number itself, e.g., 145 = 1! + 4! + 5!.)
17. Write a program to find the factorial of given number using function.
18. Write a program using function to Find the Average of Three Numbers.
19. Write a program using function to Calculate Sum of 5 Subjects and Find
Percentage.
20. Write a program using function to Calculate Area of Circle.
21. Write a program using function to Calculate Area of Rectangle.
22. Write a program using function to Calculate Area and Circumference of Circle.
23. Write a program using function to Calculate Area of Scalene Triangle.
24. Write a program using function to Calculate Area of Right angle Triangle.
25. Write a program using function to find the area of parallelogram.
26. Write a program using function to find the volume and surface area of cube.
27. Write a program using function to find the volume and surface area of cylinder.

You might also like